<?php
	!defined('DIRCMS_MANAGE') && exit('Access Denied!');
	if($_roleid!=1 && $_userid!=ADMIN_FOUNDERS)showmsg_nourl('您没有该操作的权限!');
	$action=empty($action)?'manage':trim($action);
	require_once(DIRCMS_ROOT.'include/list.class.php');
	$l=new dircmslist();
	$c=new cache();
	switch($action)
	{
		case 'manage':
			if(isset($do_submit))
			{
				foreach($id as $modelid)
				{
					$modelid=intval($modelid);
					$db->update(DB_PRE.'model',array('modelname'=>$modelname[$modelid]),'id='.$modelid);
				}
				if(isset($installmodel)&& $installmodel)
				{
					
				}
				$c->cache_model();
				showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage ');
			}
			$where=1;
			$orderby="id ASC";
			$result=$l->getlist(DB_PRE.'model',$where,$orderby,1,20);
			include admin_tlp('model_manage');
			break;
		case 'add':
			if(isset($do_submit))
			{
				$newmodel['isinstall']=1;
				if(!preg_match('/[a-z0-9_]{2,30}/i',$newmodel['name']))showmsg('数据表名称由2-30个数字, 字母, 下划线组成!',ADMIN_FILE.'?file=model&action=manage');
				if(in_array(DB_PRE.$newmodel['name'],$db->get_tables()))showmsg(DB_PRE.$newmodel['name'].'表已经存在, 请更换表名!',ADMIN_FILE.'?file=model&action=manage');
				if(($modelid=$db->insert(DB_PRE.'model',$newmodel,false)) && $db->create_model_table(DB_PRE.$newmodel['name'])) 
				{
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'title', '标题', '','title', '', '', '', '', '1', '200', '', '', '', '1', '0', '1', '1', '1,2,3,4', '0', 'like');",true); // 插入标题
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'style', '颜色和字型', '','style', '', '', '', '', '1', '200', '', '', '', '2', '0', '1', '1', '1', '0', 'like');",true); // 插入颜色和字型
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'thumb', '标题图片', '','thumb', '', '', '', '', '1', '200', '', '', '', '3', '0', '1', '1', '1,3,4', '0', 'like');",true); // 标题图片
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'keywords', '关键词', '多关键词之间用空格隔开','keyword', '', '', '', '', '1', '200', '', '', '', '4', '0', '1', '1', '1,3,4', '0', 'like');",true); // 关键词
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'description', '摘要', '不要超过255个字符','description', '', '', '', '', '1', '200', '', '', '', '4', '0', '1', '1', '1,3,4', '0', 'like');",true); // 摘要
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'inputtime', '添加时间', '','inputtime', '', '', '', '', '1', '200', '', '', '', '5', '0', '0', '1', '1', '0', 'like');",true); // 添加时间
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'groupid', '阅读权限', '启用后内容不会被静态化','groupid', '', '', '', '', '1', '200', '', '', '', '6', '0', '0', '1', '1', '0', 'like');",true); // 阅读权限
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'posid', '推荐位设置', '','posid', '', '', '', '', '1', '200', '', '', '', '7', '0', '0', '1', '1', '0', 'like');",true); // 推荐位设置
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'areaid', '地区', '','areaid', '', '', '', '', '1', '200', '', '', '', '8', '0', '0', '1', '1,2,3,4', '0', 'like');",true); // 地区
					$db->query("INSERT INTO `".DB_NAME."`.`".DB_PRE."db_fields`(`modelid` ,`name` ,`fieldname` ,`tips` ,`formtype` ,`js` ,`css` ,`preg` ,`defaultvalue` ,`minsize` ,`maxsize` ,`optionvalue` ,`editorwidth` ,`editorheight` ,`orderby` ,`disabled` ,`isbase` ,`issystem` ,`privilege` ,`issearch` ,`searchby` )VALUES ( '{$modelid}', 'point', '阅读所需点数', '启用后内容不会被静态化','point', '', '', '', '', '1', '200', '', '', '', '9', '0', '0', '1', '1', '0', 'like');",true); // 阅读所需点数
				}
				$c->cache_model();
				showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage');
			}
			$categorytlpselect='<select name="newmodel[categorytlp]">';
			$listtlpselect='<select name="newmodel[listtlp]">';
			$showtlpselect='<select name="newmodel[contenttlp]">';
			$searchtlpselect='<select name="newmodel[stemplate]">';
			$cache=cache_read('template.cache.php',TPL_ROOT.TPL_NAME.'/');
			if($cache)foreach($cache as $r)
			{
				if(substr($r['template'],0,9)=='category_')
				{
					$categorytlpselect.='<option value="'.$r['template'].'">'.$r['template'].'.html</option>';
				}

				if(substr($r['template'],0,15)=='final_category_')
				{
					$listtlpselect.='<option value="'.$r['template'].'">'.$r['template'].'.html</option>';
				}

				if(substr($r['template'],0,4)=='show')
				{
					$showtlpselect.='<option value="'.$r['template'].'">'.$r['template'].'.html</option>';
				}
				if(substr($r['template'],0,7)=='search_')
				{
					$searchtlpselect.='<option value="'.$r['template'].'">'.$r['template'].'.html</option>';
				}
			}
			$categorytlp.='</select>';
			$listtlpselect.='</select>';
			$showtlpselect.='</select>';
			$searchtlpselect.='</select>';
			include admin_tlp('model_add');
			break;
		case 'chkmodel':
			echo in_array(DB_PRE.$data,$db->get_tables())?'yes':'no';
			exit();
			break;
		case 'template':
			$db->update(DB_PRE.'model',array($tlp=>$tlpname),'id='.intval($modelid));
			$c->cache_model();
			showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage ');
			break;
		case 'install':
			$m=$isinstall?'安装':'卸载';
			$db->update(DB_PRE.'model',array('isinstall'=>intval($isinstall)),'id='.intval($id));
			$c->cache_model();
			showmsg('模型'.$m.'成功!',ADMIN_FILE.'?file=model&action=manage ');
			break;
		case 'delete':
			if($db->drop_table($tbname) && $db->mysql_delete(DB_PRE.'model',intval($id)) && $db->mysql_delete(DB_PRE.'db_fields',intval($id),'modelid'))
			{
				$c->cache_model();
				showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage');
			}
			else
			{
				showmsg($LANG['MANAGE_ERROR']);
			}
			break;
		case 'preview':
			@header("Cache-Control: no-cache, must-revalidate");
			require_once(DIRCMS_ROOT.'include/form.class.php');	
			$f=new form($modelid);
			$base_r=$f->get();
			$more_r=$f->getmore();
			include admin_tlp('model_preview');
			break;
		case 'manage_fields':
			$result=$db->fetch_all("SELECT * FROM ".DB_PRE."db_fields WHERE ".DB_PRE."db_fields.modelid=".intval($modelid)." ORDER BY ".DB_PRE."db_fields.orderby ASC");
			if(isset($do_submit)) //排序
			{
				$i=0;
				foreach($id as $val)
				{
					$fieldname=$fieldsname[$i];
					$dw=$danwei[$i];
					$cs=$css[$i];
					$db->query("UPDATE `".DB_PRE."db_fields` SET `".DB_PRE."db_fields`.`orderby`=".intval($orderby[$i]).",`".DB_PRE."db_fields`.`css`='{$cs}',`".DB_PRE."db_fields`.`danwei`='{$dw}',`".DB_PRE."db_fields`.`fieldname`='{$fieldname}' WHERE `".DB_PRE."db_fields`.`id`=".intval($val),true);
					$i++;
				}
				$c->cache_fields($modelid);
				showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);
			}
			$r=cache_read('cache_model'.$modelid.'.cache.php',DIRCMS_ROOT.'data/cache_model/');
			$fields1=$db->get_fields(DB_PRE.'content');
			$fields2=$db->get_fields(DB_PRE.$r['name']);
			ob_start();
			var_dump(array_merge($fields1,$fields2),true);
			$fields=ob_get_contents();
			ob_end_clean();
			include admin_tlp('model_manage_fields');
			break;
		case 'disable_fields':
			$disable=intval($disable);
			if($db->query("UPDATE ".DB_PRE."db_fields SET ".DB_PRE."db_fields.disabled=$disable WHERE  ".DB_PRE."db_fields.id=".intval($id),true)){$c->cache_fields($modelid);showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);}
			else showmsg($LANG['MANAGE_ERROR'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);
			break;
		case 'setbase_fields':
			$isbase=intval($isbase);
			if($db->query("UPDATE ".DB_PRE."db_fields SET ".DB_PRE."db_fields.isbase=$isbase WHERE  ".DB_PRE."db_fields.id=".intval($id),true)){$c->cache_fields($modelid);showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);}
			else showmsg($LANG['MANAGE_ERROR'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);
			break;
		case 'issearch_fields':
			$issearch=intval($issearch);
			if($db->query("UPDATE ".DB_PRE."db_fields SET ".DB_PRE."db_fields.issearch=$issearch WHERE  ".DB_PRE."db_fields.id=".intval($id),true)){$c->cache_fields($modelid);showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);}
			else showmsg($LANG['MANAGE_ERROR'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);
			break;
		case 'chkfields':
			$r=$db->fetch_one("SELECT name FROM ".DB_PRE."model WHERE ".DB_PRE."model.id=".intval($modelid));
			echo (in_array($data,$db->get_fields(DB_PRE.$r['name']))||in_array($data,array('id','catid','typeid','areaid','groupid','template','title','style','thumb','keywords','downurl','videourl','description','posids','url','status','point','userid','username','userspace','pages','inputtime','updatetime','tags','islink','orderby','contentid','content')))?'yes':'no';
			exit();
			break;
		case 'add_fields':
			if(isset($do_submit))
			{
				$info['privilege']=implode(',',$privilege);
				$modelid=$info['modelid'];
				$info['maxsize']=(isset($info['maxsize']) && intval($info['maxsize']))?min(intval($info['maxsize']),255):255;				
				switch($info['preg'])
				{
					case 'limit3_50':
						$minsize=3;
						$maxsize=50;
						break;
					case 'userName':
						$minsize=3;
						$maxsize=30;
						break;
					case 'usePsw':
						$minsize=3;
						$maxsize=30;
						break;
					case 'email':
						$minsize=3;
						$maxsize=80;
						break;
					case 'qq':
						$minsize=3;
						$maxsize=15;
						break;
					case 'mobile':
						$minsize=10;
						$maxsize=15;
						break;
					case 'phone':
						$minsize=3;
						$maxsize=50;
						break;
					case 'ip':
						$minsize=12;
						$maxsize=15;
						break;	
					default:
						$minsize=0;
						$maxsize=255;
						break;						
				}
				$r=$db->fetch_one("SELECT name FROM ".DB_PRE."model WHERE ".DB_PRE."model.id=".intval($modelid));
				if(in_array($info['name'],$db->get_fields(DB_PRE.$r['name'])))showmsg('指定字段已存在!');
				if(in_array($info['formtype'],array('id','catid','typeid','areaid','groupid','template','title','style','thumb','keywords','description','posids','url','status','point','userid','username','inputtime','updatetime','tags','islink')))$info['name']=$info['formtype'];
				if(in_array($info['name'],array('id','catid','typeid','areaid','groupid','template','title','style','thumb','keywords','description','posids','url','status','downurl','videourl','point','userid','username','userspace','pages','inputtime','updatetime','tags','islink','orderby','contentid','content')))showmsg('指定字段无法使用!');
				if($info['issearch'])
				{
					if($info['searchby']=='ltgt' && (!preg_replace('/[^a-z0-9_]/i','',$searchbymin)||!preg_replace('/[^a-z0-9_]/i','',$searchbymax)))
					{
						showmsg('搜索变量不能为空!');
					}
					else
					{
						if(!preg_replace('/[^a-z0-9_]/i','',$searchbyvalue) && $info['searchby']!='ltgt')showmsg('搜索变量不能为空!');
					}
				}
				$info['searchbyvalue']=$info['searchby']=='ltgt'?preg_replace('/[^a-z0-9_]/i','',$searchbymin).'-'.preg_replace('/[^a-z0-9_]/i','',$searchbymax):preg_replace('/[^a-z0-9_]/i','',$searchbyvalue);

				if(in_array($info['formtype'],array('textarea','editor','images')))
				{
					$db->create_fields(DB_PRE.$r['name'],$info['name'],false);
				}else{
					$db->create_fields(DB_PRE.$r['name'],$info['name'],intval($info['maxsize']));
				}
				
				$db->insert(DB_PRE.'db_fields',$info,false);
				unset($r);
				$c->cache_fields($modelid);
				showmsg($LANG['MANAGE_SUCEESS']);
			}
			$membergroup=cache_read('membergroup.cache.php',DIRCMS_ROOT.'data/cache/');
			$privilege=explode(',',$r['privilege']);
			include admin_tlp('model_add_fields');
			break;
		case 'edit_fields':
			$r=$db->fetch_one("SELECT * FROM ".DB_PRE."db_fields WHERE ".DB_PRE."db_fields.id=".intval($id));

			if(isset($do_submit))
			{	
				$info['privilege']=implode(',',$privilege);
				$modelid=$info['modelid'];
				$info['maxsize']=(isset($info['maxsize']) && intval($info['maxsize']))?min(intval($info['maxsize']),255):255; 
				switch($info['preg'])
				{
					case 'limit3_50':
						$minsize=3;
						$maxsize=50;
						break;
					case 'userName':
						$minsize=3;
						$maxsize=30;
						break;
					case 'usePsw':
						$minsize=3;
						$maxsize=30;
						break;
					case 'email':
						$minsize=3;
						$maxsize=80;
						break;
					case 'qq':
						$minsize=3;
						$maxsize=15;
						break;
					case 'mobile':
						$minsize=10;
						$maxsize=15;
						break;
					case 'phone':
						$minsize=3;
						$maxsize=50;
						break;
					case 'ip':
						$minsize=12;
						$maxsize=15;
						break;	
					default:
						$minsize=0;
						$maxsize=255;
						break;						
				}
				unset($info['modelid'],$info['name'],$info['formtype']);
				if($info['issearch'])
				{
					if($info['searchby']=='ltgt' && (!preg_replace('/[^a-z0-9_]/i','',$searchbymin)||!preg_replace('/[^a-z0-9_]/i','',$searchbymax)))
					{
						showmsg('搜索变量不能为空!');
					}
					else
					{
						if(!preg_replace('/[^a-z0-9_]/i','',$searchbyvalue) && $info['searchby']!='ltgt')showmsg('搜索变量不能为空!');
					}
				}
				$info['searchbyvalue']=$info['searchby']=='ltgt'?preg_replace('/[^a-z0-9_]/i','',$searchbymin).'-'.preg_replace('/[^a-z0-9_]/i','',$searchbymax):preg_replace('/[^a-z0-9_]/i','',$searchbyvalue);
				$db->update(DB_PRE.'db_fields',$info,"id=".intval($id));
				$c->cache_fields($modelid);
				showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);
			}
			if(stripos($r['searchbyvalue'],'-'))
			{
				$searchbyvalue=explode('-',$r['searchbyvalue']);
				$searchbymin=$searchbyvalue[0];
				$searchbymax=$searchbyvalue[1];
			}

			$membergroup=cache_read('membergroup.cache.php',DIRCMS_ROOT.'data/cache/');
			$privilege=explode(',',$r['privilege']);
			include admin_tlp('model_edit_fields');
			unset($r);
			break;
		case 'delete_fields':
			$r=$db->fetch_one("SELECT name FROM ".DB_PRE."model WHERE ".DB_PRE."model.id=".intval($modelid));
			$db->query("ALTER TABLE `".DB_PRE."{$r['name']}` DROP `{$name}`",true);
			$db->query("DELETE FROM ".DB_PRE."db_fields WHERE ".DB_PRE."db_fields.id=".intval($id),true);
			$c->cache_fields($modelid);
			showmsg($LANG['MANAGE_SUCEESS'],ADMIN_FILE.'?file=model&action=manage_fields&modelid='.$modelid);
			break;
	}
?>