<?php
/* 快捷商城系统
 * 版本号：2.0
 * 官网：http://www.kjcms.cn
 * 2015-02-16
 */
class cls_developer {
	static $perms;
	static function get_perms($key) {
		if( empty(self::$perms) ) {
			self::$perms = array(
				"path_view" => KJ_DIR_APP . "/view",
				"path_model" => KJ_DIR_APP . "/model",
				"path_datasource" => KJ_DIR_APP . "/datasource",
				"path_developer" => KJ_DIR_DATA . "/developer",
				"no_dir" => array('admin','common','developer','install'),
			);
		}
		$arr_return = array();
		if(isset(self::$perms[$key])) $arr_return = self::$perms[$key];
		return $arr_return;
	}
	static function get_list( $path ) {
		if(!in_array(substr($path,0,1) , array("/" , "\\"))) $path = "/" . $path;
		$path = self::get_perms('path_view') . $path;
		$arr_folder = fun_file::get_dirs($path);
		$arr_return['file'] = fun_file::get_files($path);
		if(!empty($path)) {
			$arr_no_dir = self::get_perms("no_dir");
			$arr_return['folder'] = array();
			foreach($arr_folder as $item) {
				if(in_array($item['name'] , $arr_no_dir)) continue;
				$arr_return['folder'][] = $item;
			}
		} else {
			$arr_return['folder'] = $arr_folder;
		}
		return $arr_return;
	}
	static function on_dir_del($path , $name) {
	}
	static function get_file_cont($path) {
		if(!in_array(substr($path,0,1) , array("/" , "\\"))) $path = "/" . $path;
		$path = self::get_perms('path_view') . $path;
		if(file_exists($path)) {
			return file_get_contents($path);
		} else {
			return "";
		}
	}
	static function on_file_save($path , $cont) {
		if(!in_array(substr($path,0,1) , array("/" , "\\"))) $path = "/" . $path;
		$path = self::get_perms('path_view') . $path;
		if(!file_exists($path)) return array("code" => 500 , "msg" => "模板文件不存在" . $path);
		$cont = fun_get::filter($cont , true);
		$arr = fun_file::file_create($path , $cont);
		return $arr;
	}
	static function get_datasource($path) {
		return array();
	}
	static function get_tables() {
		$arr_table = array();
		$obj_db = cls_obj::db();
		$obj_result = $obj_db->query("show table status");
		$pre = strtolower(cls_config::DB_PRE);
		$len = strlen($pre);
		while ($obj_rs = $obj_db->fetch_array($obj_result) ) {
			if(strtolower(substr($obj_rs['Name'],0,$len)) != $pre ) continue;
			$name = substr($obj_rs['Name'],$len);
			if(empty($obj_rs['Comment'])) $obj_rs['Comment'] = $name;
			$arr_table[$name] = $obj_rs['Comment'];
		}
		return $arr_table;
	}

	static function get_table_fileds($tablename) {
		$arr_return = array("code" => 0);
		$obj_db = cls_obj::db();
		$result = $obj_db->query("SHOW FULL COLUMNS FROM ".$tablename);
		$arr_primary_key = array();
		$arr_union_key = $arr_key = $arr_fields = array();
		while( $obj_rs = $obj_db->fetch_array($result) ) {
			$str_comment = '';
			$str_comment = (!empty($obj_rs["Comment"])) ? $obj_rs["Comment"] : $obj_rs["Field"];
			$arr = explode("(" , $obj_rs["Type"]);
			$type = $arr[0];
			/*
			$str_x = substr($obj_rs["Type"] , 0, 3);
			if(in_array($str_x , array("int","flo"))) {
				$type = "int";
			} else if($str_x == 'dat' or stristr($obj_rs['Field'] , 'date') or stristr($obj_rs['Field'],'time') ) {
				$type = 'date';
			} else {
				$type = "varchar";
			}
			*/
			$arr_fields[] = array("name" => $obj_rs["Field"] , "beta" => $str_comment , "type" => $type);
		}

		return $arr_fields;
	}
	static function get_fields($table , $table_name = array()) {
		$arr_relate = include(KJ_DIR_DATA . "/developer/table.relate.php");
		$arr_return = self::get_table_fileds(cls_config::DB_PRE . $table);
		$arr_return2 = array();
		if(isset($arr_relate[$table]) ) {
			foreach($arr_relate[$table] as $item => $key) {
				$arr_return2 = self::get_table_fileds(cls_config::DB_PRE . $item);
				if(isset($table_name[$item])) {
					for($i=0 ; $i < count($arr_return2) ; $i++) {
						$arr_return2[$i]['beta'] = $arr_return2[$i]['beta'] . "[" . $table_name[$item] . "]";
					}
				}
				$arr_return = array_merge($arr_return , $arr_return2);
			}
		}
		return $arr_return;
	}

