<?PHP

class model extends engine{

	var $call_sql_class = array('templates', 'roles', 'permissions', 'menus', 'settings', 'redirect_link', 'elements');
	var $clone_class = array(
		array('templates' => 'models'),
		array('templates' => 'pages'),
		array('menus' => 'main_menus')
	);
	var $call_class = array('File', 'Obj', 'ArrayClass', 'modelGenerator', 'Zip', 'Curl', 'Form', 'dragAndDrop');
	var $core_link = false;

	function get_menu_data(){

		$this->recursive_menu('', 0);

		$this->main_menus->columns("(SELECT name FROM menus AS p1 WHERE p1.id = menus.parent_id) AS parent_name")->append();
		$this->main_menus->dataSeek();
		$this->main_menus->Select("WHERE is_public = 0 ORDER BY name");
		return $this;
	}
	function recursive_menu($position, $id, $counter = 1){

		$this->menus->columns("(SELECT name FROM menus AS p1 WHERE p1.id = menus.parent_id) AS parent_name, (SELECT 1 FROM menus AS p1 WHERE EXISTS(SELECT 1 FROM menus AS p2 WHERE p2.parent_id = p1.id) AND p1.id = menus.id LIMIT 1) AS is_main")->append();
		$this->menus->Select("WHERE is_public = 0 AND parent_id = ".$id." ORDER BY queue");
		$result = $this->menus->Result;
		while($row = mysqli_fetch_Assoc($result)){

			$row['counter'] = $counter;
			$this->menus->Rows[] = $row;
			$this->recursive_menu($position, $row['id'], $counter+1);
		}
	}

	function get_elements_data(){

		$this->roles->Select();

		$this->elements->elements();
		return $this;
	}
	function get_export_db_data(){

		if($_GET['type'] == 'model'){

			$this->templates->useMethod(array($this, 'get_additional_data'));
			$this->templates->Select("WHERE name = '".$_GET['model_name']."' ");
		}
		if($_GET['type'] == 'page'){

			$this->templates->useMethod(array($this, 'get_additional_data'));
			$this->templates->Select("WHERE name = '".$_GET['model_name']."' AND page = '".$_GET['page_name']."' ");
		}
		return $this;
	}

	function get_additional_data($row){

		$this->menus->Select("WHERE model_id = ".$row['id']." AND is_public = 0", true);
		$this->permissions->Select("WHERE table_name = 'templates' AND table_id = ".$row['id'], true);
	}
	function get_model_data(){

		$this->banners->Select();
		return $this;
	}
	function get_plugins_data(){

		$this->templates->useMethod(array($this, 'get_plugins_permissions'));
		$this->templates->Select("WHERE type = 'PLUGIN' ");

		$this->roles->dataSeek();
		$this->roles->roles();
		return $this;
	}

	function get_plugins_permissions($row){

		$this->permissions->permissions_and_roles("WHERE table_name = 'templates' and table_id = ".$row['id']." ORDER BY p2.name ", true);
		if(is_Array($this->permissions->Rows)){

			foreach($this->permissions->Rows as $v){

				$row['roles'] .= $row['roles'] ? ', '.$v['name'] : $v['name'];
			}
		}
		return $row;
	}


	function get_queue_data(){

		$this->templates->templates("WHERE type = 'MODEL' ORDER BY page_position, position, name ");

		return $this;
	}

	function get_database_data(){

		$rows = $this->Sql->Query("SHOW TABLES FROM ".constant('sqlconf[database]'), true);
		$this->tables = new stdClass();
		$this->tables->Rows = $rows;

		return $this;
	}

	function get_table_columns(){

		$rows = $this->Sql->Query("SHOW COLUMNS FROM ".constant('sqlconf[database]').".".$_GET['mysql_table'], true);
		$this->table_columns = $rows;

		$this->Page('table_columns');
		exit;
	}

	function get_manage_data(){

		$this->file_list = $this->Curl->SendCurl('http://www.projectpartner.ee/scripts/models.php');

		return $this;
	}

	function models(){

		$this->models->useMethod(array($this, 'model_pages'));
		$this->models->models();

		$this->menus->columns("menus.id as menu_id, menus.name, templates.id as template_id");
		$this->menus->menus("JOIN templates ON templates.id=menus.model_id
		WHERE menus.is_restricted = 1 ".
		"ORDER BY menus.name ");

		$this->roles->dataSeek();
		$this->roles->roles();

		$this->File->GetAllFiles(_CurrentTemplate.'/form/views/');

		return $this;
	}

	function model_pages($row){

		$this->pages->useMethod(array($this, 'pages'));
		$this->pages->templates("WHERE type = 'MODEL' AND  name = '".$row['name']."' ORDER BY page ");
	}

	function pages($row){

		$this->menus->menus("WHERE model_id = ".$row['id'], true);
		$row['menu'] = $this->menus->Rows[0]['name'];
		$row['menu_parent_id'] = $this->menus->Rows[0]['parent_id'];

		$this->menus->columns("menus.id as menu_id, menus.name, templates.id as template_id");
		$this->menus->menus("JOIN templates ON templates.id=menus.model_id
		WHERE menus.is_restricted = 1 ORDER BY menus.name ");

		$this->permissions->permissions_and_roles("WHERE table_name = 'templates' and table_id = ".$row['id']." GROUP BY p2.id  ORDER BY p2.name ", true);

		if(is_Array($this->permissions->Rows)){

			foreach($this->permissions->Rows as $v){

				$row['roles'] .= $row['roles'] ? ', '.$v['name'] : $v['name'];
			}
		}

		if($row['is_static'] == 1)
			$row['is_static_text'] = $this->Language('true');
		else
			$row['is_static_text'] = $this->Language('false');

		if($row['is_first_page'] == 1)
			$row['is_first_page_text'] = $this->Language('true');
		else
			$row['is_first_page_text'] = $this->Language('false');

		return $row;
	}

	function menu(){

		$this->recurisive_menu();
		return $this;
	}
	function recurisive_menu($parent_id=0, $counter=0){

		$this->menus->menus("WHERE language = '".$_SESSION['language']."' and parent_id=".$parent_id." and is_public = 0 ".
			"ORDER by queue ");

		if($this->menus->Numrows > 0){

			while ($row = $this->menus->Assoc()){

				$row['counter'] = $counter;
				$row['space'] = str_repeat('&nbsp;&nbsp;', $counter);
				$this->MenuList[] = $row;
				$this->recurisive_menu($row['id'], ($counter+1));
			}
		}
	}

	function edit(){

		$this->menus->menus(
			"WHERE id =".$_GET['id']." ");

		$this->main_menus->menus("WHERE language = '".$_SESSION['language']."' and is_public = 0 ".
			"ORDER by name ");

		$this->models->useMethod(array($this, 'pages_list'));
		$this->models->templates("WHERE type = 'MODEL' ".
			"GROUP BY name ".
			"ORDER BY name ");
		return $this;
	}

	function pages_list($row){

		$this->pages->templates("WHERE type = 'MODEL' and name = '".$row['name']."' ");
	}

	function if_table_not_exists($table){

		if( !file_Exists(_RootFolder.'/app/querys/'.$table.'.php') ){

			return true;
		}
		return false;
	}

	function new_version_exists(){

		$this->get_manage_data();
		$exp = explode("\n", str_replace('.zip', '', $this->file_list));
		$update = false;

		foreach($exp as $v){

			if($v){

				$version = 0;

				$check = explode('_v_', $v);
				$model = $check[0];
				$model_list .= $model_list ? ",'".$model."'" : "'".$model."'";
				$version = str_replace('_', '.', $check[1]);

				$this->templates->templates("WHERE type IN('MODEL', 'CORE') and name = '".$model."' GROUP BY name ORDER BY name ");
				$row = $this->templates->Assoc();

				if((float)$version > (float)$row['version']){

					$update = true;
					break;
				}
			}
		}
		return $update;
	}

	//updates

	function update_element(){

		$this->permissions->Delete("WHERE table_name = 'elements' and table_id = ".$_GET['id']);
		if($_POST['access']){

			foreach($_POST['access'] as $v){

				$this->permissions->Insert(array(
					'role_id'	 => $v,
					'table_name' => 'elements',
					'table_id' => $_GET['id'],
					'created_at' => 'NOW()'
				));
			}
		}
	}

	function update_queue(){

		foreach($_POST['queue'] as $id => $queue){

			$this->templates->Update(array('queue' => $queue), "WHERE id = ".$id);
		}
	}

	function activate(){

		$this->templates->Update(array('is_active' => ($_GET['is_active'] == 1 ? 0 : 1) ), "WHERE id = ".$_GET['id']);
		$this->menus->Update(array('is_enabled' => ($_GET['is_active'] == 1 ? 0 : 1) ), "WHERE model_id = ".$_GET['id']);
	}

	function add(){

		$_POST['language'] = $_SESSION['language'];
		$_POST['type'] = $_POST['type'] ? $_POST['type'] : 'MODEL';
		$_POST['version'] = 1;
		unset($_POST['id']);

		$this->templates->insert($_POST);
		$Insertid = $this->templates->Insertid;
		if($_POST['type'] == 'MODEL')
			$this->create_or_update_model($_POST['name'], $_POST['page'], $_POST['page_position'], 'insert');


		if($_POST['menu']){

			$this->update_menu($Insertid, $_POST['menu']);
		}

		if(is_array($_POST['roles'])){

			foreach($_POST['roles'] as $v){

				$this->permissions->Insert(array(
					'role_id'	 => $v,
					'table_name' => 'templates',
					'table_id' => $Insertid,
					'created_at' => 'NOW()'
				));
			}
		}
	}

	function update(){

		$_POST['type'] = $_POST['type'] ? $_POST['type'] : 'MODEL';

		$this->templates->Update($_POST, "WHERE id = ".$_POST['id']);
		if($_POST['type'] == 'MODEL')
			$this->create_or_update_model($_POST['name'], $_POST['page'], $_POST['page_position'], 'update');

		$this->permissions->Delete("WHERE table_name = 'templates' and table_id = ".$_POST['id']);

		foreach($_POST['roles'] as $v){

			$this->permissions->Insert(array(
				'role_id'	 => $v,
				'table_name' => 'templates',
				'table_id' => $_POST['id'],
				'created_at' => 'NOW()'
			));
		}
		if($_POST['menu']){

			$this->update_menu($_POST['id'], $_POST['menu']);
		}
	}

	function update_menu($model_id, $name){

		$this->menus->menus("WHERE model_id = ".$model_id);
		$row = $this->menus->Assoc();
		if($this->menus->Numrows > 0){

			if($row['is_public'])
				$this->menus->Update(array('name' => $name), "WHERE model_id = ".$model_id);
			else
				$this->menus->Update(array('name' => $name, 'parent_id' => $_POST['model_parent_id']), "WHERE model_id = ".$model_id);
		}
		else{

			$this->menus->menus("WHERE is_public = 0 ".
			"ORDER BY queue asc ".
			"LIMIT 1", true);
			$queue = ($this->menus->Rows[0]['queue']+1);

			$array = array(
				'parent_id' => $_POST['model_parent_id'],
				'model_id'	 => $model_id,
				'name' => $name,
				'language' => $_SESSION['language'],
				'queue' => $queue,
				'is_public' => '0',
				'is_enabled' => 1,
				'is_restricted' => 1,
				'created_at' => 'NOW()'
			);

			$this->menus->Insert($array);
		}
	}

	function delete(){

		$this->permissions->Delete("WHERE table_name = 'templates' and table_id = ".$_GET['id']);
		$this->templates->Delete("WHERE id = ".$_GET['id']);
		$this->menus->Delete("WHERE model_id = ".$_GET['id']." ");
		$this->menus->Update(array('model_id' => 0), "WHERE model_id = ".$_GET['id']." ");
	}

	function delete_model(){

		$this->templates->templates("WHERE name = '".$_GET['name']."' and type = 'MODEL' ", true);

		if(!empty($this->templates->Rows)){

			foreach($this->templates->Rows as $v){

				$_GET['id'] = $v['id'];
				$this->delete();
			}
		}
	}

	//MODELS
	function set_permission(){

		$this->Sql->Query('', file_get_contents(_QueryFolder.'/'.$_POST['cmodel'].'_tables.sql'), true);
		$exp = explode("\n", file_get_contents(_QueryFolder.'/'.$_POST['cmodel'].'_set_permissions.sql'));
		foreach($exp as $v){

			if(!empty($v)){

				$this->Sql->Query('', $v, true);
				foreach($_POST['role_id'] as $v_r){

					$array = array(
						'role_id' => $v_r,
						'table_name' => 'templates',
						'table_id' => $this->Sql->Insertid,
						'created_at' => 'NOW()'
					);
					$this->permissions->Insert($array);
				}
			}
		}
		die($this->Redirect('./'));
	}

	function models_access(){

		$this->templates->templates("WHERE name = '".$_POST['model_name']."' and type = 'MODEL' ", true);

		foreach($this->templates->Rows as $v){

			$this->permissions->Delete("WHERE table_name = 'templates' and table_id = ".$v['id']);

			foreach($_POST['roles'] as $role){

				$this->permissions->Insert(array(
					'role_id'	 => $role,
					'table_name' => 'templates',
					'table_id' => $v['id'],
					'created_at' => 'NOW()'
				));
			}
		}
	}

	function create_or_update_model($model, $page, $position, $method){

		if(!is_dir(_RootFolder.'/app/models/'.$model))
			mkdir(_RootFolder.'/app/models/'.$model);

		$model_file = _RootFolder.'/app/models/'.$model.'/index.php';
		$controller_file = _RootFolder.'/app/models/'.$model.'/controller.php';
		$mysql_table = $_POST['mysql_table'];

		$view_folder = '/';
		$view_admin_folder = '/';
		if(preg_match('/admin/i', $position) && !preg_match('/public/i', $position)){

			$view_folder = 'admin/';
			$view_admin_folder = 'admin/';
		}
		if(preg_match('/admin/i', $position) && preg_match('/public/i', $position)){

			$view_admin_folder = 'admin/';
		}

		$view_file = _RootFolder.'/app/models/'.$model.'/views/'.$view_folder.$page.'.php';
		$view_file_edit = _RootFolder.'/app/models/'.$model.'/views/'.$view_folder.'edit.php';
		$view_ajax_file = _RootFolder.'/app/models/'.$model.'/views/'.$view_folder.'ajax_'.$page.'.php';

		$view_admin_file = _RootFolder.'/app/models/'.$model.'/views/'.$view_admin_folder.$page.'.php';
		$view_admin_ajax_file = _RootFolder.'/app/models/'.$model.'/views/'.$view_admin_folder.'ajax_'.$page.'.php';

		//add files
		if(!is_file($controller_file)){

			$php = preg_replace_callback('/{([a-zA-Z_]+)}/', function( $matches ) use ( $model, $page, $mysql_table ) {return $$matches[1];}, file_get_contents(_CurrentTemplate.'/form/controller.tpl'));
			if($_POST['add_ajax_options']){

				$php = str_replace('$this->'.$mysql_table.'->'.$mysql_table.'("");', '', $php);
			}
			file_put_contents($controller_file, $php);
		}
		if(!is_file($model_file)){

			$php = preg_replace_callback('/{([a-zA-Z_]+)}/', function( $matches ) use ( $model, $page, $mysql_table ) {return $$matches[1];}, file_get_contents(_CurrentTemplate.'/form/model.tpl'));
			file_put_contents($model_file, $php);
		}
		if(!is_file($view_file) && !is_file($view_admin_file)){

			if(preg_match('/admin/i', $position)){

				//REGULAR VIEW
				$php = $this->createView($_POST['view']);

				$this->File->WriteDirectorRecursive(dirname($view_file));
				file_put_contents($view_file, $php);
				if( preg_match('/_edit/i', $_POST['view']) ){

					$php = $this->createView('edit');
					if(!is_file($view_file_edit))
						file_put_contents($view_file_edit, $php);
				}

				if($_POST['add_ajax_options']){

					//AJAX VIEW AND MODEL AND CONTROLLER
					$php = '';
					$this->File->WriteDirectorRecursive(dirname($view_ajax_file));
					file_put_contents($view_ajax_file, $php);
					$tmp_page = $page;
					$page = 'ajax_'.$tmp_page;

					if($method == 'insert'){

						$_POST['page'] = $page;
						$_POST['version'] = 1;
						$this->templates->insert($_POST);
						foreach($_POST['roles'] as $v){

							$this->permissions->Insert(array(
								'role_id'	 => $v,
								'table_name' => 'templates',
								'table_id' => $this->templates->Insertid,
								'created_at' => 'NOW()'
							));
						}
					}

					//model
					$php = preg_replace_callback('/{([a-zA-Z_]+)}/', function( $matches ) use ( $model, $page, $mysql_table ) {return $$matches[1];}, file_get_contents(_CurrentTemplate.'/form/model_method.tpl'));
					$php = str_replace("->Page('".$page."');", ';', $php);
					if(!preg_match('/function '.$page.'\(/i', file_get_contents($model_file))){

						$this->append_function($model_file, $php);
					}

					//controller
					$php = preg_replace_callback('/{([a-zA-Z_]+)}/', function( $matches ) use ( $model, $page, $mysql_table ) {return $$matches[1];}, file_get_contents(_CurrentTemplate.'/form/controller_method.tpl'));
					if(!preg_match('/function get_'.$page.'_data\(/i', file_get_contents($controller_file))){

						$this->append_function($controller_file, $php);
					}
					$page = $tmp_page;
				}
				else{

					$php = $this->createView($_POST['view']);
					$this->File->WriteDirectorRecursive(dirname($view_file));
					file_put_contents($view_file, $php);
					if( preg_match('/_edit/i', $_POST['view']) ){

						$php = $this->createView('edit');
						if(!is_file($view_file_edit))
							file_put_contents($view_file_edit, $php);
					}
				}
			}
			else{

				$php = $this->createView($_POST['view']);
				$this->File->WriteDirectorRecursive(dirname($view_file));
				file_put_contents($view_file, $php);
				if( preg_match('/_edit/i', $_POST['view']) ){

					$php = $this->createView('edit');
					if(!is_file($view_file_edit))
						file_put_contents($view_file_edit, $php);
				}
			}
			if(!is_file(_RootFolder.'/app/models/'.$model.'/views/.htaccess'))
				file_put_contents(_RootFolder.'/app/models/'.$model.'/views/.htaccess', "<Files *.php>\ndeny from all\n</Files>\n<Files *.tpl>\ndeny from all\n</Files>");
		}


		//update files
		if(is_file($model_file)){

			$php = preg_replace_callback('/{([a-zA-Z_]+)}/', function( $matches ) use ( $model, $page, $mysql_table ) {return $$matches[1];}, file_get_contents(_CurrentTemplate.'/form/model_method.tpl'));
			if(!preg_match('/function '.$page.'\(/i', file_get_contents($model_file))){

				$this->append_function($model_file, $php);
			}
		}
		if(is_file($controller_file)){

			$php = preg_replace_callback('/{([a-zA-Z_]+)}/', function( $matches ) use ( $model, $page, $mysql_table ) {return $$matches[1];}, file_get_contents(_CurrentTemplate.'/form/controller_method.tpl'));
			if(!preg_match('/function get_'.$page.'_data\(/i', file_get_contents($controller_file))){

				$this->append_function($controller_file, $php);
			}
		}

		//create link
		if($_POST['make_redirect_link']){

			$this->redirect_link->Select("WHERE redirect_url LIKE '".str_replace('_', '-', $_POST['page']).'/'."'");
			if($this->redirect_link->Numrows == 0){

				$this->redirect_link->Insert(array(
					'canonical_url' => '?show_page='.str_replace('_', '-', $_POST['page']).'&model='.$_POST['name'].'&page='.$_POST['page'],
					'redirect_url' => str_replace('_', '-', $_POST['page']).'/',
					'from' => 'model',
					'is_indexed' => 1,
					'created_at' => 'NOW()'
				));
			}
		}
	}

	function createView($view){

		if($view){

			$array = $_POST;
			$array['model'] = $_POST['name'];
			$array['title'] = $_POST['page'];
			$array['columns'] = '';

			$this->Sql->Query("SHOW COLUMNS FROM ".$_POST['mysql_table']);
			while($row = mysqli_fetch_Assoc($this->Sql->Result)){

				$field = $row['Field'];
				$array['columns'] .= $array['columns'] ? ", '".$field."'" : "'".$field."'";
			}

			$file = file_get_contents(_CurrentTemplate.'/form/views/'.$view.'.tpl');
			return $this->replace($file, $array);
		}
		return '';
	}

	function append_function($file, $php){

		$dir = dirname($file);
		$exp = explode('/', $dir);
		$last_dir = $exp[count($exp)-1];
		$this->File->WriteDirectorRecursive(_RootFolder.'/tmp/backup/'.$last_dir);
		copy($file, _RootFolder.'/tmp/backup/'.$last_dir.'/'.basename($file));

		$content = file_get_contents($file); // Open file form read.
		$exp = explode("\n", $content);
		$full_php = '';
		$function_added = false;
		foreach($exp as $line){

			if(preg_match('/function([[:space:]])/i', $line) && $function_added == false){//function forum(){

				$line = $php."\n".$line;
				$function_added = true;
			}
			$full_php .= $full_php ? "\n".$line : $line;
		}
		file_put_contents($file, trim($full_php));
	}

	function install(){

		$file_content = $this->Curl->SendCurl('http://www.projectpartner.ee/scripts/models.php?file='.$_GET['file'].'.zip');
		$check = explode('_v_', $_GET['file']);
		$version = str_replace('_', '.', $check[1]);
		$model = $check[0];
		$file = $_GET['file'].'.zip';

		//core update
		if(preg_match('/core/i', $file)){

			$dir = _RootFolder.'/tmp/core';
			if(!is_dir($dir)){

				mkdir($dir);
			}
			file_put_contents($dir.'/'.$_GET['file'].'.zip', $file_content);

			if ($this->Zip->open($dir.'/'.$file) === TRUE) {

				if(!is_dir($dir.'/unzip')){

					mkdir($dir.'/unzip');
				}
				if(!is_dir($dir.'/unzip/'.$file)){

					mkdir($dir.'/unzip/'.$file);
				}

				$this->Zip->extract($dir.'/'.$file, $dir.'/unzip/'.$file);

				system('cp -rf '.$dir.'/unzip/'.$file.'/core/* '._RootFolder.'/core/');

				$this->templates->Update(array('version' => $version), "WHERE name = 'core' ");
				if($this->templates->Affectedrows == 0){

					$this->templates->insert(array('name' => 'core', 'page' => 'core', 'is_active' => '0', 'type' => 'CORE', 'version' => $version));
				}
			}
		}
		//model update
		else{

			$dir = _RootFolder.'/tmp/app';
			if(!is_dir($dir)){

				mkdir($dir);
			}
			file_put_contents($dir.'/'.$_GET['file'].'.zip', $file_content);

			$this->templates->templates("WHERE name = '".$model."' ORDER BY version DESC LIMIT 1");
			$row = $this->templates->Assoc();

			if((float)$version > (float)$row['version']){

				if ($this->Zip->open($dir.'/'.$file) === TRUE) {

					if(!is_dir($dir.'/unzip')){

						mkdir($dir.'/unzip');
					}
					if(!is_dir($dir.'/unzip/'.$file)){

						mkdir($dir.'/unzip/'.$file);
					}

					$this->Zip->extract($dir.'/'.$file, $dir.'/unzip/'.$file);

					system('cp -rf '.$dir.'/unzip/'.$file.'/app/installers '._RootFolder.'/app/');
					system('cp -rf '.$dir.'/unzip/'.$file.'/app/models '._RootFolder.'/app/');
					system('cp -rf '.$dir.'/unzip/'.$file.'/app/querys '._RootFolder.'/app/');
					system('cp -rf '.$dir.'/unzip/'.$file.'/app/helpers '._RootFolder.'/app/');

					$this->File->GetAllFiles($dir.'/unzip/'.$file.'/app/sql/', '.sql', '', 'both', false);
					$sql_list = $this->File->Files;
					foreach($sql_list as $v1){

						$this->Sql->Query(file_Get_contents($dir.'/unzip/'.$file.'/app/sql/'.$v1['file']));
					}

					if( file_Exists(_RootFolder.'/app/installers/'.$model.'.php') ){

						require_once _RootFolder.'/app/installers/'.$name.'.php';
						$install_class = $name.'_Install';
						$install_class = new $install_class;
						$install_class->install();
					}
					$this->templates->Update(array('version' => $version), "WHERE name = '".$model."' ");
				}
			}
		}
		system('rm -R '.$dir.'/unzip');
	}

	function add_model_from_file(){

		if($_FILES['model_file']['size'] > 0){

			$dir = _RootFolder.'/tmp/uploaded_app';
			$file = $_FILES['model_file']['name'];

			if(!is_dir($dir)){

				mkdir($dir);
			}

			move_uploaded_file($_FILES['model_file']['tmp_name'], $dir.'/'.$file);

			if ($this->Zip->open($dir.'/'.$file) === TRUE) {

				$this->Zip->extract($dir.'/'.$file, $dir);
				$this->File->GetAllFiles($dir.'/app/models/', '.php', '', 'both', false);
				$model = str_replace('.php', '', $this->File->Files[0]['file']);
				$version = 1;

				if(is_dir($dir.'/app')){

					system('cp -rf '.$dir.'/app/installers '._RootFolder.'/app/');
					system('cp -rf '.$dir.'/app/models '._RootFolder.'/app/');
					system('cp -rf '.$dir.'/app/querys '._RootFolder.'/app/');
					system('cp -rf '.$dir.'/app/helpers '._RootFolder.'/app/');

					$this->File->GetAllFiles($dir.'/app/sql/', '.sql', '', 'both', false);
					$sql_list = $this->File->Files;
					foreach($sql_list as $v1){

						$this->Sql->Query(file_Get_contents($dir.'/app/sql/'.$v1['file']));
					}

					if( file_Exists(_RootFolder.'/app/installers/'.$model.'.php') ){

						require_once _RootFolder.'/app/installers/'.$model.'.php';
						$install_class = $model.'_Install';
						$install_class = new $install_class;
						$install_class->install();
					}
					$this->templates->Update(array('version' => $version), "WHERE name = '".$model."' ");
					$this->Message('Successfully installed');
				}
				else{

					$this->error('Cannot install');
				}
			}
			else{

				$this->error('Cannot install');
			}
		}
	}

	function create_install(){

		ini_set('max_execution_time', 300);

		$model = $_GET['model_name'];

		$dir = _RootFolder.'/tmp/compress';
		system('rm -R '.$dir);

		if(!is_dir($dir)){

			mkdir($dir);
		}
		if(!is_dir($dir.'/'.$model)){

			mkdir($dir.'/'.$model);
		}

		if(preg_match('/core/i', $model)){

			if(!is_dir($dir.'/'.$model)){

				mkdir($dir.'/'.$model);
			}
			system('cp -rf '._RootFolder.'/core/* '.$dir.'/'.$model);

			$this->templates->Update(array('version' => $_GET['version']), "WHERE name = '".$model."' ");

			$file = $dir.'/'.$model.'_v_'.$_GET['version'].'.zip';

			file_put_contents($file, '');
			$this->Zip->open($file);
			$this->File->GetAllFiles($dir.'/'.$model);
			foreach($this->File->FilesRecursive as $v){

				$this->Zip->addFile($v['file'], str_replace($dir.'/'.$model, 'core', $v['file']), $file);
			}
			$this->Zip->close();
			$_SESSION['create_install'][$model] = _RootUrl.'/tmp/compress/'.$model.'_v_'.$_GET['version'].'.zip';
			$this->Message('file created');


			return true;
		}

		if($model && !is_file(_RootFolder.'/app/models/'.$model.'/index.php')){

			echo 'no such model';
			return true;
		}

		if($model){

			if(!is_dir($dir.'/'.$model.'/models')){

				mkdir($dir.'/'.$model.'/models');
			}
			if(!is_dir($dir.'/'.$model.'/controllers')){

				mkdir($dir.'/'.$model.'/controllers');
			}
			if(!is_dir($dir.'/'.$model.'/installers')){

				mkdir($dir.'/'.$model.'/installers');
			}
			if(!is_dir($dir.'/'.$model.'/views')){

				mkdir($dir.'/'.$model.'/views');
			}
			if(!is_dir($dir.'/'.$model.'/querys')){

				mkdir($dir.'/'.$model.'/querys');
				mkdir($dir.'/'.$model.'/sql');
			}

			system('cp -rf '._RootFolder.'/app/models/'.$model.'/index.php '.$dir.'/'.$model.'/models/');
			system('cp -rf '._RootFolder.'/app/installers/'.$model.'.php '.$dir.'/'.$model.'/installers/');

			if(file_exists(_RootFolder.'/app/models/'.$model.'/controller.php')){

				$content = file_get_contents(_RootFolder.'/app/models/'.$model.'/controller.php');

				preg_match('/callSqlClass([[:space:]\=_]+)array\(([a-zA-Z[:space:]\,\_\'_]+)\)/se', $content, $match);
				$exp = explode(',', $match[2]);
				foreach($exp as $v){

					$file = str_replace("'", '', $v);
					$file = str_replace(' ', '', $file);
					$this->Sql->Query("SHOW CREATE TABLE `".$file."` ");
					if($this->Sql->Numrows > 0){

						$r = mysqli_fetch_Assoc($q);
						$create_sql = $r['Create Table'];
						$create_sql = preg_replace('/AUTO_INCREMENT\=([0-9_]+)/s', '', $create_sql);
						$create_sql = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $create_sql);
						file_put_contents($dir.'/'.$model.'/sql/'.$file.'.sql', $create_sql);
					}
					system('cp -rf '._RootFolder.'/app/querys/'.$file.'.php '.$dir.'/'.$model.'/querys/');
				}
			}

			$this->File->GetAllFiles($dir.'/'.$model);

			$this->templates->Update(array('version' => $_GET['version']), "WHERE name = '".$model."' ");

			$file = $dir.'/'.$model.'_v_'.$_GET['version'].'.zip';

			file_put_contents($file, '');
			$this->Zip->open($file);
			foreach($this->File->FilesRecursive as $v){

				$this->Zip->addFile($v['file'], str_replace($dir.'/'.$model, 'app', $v['file']), $file);
			}
			$this->Zip->close();
			$_SESSION['create_install'][$model] = _RootUrl.'/tmp/compress/'.$model.'_v_'.$_GET['version'].'.zip';
			$this->Message('file created');
		}
		else{

			$this->Error('No such model');
		}
	}