	static function datasource_save($arr_msg) {
		if(!isset($arr_msg['dirname']) || empty($arr_msg['dirname'])) return array('code' => 500 , 'msg' => '没有选择模板');
		if(!in_array(substr($arr_msg['dirname'],0,1) , array("/" , "\\"))) $arr_msg['dirname'] = "/" . $arr_msg['dirname'];
		if(!empty($arr_msg['typename'])) $arr_msg['dirname'] .= "." . $arr_msg['typename'];
		$path = self::get_perms('path_developer') . $arr_msg['dirname'] . ".php";
		$arr_app_model = (file_exists($path)) ? include($path) : array();
		if(isset($arr_msg['oldname']) && $arr_msg['oldname']!='') {
			unset($arr_app_model[$arr_msg['oldname']]);
			unset($arr_msg['oldname']);
		}
		$arr_app_model[$arr_msg['name']] = $arr_msg;
		$val=var_export($arr_app_model,true);
		$val = '<'.'?php'.chr(10).'return '.$val.";";
		fun_file::file_create($path,$val,1);
		return array("code" => 0 , "msg" => "成功保存");
	}
	static function datasource_del($dirname , $typename , $name) {
		if(!isset($dirname) || empty($dirname)) return array('code' => 500 , 'msg' => '没有选择模板');
		if(!in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = "/" . $dirname;
		if(!empty($typename)) $dirname .= "." . $typename;
		$path = self::get_perms('path_developer') . $dirname . ".php";
		$arr_app_model = (file_exists($path)) ? include($path) : array();
		unset($arr_app_model[$name]);
		$val = var_export($arr_app_model,true);
		$val = '<'.'?php'.chr(10).'return '.$val.";";
		fun_file::file_create($path,$val,1);
		return array("code" => 0 , "msg" => "成功保存");
	}
	//生成数据源
	static function datasource_create($dirname , $typename) {
		if(!isset($dirname) || empty($dirname)) return array('code' => 500 , 'msg' => '没有选择模板');
		if(!in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = "/" . $dirname;
		$dirname2 = (!empty($typename))?  $dirname . "." . $typename : $dirname;
		$path = self::get_perms('path_developer') . $dirname2 . ".php";
		$arr_app_model = (file_exists($path)) ? include($path) : array();
		$filename = "user";
		if(!empty($typename)) $filename .= "." . $typename;

		$arr_relate = include(KJ_DIR_DATA . "/developer/table.relate.php");
		$phpcont = '<' . '?' . 'php ' . chr(10) . 'class datasource_' . str_replace('.','_',$filename) . ' {';
		foreach($arr_app_model as $key => $item) {
			$tablename = '" . cls_config::DB_PRE . "' . $item['seltable'];
			if(isset($arr_relate[$item['seltable']])) {
				$arr_wherename = array();
				$arr_sortname = array();
				foreach($item['where'] as $item2) {
					$arr_wherename[] = $item2['name'];
				}
				foreach($item['sort'] as $item2) {
					$arr_sortname[] = $item2['name'];
				}
				foreach($arr_relate[$item['seltable']] as $key2 => $item2) {
					$arr = self::get_table_fileds(cls_config::DB_PRE . $key2);
					$arr_table_fields = array();
					foreach($arr as $item3) {
						$arr_table_fields[] = $item3['name'];
					}
					$arr = array_intersect($item['fields'] , $arr_table_fields);
					$arr1 = array_intersect($arr_wherename , $arr_table_fields);
					$arr2 = array_intersect_assoc($arr_sortname , $arr_table_fields);
					if(!empty($arr) || !empty($arr1) || !empty($arr2) ) {
						$tablename .= ' left join " . cls_config::DB_PRE . "' . $key2 . ' on ' . $item2;
					}
				}
			}
			$param = array();
			foreach($item['param_name'] as $name) {
				$param[] = '$' . $name;
			}
			$sort = self::get_create_sort($item['sort']);
			$fields = (is_array($item['fields'])) ? implode("," , $item['fields']) : "";
			$param = implode("," , $param);
			$phpcont .= chr(10) . "	function " . $item['name'] . "(" . $param . ") {";
			$phpcont .= chr(10) . '		$obj_db = cls_obj::db();';
			$phpcont .= chr(10) . '		$arr_return = array();';
			$phpcont .= chr(10) . '		$arr_list = array();';
			$phpcont .= chr(10) . '		$where = "' . self::get_create_where($item['where']) . '";';
			if(!empty($item['pagesize'])) {
				$phpcont .= chr(10) . '		$page = fun_get::get("page");';
				$phpcont .= chr(10) . '		$arr_return["pageinfo"] = $obj_db->get_pageinfo("' . $tablename . '" , $where , $page , ' . $item['pagesize'] . ');';
				$limit = '" . $arr_return["pageinfo"]["limit"] . "';
			} else {
				if(!empty($item['limit_end'])) {
					$limit = ' limit ' . $item['limit_start'] . "," . $item['limit_end'];
				} else {
					$limit = '';
				}
			}
			$phpcont .= chr(10) . '		$obj_result = $obj_db->select("select ' . $fields . ' from ' . $tablename . '" . $where . "' . $sort . $limit . '");';
			$phpcont .= chr(10) . '		while($obj_rs = $obj_db->fetch_array($obj_result)) {';
			$phpcont .= chr(10) . '			$arr_list[] = $obj_rs;';
			$phpcont .= chr(10) . '		}';
			if(!empty($item['pagesize'])) {
				$phpcont .= chr(10) . '		$arr_return["pagebtns"] = fun_kj::get_pagebtns($arr_return["pageinfo"]);';
				$phpcont .= chr(10) . '		$arr_return["list"] = $arr_list;';
			} else {
				$phpcont .= chr(10) . '		$arr_return = $arr_list;';
			}
			$phpcont .= chr(10) . '		return $arr_return;';
			$phpcont .= chr(10) . '	}';
		}
		$phpcont .= chr(10) . "}";
		$path = self::get_perms('path_datasource') . $dirname . "/datasource." . $filename . ".php";
		fun_file::file_create($path , $phpcont , 1);
		return array("code" => 0);

	}
	static function datasource_folder_create($dirname , $id , $name) {
		if(!isset($dirname) || empty($dirname)) return array('code' => 500 , 'msg' => '没有选择模板');
		if(in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = substr($dirname,1);
		if(empty($id)) return array("code" => 500 , "msg" => "目录唯一标识不能为空");
		if(empty($name)) return array("code" => 500 , "msg" => "目录名称不能为空");
		$filename = "folder";
		if(!empty($dirname)) $filename .= "." . $dirname;
		$path = self::get_perms('path_developer') . "/" . $filename . ".php";
		$arr_folder = array();
		if(file_exists($path)) {//不存在，则创建文件
			$arr_folder = include($path);
		}
		$arr_folder[$id] = array("id" => $id , "name" => $name);
		$val = var_export($arr_folder,true);
		$val = '<'.'?php'.chr(10).'return '.$val.";";
		fun_file::file_create($path,$val,1);
		return array("code" => 0 , "msg" => "成功保存");
	}
	static function datasource_folder_del($dirname , $id) {
		if(!isset($dirname) || empty($dirname)) return array('code' => 500 , 'msg' => '没有选择模板');
		if(in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = substr($dirname,1);
		if(empty($id)) return array("code" => 500 , "msg" => "没有找到要删除的目录");
		$filename = "folder";
 		if(!empty($dirname)) $filename .= "." . $dirname;
		$path = self::get_perms('path_developer') . "/" . $filename . ".php";
		$arr_folder = array();
		if(file_exists($path)) {//不存在，则创建文件
			$arr_folder = include($path);
		}
		if(isset($arr_folder[$id])) unset($arr_folder[$id]);
		$val = var_export($arr_folder,true);
		$val = '<'.'?php'.chr(10).'return '.$val.";";
		fun_file::file_create($path,$val,1);
		return array("code" => 0 , "msg" => "成功保存");
	}
	static function get_create_where($arr_where) {
		if(empty($arr_where)) return '';
		$where = array();
		foreach($arr_where as $item) {
			switch($item['condition']) {
				case 'in':
					$where[] = $item['name'] . " in(" . $item['val'] . ")";
					break;
				case 'not in':
					$where[] = "not " . $item['name'] . " in(" . $item['val'] . ")";
					break;
				case 'left' :
					$where[] = "left(" . $item['name'] . "," . strlen($item['val']) . ")='" . $item['val'] . "'";
					break;
				case 'right' :
					$where[] = "right(" . $item['name'] . "," . strlen($item['val']) . ")='" . $item['val'] . "'";
					break;
				case 'like' :
					$where[] = '" . $obj_db->concat(",","' . $item['name'] . '",",") . " like \'%,' . $item['val'] . ',%\'';
					break;
				case 'not like':
					$where[] = ' not " . $obj_db->concat(",","' . $item['name'] . '",",") . " like \'%,' . $item['val'] . ',%"';
					break;
				default:
					$where[] = $item['name'] . fun_get::filter($item['condition'],true) . "'" . $item['val'] . "'";
			}
		}
		return " where " . implode(" and " , $where);
	}
	static function get_create_sort($arr_sort) {
		if(empty($arr_sort)) return '';
		$arr = array();
		foreach($arr_sort as $item) {
			$arr[] = $item['name'] . ' ' . $item['by'];
		}
		$sort = " order by " . implode("," , $arr);
		return $sort;
	}
	static function get_datasource_info($dirname , $typename , $name) {
		if( empty($dirname)) $dirname = "default";
		if(!in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = "/" . $dirname;
		if(!empty($typename)) $dirname .= "." . $typename;
		$path = self::get_perms('path_developer') . $dirname . ".php";
		$arr_app_model = (file_exists($path)) ? include($path) : array();
		$arr_return = array(
			"dirname" => $dirname,
			"typename" => $typename,
			"name" => $name,
			"cnname" => "",
			"seltable" => "",
			"limit_start" => 0,
			"limit_end" => 10,
			"pagesize" => 0,
			"datasource_name" => '',
			"where" => array(),
			"fields" => array(),
			"param_name" => array(),
			"sort" => array(),
		);
		if(isset($arr_app_model[$name])) $arr_return = $arr_app_model[$name];
		return $arr_return;
	}
	static function get_datasource_list( $dirname , $typename = '' ) {
		if( empty($dirname)) $dirname = "default";
		if(!in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = "/" . $dirname;
		if(!empty($typename)) $dirname .= "." . $typename;
		$path = self::get_perms('path_developer') . $dirname . ".php";
		$arr_app_model = (file_exists($path)) ? include($path) : array();
		$arr_list = array();
		foreach($arr_app_model as $item => $key ) {
			if(!isset($key['cnname']) || empty($key['cnname'])) $key['cnname'] = $item;
			$arr_list[$item] = $key;
		}
		return $arr_list;
	}

	static function get_datasource_folder($dirname) {
		if(!isset($dirname) || empty($dirname)) return array('code' => 500 , 'msg' => '没有选择模板');
		if(in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = substr($dirname,1);
		$filename = "folder";
		if(!empty($dirname)) $filename .= "." . $dirname;
		$path = self::get_perms('path_developer') . "/" . $filename . ".php";
		$arr_folder = array();
		if(file_exists($path)) {//不存在，则创建文件
			$arr_folder = include($path);
		}
		return $arr_folder;
	}

	static function get_datasource_sys($dirname) {
		$obj_db = cls_obj::db();
		$obj_channel = $obj_db->get_one("select channel_id from " . cls_config::DB_PRE . "article_channel where channel_key='datasource' limit 0,1");
		if(empty($obj_channel)) return array();
		$channel_id = $obj_channel['channel_id'];
		$obj_folder = $obj_db->get_one("select folder_id from " . cls_config::DB_PRE . "article_folder where folder_name='" . $dirname . "' and folder_channel_id='" . $channel_id . "' limit 0,1");
		if(empty($obj_folder)) return array();
		$folder_id = $obj_folder['folder_id'];
		$arr_list = array();
		$obj_result = $obj_db->select("select article_title,article_id from " . cls_config::DB_PRE . "article where article_folder_id='" . $folder_id . "'");
		while($obj_rs = $obj_db->fetch_array($obj_result)) {
			$arr = explode("//" , $obj_rs['article_title']);
			$obj_rs['article_title'] = implode("<br>" , $arr);
			$arr_list[] = $obj_rs;
		}
		return $arr_list;
	}

	static function get_datasource_sys_info($id) {
		$obj_db = cls_obj::db();
		$obj_info = $obj_db->get_one("select article_content,article_id,article_title from " . cls_config::DB_PRE . "article where article_id='" . $id . "'");
		if(empty($obj_info)) return array('article_content'=>'' , 'article_id' => '' , 'article_title' => '');
		$obj_info['article_content'] = fun_get::filter($obj_info['article_content'] , true);
		return $obj_info;
	}

	static function file_rename($dirname , $oldname , $newname) {
		if(!in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = "/" . $dirname;
		$old_path = self::get_perms('path_view') . $dirname . "/" . $oldname;
		if(!file_exists($old_path)) return array("code" => 500 , "msg" => "原文件不存在");
		$new_path = self::get_perms('path_view') . $dirname . "/" . $newname;
		if(file_exists($new_path)) return array("code" => 500 , "msg" => "文件" . $newname . "已经存在，请换一个名称");
		$arr = fun_file::file_rename($old_path,$new_path);
		return $arr;
	}
	static function folder_rename($dirname , $oldname , $newname) {
		if(!in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = "/" . $dirname;
		$old_path = self::get_perms('path_view') . $dirname . "/" . $oldname;
		if(!is_dir($old_path)) return array("code" => 500 , "msg" => "原目录不存在");
		$new_path = self::get_perms('path_view') . $dirname . "/" . $newname;
		if(is_dir($new_path)) return array("code" => 500 , "msg" => "目录" . $newname . "已经存在，请换一个名称");
		$arr = fun_file::dir_rename($old_path,$new_path);
		return $arr;
	}
	static function folder_create($name) {
		if(empty($name)) return array("code" => 500 , "msg" => "新目录名称不能为空");
		$folder_path = self::get_perms('path_view') . "/" . $name;
		if(is_dir($folder_path)) return array("code" => 500 , "msg" => "目录已存在，请换个名称");
		$arr = fun_file::dir_create($folder_path);
		return $arr;
	}
	static function file_create($dirname , $name) {
		if(empty($name)) return array("code" => 500 , "msg" => "新文件名称不能为空");
		if(empty($dirname)) return array("code" => 500 , "msg" => "必须指定目录");
		if(!in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = "/" . $dirname;
		$path = self::get_perms('path_view') . $dirname . "/" . $name;
		if(file_exists($path)) return array("code" => 500 , "msg" => "文件已存在，请换个名称");
		$arr = fun_file::file_create($path , '');
		return $arr;
	}
	static function folder_del($name) {
		if(empty($name)) return array("code" => 500 , "msg" => "没有指定要删除的目录");
		$folder_path = self::get_perms('path_view') . "/" . $name;
		if(!is_dir($folder_path)) return array("code" => 500 , "msg" => "要删除的目录不存在");
		$arr = fun_file::dir_delete($folder_path);
		return $arr;
	}
	static function file_del($dirname , $name) {
		if(empty($name)) return array("code" => 500 , "msg" => "没有指定要删除的文件");
		if(empty($dirname)) return array("code" => 500 , "msg" => "必须指定目录");
		if(!in_array(substr($dirname,0,1) , array("/" , "\\"))) $dirname = "/" . $dirname;
		$path = self::get_perms('path_view') . $dirname . "/" . $name;
		if(!file_exists($path)) return array("code" => 500 , "msg" => "要删除的文件不存在");
		$arr = fun_file::file_delete($path);
		return $arr;
	}
}