	function remove_model(){

		$check = explode('_v_', $_GET['file']);
		$model = $check[0];

		if( file_Exists(_RootFolder.'/app/installers/'.$model.'.php') ){

			if(is_file(_RootFolder.'/app/installers/'.$name.'.php')){

				require_once _RootFolder.'/app/installers/'.$name.'.php';
				$install_class = $name.'_Install';
				$install_class = new $install_class;
				$install_class->remove();
			}
		}

		$dir = _RootFolder.'/app';

		system('rm -R '.$dir.'/installers/'.$model.'.php');
		system('rm -R '.$dir.'/models/'.$model.'.php');
		system('rm -R '.$dir.'/controllers/'.$model.'.php');
		system('rm -R '.$dir.'/views/'.$model);
		system('rm -R '.$dir.'/designers/'.$model.'.php');

		$this->settings->Delete("WHERE name = 'model' AND value LIKE '".$model."_%' ");
	}

	function create_table_php(){

		if( $_GET['table'] && !file_Exists(_RootFolder.'/app/querys/'.$_GET['table'].'.php') ){

			$content = file_get_contents(_CurrentTemplate.'/form/query.tpl');
			$content = str_replace("{'name'}", $_GET['table'], $content);
			file_put_contents(_RootFolder.'/app/querys/'.$_GET['table'].'.php', $content);
		}
	}

	function add_menu(){

		$_POST['is_restricted'] = 1;
		$_POST['class'] = !$_POST['clickAble'] ? 'no-click' : '';

		$this->menus->Select("WHERE parent_id = ".$_POST['parent_id']." ORDER BY queue DESC LIMIT 1");
		$row = $this->menus->Assoc();
		$_POST['queue'] = $row['queue']+1;

		$this->menus->Insert($_POST);
	}

	function update_admin_menu(){

		$_POST['class'] = !$_POST['clickAble'] ? 'no-click' : '';

		$this->menus->defaults(array('id_enabled' => 0));
		$this->menus->Update($_POST, "WHERE id = ".$_GET['id']);
	}

	function dragAndDrop(){

		$this->dragAndDrop->onDrop('menus', 'parent_id');
	}
}
?>