<?php
defined('IN_YUNYECMSAdmin') or exit('No permission.');
core::load_admin_class('admin');
class yunyecmsmodel extends YUNYE_admin{
	function __construct() {
		parent::__construct();
		$this->db = core::load_model('model_model');
		if(!getroot('model','modelview')){
			messagebox(Lan('no_permission_modelview'),'back',"warn");			
		 }
	  }
	 //加载首页
	  public function init() {
		if(!getroot('model','modelview')){
			messagebox(Lan('no_permission_modelview'),'back',"warn");			
		 }
		 $parnav='<li><a href=\"'.url_admin('init','yunyecmsmodel','',$this->hashurl['usvg']).'\" target=\"maincontent\">模型</a></li><li class=\"active\">模型管理</li>';
		 global $yunyecms_dbconfig;
		 $dbpre=$yunyecms_dbconfig['tablepre'];
		 $pagesize=20;
		 $sqlquery="select `modelid`, `modelname`,`tablename`,`modeltype`,`ordernum`,`tplhome`,`tpllist`,`tplcontent` from `#yunyecms_model`  ";
		 $where=" where `modelname`<>'' ";
		 $sqlcnt=" select count(*) from `#yunyecms_model` ";
		 $order=" order by `ordernum` asc ";
		  if(isset($_POST["searchkey"])){
		   $searchkey=usafestr(trim($_POST["searchkey"]));
		   if(empty($searchkey)){
			   messagebox(Lan('search_key_empty'),url_admin('init','','',$this->hashurl['usvg']),"warn");
			   exit;		
			   }else{
		        $where=" where `modelname`  like'%{$searchkey}%' ";
				   }
		 }
		 $pagearr=$this->db->pagelist($sqlcnt,$sqlquery,$where,$order,$pagesize);

		 if($pagearr["count"]!=0){
			 $list=$pagearr["query"];
			 	 foreach($list as $key => $val) {
                     $modelid=$val["modelid"];
                     $modeltype=$val["modeltype"];
				     switch($modeltype){
						 case 1:
						 $list[$key]['modeltype']='信息列表'; 
						 break;
						 case 2:
						 $list[$key]['modeltype']='单页面'; 
						 break;
						case 3:
						 $list[$key]['modeltype']='表单'; 
						 break;	
						default:
						 $list[$key]['modeltype']='信息列表'; 
					 }
			        }
			 $pages=$pagearr["page"];
		  }
		 require tpl_adm('yunyecmsmodel_list');
	  }
	  
	  public function fieldslist() {
		if(!getroot('model','fieldsview')){
			messagebox(Lan('no_permission_fieldsview'),'back',"warn");			
		 }		  
		  $modelid=$_REQUEST['modelid'];
		 	if(empty($modelid)){
			  messagebox("参数错误，模型ID不存在！",url_admin('init','','',$this->hashurl['usvg']),"info");
			} 
		  if(!is_numeric($modelid)){
			  messagebox("参数错误，模型ID不存在！",url_admin('init','','',$this->hashurl['usvg']),"info");
		   }
		   $modelid=usafestr(trim($modelid));
		   $curmodel=$this->db->find("select * from `#yunyecms_model` where `modelid`= {$modelid}");
		  
		 $parnav='<li><a href=\"'.url_admin('init','yunyecmsmodel','',$this->hashurl['usvg']).'\" target=\"maincontent\">模型</a></li><li class=\"active\">模型管理</li>';
		 $pagesize=20;
		 $sqlquery="select `id`, `modelid`, `fdname`, `fdtitle`, `fdtype`, `fdlen`, `ismt`, `isindex`, `isunique`, `ispage`, `tobr`, `showhtml`, `ordernum`, `formctrl`, `formsize`, `editorstyle`, `defaultvalue`, `isrequired`, `istougao`, `issearch`, `issys`, `isallowdel`, `remark`, `isdisplay`,`isadd` from `#yunyecms_modelfields`  ";
		 $where=" where modelid={$modelid}  ";
		 $sqlcnt=" select count(*) from `#yunyecms_modelfields` ";
		 $order=" order by `ordernum` asc ";
		  if(isset($_POST["searchkey"])){
		   $searchkey=usafestr(trim($_POST["searchkey"]));
		   if(empty($searchkey)){
			   messagebox(Lan('search_key_empty'),url_admin('init','','',$this->hashurl['usvg']),"warn");
			   exit;		
			   }else{
		        $where=" where `fdname`  like'%{$searchkey}%' ";
				   }
		 }
		  
		 $pagearr=$this->db->pagelist($sqlcnt,$sqlquery,$where,$order,$pagesize);
		 if($pagearr["count"]!=0){
			 $list=$pagearr["query"];
			 foreach($list as $key => $val) {
                     $modelid=$val["modelid"];
                     $formctrl=$val["formctrl"];
				     switch($formctrl){
						 case "text":
						 $list[$key]['formctrl']='文本框（text）'; 
						 break;
						 case "textarea":
						 $list[$key]['formctrl']='文本区域(textarea)'; 
						 break;
						 case "selctrl":
						 $list[$key]['formctrl']='选择框(select)'; 
						 break;	
						 case "radio":
						 $list[$key]['formctrl']='单选按钮(radio)'; 
						 break;	
						 case "checkbox":
						 $list[$key]['formctrl']='复选框(checkbox)'; 
						 break;
						 case "editor":
						 $list[$key]['formctrl']='编辑器(editor)'; 
						 break;
						 case "img":
						 $list[$key]['formctrl']='图片(img)'; 
						 break;	
						 case "file":
						 $list[$key]['formctrl']='文件(file)';
						 break;	 	 
						 default:
						 $list[$key]['formctrl']='文本框（text）';
					 }
			        $list[$key]['model']=$this->db->find("select * from `#yunyecms_model` where `modelid`= {$modelid}");
				 
			        }
			 $pages=$pagearr["page"];
		  }
		 require tpl_adm('modelfieldslist');
	  }
	  
	 public function model_add(){
		 global $yunyecms_dbconfig;
		 $dbpre=$yunyecms_dbconfig['tablepre'];
		 $modelid=0;
		 $cmodel=array();
		 if(!empty($_GET["id"])){
			 if(!getroot('model','modeledit')){
				messagebox(Lan('no_permission_modeledit'),'back',"warn");			
			 }			 
			$parnav='<li><a href=\"'.url_admin('init','yunyecmsmodel','',$this->hashurl['usvg']).'\" target=\"maincontent\">模型</a></li><li class=\"active\">修改模型</li>';
			$modelid=trim($_GET["id"]);
			 if(!is_numeric($modelid)){
			   messagebox(Lan('model_id_notnumber'),url_admin('init','','',$this->hashurl['usvg']),"warn");
			 }
			$maxorder=0;
			$cmodel=$this->db->find("select * from `#yunyecms_model` where `modelid`= {$modelid}");
			 if(empty($cmodel)){
				  messagebox(Lan('model_not_exist'),url_admin('model_add','model',array('id'=>$modelid),$this->hashurl['usvg']),"warn");		
			  }
		    $yyact="edit";
			$maxorder=$cmodel['ordernum'];
			}else{
			if(!getroot('model','modeladd')){
				messagebox(Lan('no_permission_modeladd'),'back',"warn");			
			 }
			$parnav='<li><a href=\"'.url_admin('init','yunyecmsmodel','',$this->hashurl['usvg']).'\" target=\"maincontent\">模型</a></li><li class=\"active\">添加模型</li>';
			 $modelmax=$this->db->find("select max(ordernum) as maxorder from `#yunyecms_model`");
			 if(!empty($modelmax)){
				$maxorder=$modelmax['maxorder']+1;
				}
		      $yyact=yyact_get("add");
				}
				if(isset($_POST["yyact"])){
				   $yyact_post=$_POST["yyact"];
				   $modelname=$_POST["modelname"];
				   $ordernum=$_POST["ordernum"];
				   $tplhome=$_POST["tplhome"];
				   $tpllist=$_POST["tpllist"];
				   $tplcontent=$_POST["tplcontent"];
				   $yyact_post=usafestr(trim($yyact_post));
				   $modelname=usafestr(trim($modelname));
				   $tplhome=usafestr(trim($tplhome));
				   $tpllist=usafestr(trim($tpllist));
				   $tplcontent=usafestr(trim($tplcontent));
				   if($yyact_post=="add"){
				       $tablename=$_POST["tablename"];
					   $modeltype=$_POST["modeltype"];
				       $tablename=usafestr(trim($tablename));
					   $this->insert_admin_model($dbpre,$modelname,$tablename,$modeltype,$ordernum,$tplhome,$tpllist,$tplcontent);
				  }
					
				 if($_POST["yyact"]=="edit"){
					   $id=$_POST["id"];
					   $oldmodelname=$_POST["oldmodelname"];
					   $this->edit_admin_model($id,$modelname,$oldmodelname,$ordernum,$tplhome,$tpllist,$tplcontent);
				  }		  
		  }
		require tpl_adm('model_add');
	 }
	

	  public function model_delete(){
			 if(!getroot('model','modeldel')){
				messagebox(Lan('no_permission_modeldel'),'back',"warn");			
			 }			  
		 if(!empty($_GET["id"])){
			 $id=trim($_GET["id"]);
			 if(!is_numeric($id)){
			   messagebox(Lan('model_id_notnumber'),url_admin(),"warn");
			 }
			 $cmodel=$this->db->find("select * from `#yunyecms_model` where `modelid`= {$id}");
			  if(empty($cmodel)){
				 messagebox(Lan('model_not_exist'),url_admin(),"warn");	
			  }
			 $modelid=$id;
			 $tbname=$cmodel['tablename'];
			 $modelname=$cmodel['modelname'];
			 $primarytable="`#yunyecms_m_{$tbname}`";
			 //$modeldatatb="`#yunyecms_m_{$tbname}_data`";
			 $sqldelmodtb=" DROP TABLE IF EXISTS {$primarytable}";
			 //$sqldelmodtbdata=" DROP TABLE IF EXISTS {$modeldatatb}";
			 $sqldelmodfiedls=" delete from `#yunyecms_modelfields` where modelid={$modelid}";
			 $query1=$this->db->query($sqldelmodtb);
			//$query2=$this->db->query($sqldelmodtbdata);
			 $query3=$this->db->query($sqldelmodfiedls);
			 if(!($query1&&$query3)){
				$this->db->Autocommit_rollback(); 
				 messagebox(Lan('model_delete_error'),url_admin("init"),"warn");
			 }else{
				$query=$this->db->query("delete from `#yunyecms_model` where modelid='$id'");
				if($query){
					$doing="删除数据模型——".$modelname;
					$yyact="deletemodel";
					insert_admlogs($doing,$yyact);
						messagebox(Lan('model_delete_success'),url_admin("init"),"success");
					}else{
						messagebox(Lan('model_delete_error'),url_admin("init"));
						}
			   }
		
			}
	 }	
	 
	private function checkmodel_exist($modelname,$tablename) {
		$modelname = trim($modelname);
		 if(empty($modelname)){
		     return false;
			 }else{
			  if ($this->db->find("select `modelname` from `#yunyecms_model` where `modelname`= '{$modelname}' or  `tablename`= '$tablename'")){
				  return true;
			  }				 
		  }
	  }
	
	private function add_admin_model($modelname,$tablename,$modeltype,$ordernum=0,$tplhome='',$tpllist='',$tplcontent='') {
					 $modelname=usafestr(trim($modelname));
					 $tablename=usafestr(trim($tablename));
					 $modeltype=intval(trim($modeltype));
					 $tplhome=uhtmlspecialchars(trim($tplhome));
					 $tpllist=uhtmlspecialchars(trim($tpllist));
					 $tplcontent=uhtmlspecialchars(trim($tplcontent));
					 $ordernum=intval(trim($ordernum));
		            $strsql="insert into `#yunyecms_model`(`modelname`,`tablename`,`modeltype`,`ordernum`,`tplhome`,`tpllist`,`tplcontent`) values('{$modelname}','{$tablename}','{$modeltype}',{$ordernum},'{$tplhome}','{$tpllist}','{$tplcontent}')";
					$query=$this->db->query($strsql);
	                $modelid=$this->db->insert_id();
					if($modelid){
				         return  $modelid;
					}else{
						return false;
					}
	 }
	
	private function insert_admin_model($dbpre,$modelname,$tablename,$modeltype,$ordernum,$tplhome,$tpllist,$tplcontent){
		          if(!is_numeric($modeltype)){
				    messagebox(Lan('modeltype_isnotnumber'),url_admin('model_add','','',$this->hashurl['usvg']),"warn");
				    }	
				  if(empty($tablename)){
				    messagebox(Lan('model_tablename_empty'),url_admin('model_add','','',$this->hashurl['usvg']),"error");			
				   }
				 $ordernum=trim($ordernum);
				 if(!is_numeric($ordernum)){
				   messagebox(Lan('ordernum_isnotnumber'),url_admin('model_add','','',$this->hashurl['usvg']),"warn");
				  }
				   if(empty($modelname)){
					   messagebox(Lan('model_name_empty'),url_admin('model_add','','',$this->hashurl['usvg']),"error");			
					 }	
				  $realtbname=$dbpre."m_".$tablename;
				 //$realtbdataname=$dbpre."m_".$tablename."_data";			
			      $tbcheck=$this->db->table_exists($realtbname);
				 if($tbcheck){
					 messagebox(Lan('model_table_exist'),url_admin('model_add','','',$this->hashurl['usvg']),"error");	
				 }else{
							switch($modeltype){
								case 1:	
									$sqlcreatemode=$this->db->getsql_create_infomode($realtbname);
									break;
								case 2:	
									$sqlcreatemode=$this->db->getsql_create_singlemode($realtbname);
									break;
								case 3:	
									$sqlcreatemode=$this->db->getsql_create_formmode($realtbname);
									break;
								 default:
								  $sqlcreatemode=$this->db->getsql_create_infomode($realtbname);
							 }
					 if($sqlcreatemode){
						  $query1=$this->db->query($sqlcreatemode);
					  }else{
				             messagebox("获取信息模型结构失败",url_admin('model_add','','',$this->hashurl['usvg']),"error");			
					  }
					 
					 $istable_exsit=false;
						   if($query1){
							    if($this->checkmodel_exist($modelname,$tablename)){
									$istable_exsit=true;
									$this->db->Autocommit_rollback(); 
									messagebox(Lan('model_already_exist'),url_admin('model_add','','',$this->hashurl['usvg']),"warn");		
					               }
						   }
					   if(!$istable_exsit){
				            $modelid=$this->add_admin_model($modelname,$tablename,$modeltype,$ordernum,$tplhome,$tpllist,$tplcontent);
							if($modelid){
											switch($modeltype){
												case 1:	
													$sqlmodefields=$this->db->getsql_infomodefields($modelid);
													break;
												case 2:	
													$sqlmodefields=$this->db->getsql_singlemodefields($modelid);
													break;
												case 3:	
													$sqlmodefields=$this->db->getsql_formmodefields($modelid);
													break;
												 default:
												  $sqlmodefields=$this->db->getsql_infomodefields($modelid);
											  }
			                     $query3=$this->db->query($sqlmodefields);
								 if($query3){
									$doing="添加数据模型——".$modelname;
									$yyact="addmodel";
									insert_admlogs($doing,$yyact);
								    messagebox(Lan('model_add_success'),url_admin('init','','',$this->hashurl['usvg']),"success");
								 }else{
									 $this->db->Autocommit_rollback();							     messagebox(Lan('model_createtable_error'),url_admin('model_add','','',$this->hashurl['usvg']),"error");	
								 }
								
							 } else{
								$this->db->Autocommit_rollback(); 
								messagebox(Lan('model_createtable_error'),url_admin('model_add','','',$this->hashurl['usvg']),"error");	
							}
					 }else{
						$this->db->Autocommit_rollback(); 
						messagebox(Lan('model_createtable_error'),url_admin('model_add','','',$this->hashurl['usvg']),"error");	
					 }
				 }
		
	}
	
	 
	private function edit_admin_model($id,$modelname,$oldmodelname,$ordernum,$tplhome='',$tpllist='',$tplcontent='') {
		 $modelname=usafestr(trim($modelname));
		 $oldmodelname=usafestr(trim($oldmodelname));
		 $tplhome=uhtmlspecialchars(trim($tplhome));
		 $tpllist=uhtmlspecialchars(trim($tpllist));
		 $tplcontent=uhtmlspecialchars(trim($tplcontent));
		 $ordernum=trim($ordernum);
		 $id=usafestr(intval(trim($id)));
		 if(!is_numeric($id)){
		   messagebox(Lan('id_notnumber'),url_admin('model_add','yunyecmsmodel',array('id'=>$id),$this->hashurl['usvg']),"warn");			
		  }
		  if(!is_numeric($ordernum)){
		   messagebox(Lan('ordernum_isnotnumber'),url_admin('model_add','yunyecmsmodel',array('id'=>$id),$this->hashurl['usvg']),"warn");			
		  }
		  if(empty($modelname)||empty($id)){
			   messagebox(Lan('model_name_empty'),url_admin('model_add','yunyecmsmodel',array('id'=>$id),$this->hashurl['usvg']),"warn");				
			 }
		  if($modelname!=$oldmodelname){
			    $num=$this->db->GetCount("select count(*) as total from `#yunyecms_model` where modelname='$modelname' and modelid<>$id limit 1");
			    if($num){ messagebox(Lan('model_already_exist'),url_admin('model_add','','',$this->hashurl['usvg']),"warn");
						}
				   }
				  $strsql="update `#yunyecms_model`  set `modelname`='$modelname',`ordernum`=$ordernum,`tplhome`='$tplhome',`tpllist`='$tpllist',`tplcontent`='$tplcontent' where modelid=$id";
				  $query=$this->db->query($strsql);
				   if($query){
					$doing="修改数据模型——".$modelname;
					$yyact="motifymodel";
					   insert_admlogs($doing,$yyact);
					   messagebox(Lan('model_edit_success'),url_admin('init','','',$this->hashurl['usvg']),"success");			
					 }
	   }
	
//添加字段
		 public function fieldsadd(){
			 global $yunyecms_dbconfig;
			 $dbpre=$yunyecms_dbconfig['tablepre'];
		     if(!empty($_REQUEST ['id'])){
			 if(!getroot('model','fieldsedit')){
				messagebox(Lan('no_permission_fieldsedit'),'back',"warn");			
			 }					 
		     $id = $_REQUEST ['id'];
			 if(!is_numeric($id)){
			   messagebox("字段参数错误",url_admin(),"warn");
			 }
			 $id=usafestr(trim($id));
		       $yyact="edit";
		        $rs=$this->db->find("select * from `#yunyecms_modelfields` where `id`= {$id}");
				if(empty($rs)){
			         messagebox("字段不存在",$_SERVER['HTTP_REFERER'],"warn");
				}else{
				$rs["formvalue"]=br2nl($rs["formvalue"]);
					if(empty($rs['modelid'])){
			         messagebox("模型不存在",$_SERVER['HTTP_REFERER'],"warn");
					}else{
					   $modelid=$rs['modelid'];
					}
				}
			    $parnav='<li><a href=\"'.url_admin("init").'\" target=\"maincontent\">模型列表</a></li><li><a href=\"'.url_admin("fieldslist","yunyecmsmodel",array("modelid"=>$modelid)).'\" target=\"maincontent\">字段列表</a></li><li class=\"active\">修改字段</li>';
			}else{
			 if(!getroot('model','fieldsadd')){
				messagebox(Lan('no_permission_fieldsadd'),'back',"warn");			
			 }					 
		        $yyact=yyact_get("add");
			    $modelid=$_REQUEST['modelid'];
			    $parnav='<li><a href=\"'.url_admin("init").'\" target=\"maincontent\">模型列表</a></li><li><a href=\"'.url_admin("fieldslist","yunyecmsmodel",array("modelid"=>$modelid)).'\" target=\"maincontent\">字段列表</a></li><li class=\"active\">添加字段</li>';
				}
				  if(empty($modelid)){
						messagebox("参数错误，模型ID不存在！",url_admin('model_add','yunyecmsmodel',array('modelid'=>$modelid)),"warn");		
					} 
				  if(!is_numeric($modelid)){
					  messagebox("参数错误，模型ID不存在！",url_admin('model_add','yunyecmsmodel',array('modelid'=>$modelid)),"warn");			
				   }
			 	  $modelid=usafestr(trim($modelid));
				  $curmodel=$this->db->find("select * from `#yunyecms_model` where `modelid`= {$modelid}");
				  if(empty($curmodel)){
					  messagebox(Lan('model_not_exist'),url_admin('fieldsadd','yunyecmsmodel',array('modelid'=>$modelid)),"warn");		
				   }			 

				  $modelfieldsmax=$this->db->find("select max(ordernum) as maxorder from `#yunyecms_modelfields`");
				  if(!empty($modelfieldsmax)){
					$maxorder=$modelfieldsmax['maxorder']+1;
					}
			 
				if(isset($_POST["yyact"])){
				   $yyact_post=$_POST["yyact"];
				   $yyact_post=usafestr(trim($yyact_post));
				   $modelid=$_POST["modelid"];
				   $fdname=$_POST["fdname"];
				   $fdtitle=$_POST["fdtitle"];
				   $fdtitle_en=$_POST["fdtitle_en"];
				   $fdtype=$_POST["fdtype"];
				   $fdlen=$_POST["fdlen"];
				   $defaultvalue=$_POST["defaultvalue"];
				   $language= empty($_POST["language"]) ? 1 :  $_POST["language"]; 
				   $isdisplay= empty($_POST["isdisplay"]) ? 0 :  $_POST["isdisplay"]; 
				   $isadd= empty($_POST["isadd"]) ? 0 :  $_POST["isadd"]; 
				   $issearch= empty($_POST["issearch"]) ? 0 :  $_POST["issearch"]; 
				   $isrequired= empty($_POST["isrequired"]) ? 0 :  $_POST["isrequired"]; 
				   $formctrl=$_POST["formctrl"];
				   $formsize=$_POST["formsize"];
				   $formwidth=$_POST["formwidth"];
				   $formheight=$_POST["formheight"];
				   $formvalue=$_POST["formvalue"];
				   $istougao= empty($_POST["istougao"])? 0 : $_POST["isallowdel"]; 
				   $isallowdel= empty($_POST["isallowdel"]) ? 0 :  $_POST["isallowdel"]; 
				   $isindex= empty($_POST["isindex"]) ? 0 :  $_POST["isindex"]; 
				   $isunique= empty($_POST["isunique"]) ? 0 :  $_POST["isunique"]; 
				   $ispage= empty($_POST["ispage"]) ? 0 :  $_POST["ispage"]; 
				   $ordernum= empty($_POST["ordernum"]) ? 0 :  $_POST["ordernum"]; 	
					
		   $fdname=usafestr(trim($fdname));
		   $fdtitle=usafestr(trim($fdtitle));
		   $fdtype=usafestr(trim($fdtype));
		   $formctrl=usafestr(trim($formctrl));
		   $defaultvalue=usafestr(trim($defaultvalue));
		   $formvalue=usafestr(trim($formvalue));
					
		   if(empty($fdname)){
				messagebox("字段名不能为空，谢谢!",$_SERVER['HTTP_REFERER'],"info");		
		   }
		   if(empty($fdtitle)){
				messagebox("字段标识不能为空，谢谢!",$_SERVER['HTTP_REFERER'],"info");		
		   }
		   if(!is_numeric($language)){
				messagebox("语言必须为数字，谢谢!",$_SERVER['HTTP_REFERER'],"info");		
			 }					
					
			if($yyact_post=="add"){
				$this->insert_modelfields($dbpre,$modelid,$fdname,$fdtitle,$fdtitle_en,$fdtype,$fdlen,$defaultvalue,$language,$isdisplay,$formctrl,$formsize,$formwidth,$formheight,$formvalue,$istougao,$isallowdel,$isindex,$isunique,$ispage,$ordernum,$isadd,$issearch,$isrequired);
				   }
				 if($_POST["yyact"]=="edit"){
					   $id=$_POST["id"];
					   $oldfdname=$_POST["oldfdname"];
				$this->update_modelfields($id,$dbpre,$oldfdname,$modelid,$fdname,$fdtitle,$fdtitle_en,$fdtype,$fdlen,$defaultvalue,$language,$isdisplay,$formctrl,$formsize,$formwidth,$formheight,$formvalue,$istougao,$isallowdel,$isindex,$isunique,$ispage,$ordernum,$isadd,$issearch,$isrequired);
				  }		  
		     }
			 
			 
			 
		require tpl_adm('model_fieldsadd');
	 }
	
	
	//插入字段
	private function insert_modelfields($dbpre,$modelid,$fdname,$fdtitle,$fdtitle_en,$fdtype,$fdlen,$defaultvalue,$language,$isdisplay,$formctrl,$formsize,$formwidth,$formheight,$formvalue,$istougao,$isallowdel,$isindex,$isunique,$ispage,$ordernum,$isadd,$issearch,$isrequired){
		      $this->db->Autocommit_start();
               $curmodel=$this->db->find("select * from `#yunyecms_model` where `modelid`= {$modelid}");
				  if(empty($curmodel)){
					  messagebox(Lan('model_not_exist'),url_admin('fieldsadd','yunyecmsmodel',array('modelid'=>$modelid)),"warn");		
				   }	
			$data['modelid']=$modelid;
			$data['fdname']=$fdname;
			$data['fdtitle']=$fdtitle;
			$data['fdtitle_en']=$fdtitle_en;
			$data['fdtype']=$fdtype;
			$data['fdlen']=$fdlen;
			$data['defaultvalue']=$defaultvalue;
			$data['language']=$language;
			$data['isdisplay']=$isdisplay;
			$data['formctrl']=$formctrl;
			$data['formsize']=$formsize;
			$data['formwidth']=$formwidth;
			$data['formheight']=$formheight;
			$data['formvalue']=$formvalue;
			$data['istougao']=$istougao;
			$data['isallowdel']=$isallowdel;
			$data['isindex']=$isindex;
			$data['isunique']=$isunique;
			$data['ispage']=$ispage;
			$data['ordernum']= $ordernum;
			$data['issys']= 0;
			$data['isadd']=$isadd;
			$data['issearch']=$issearch;
			$data['isrequired']=$isrequired;
		    $checkfieldcnt=$this->db->GetCount("select count(*) from  `#yunyecms_modelfields` where modelid={$modelid} and fdtitle='{$fdtitle}' ");
				if($checkfieldcnt>0){
					   messagebox("该字段已经存在，请重新输入!",$_SERVER['HTTP_REFERER'],"warn");		
					   exit;
				}	
		    if(!is_letternum($fdname)){
				 messagebox("字段名必须是字母、数字、下划线!",$_SERVER['HTTP_REFERER'],"warn");		
			 }	
			   $tablename="m_".$curmodel['tablename'];
			   $realtablename=$dbpre."m_".$curmodel['tablename'];
			   if($this->db->field_exists($fdname,$tablename)){
				 messagebox("该字段已经存在，请重新输入!",$_SERVER['HTTP_REFERER'],"warn");		
				}else{
			    $reid=$this->db->insert($data,"modelfields");
				if($reid !== false){
					$sqlalt="ALTER TABLE  `$realtablename` ADD  `{$fdname}`  ";
					if(!empty($fdtype)){
						switch($fdtype){
							case "VARCHAR":	
									if(!empty($fdlen)) {$sqlalt=$sqlalt.$fdtype."({$fdlen}) NULL"; }
								   else{
									  $sqlalt=$sqlalt.$fdtype."(500) NULL"; 
									 }
								     if(empty($defaultvalue)){ $defaultvalue="";}
								     $sqlalt=$sqlalt." DEFAULT '{$defaultvalue}' ";
							   break;
							 case "CHAR":	
									 if(!empty($fdlen)) {
										   $fdlen= $fdlen>=255 ? 255 : $fdlen; 
										   $sqlalt=$sqlalt.$fdtype."({$fdlen}) NULL"; 
									   }
									   else{
										  $sqlalt=$sqlalt.$fdtype."(255) NULL"; 
										 }
									  if(empty($defaultvalue)){ $defaultvalue="";}
									  $sqlalt=$sqlalt." DEFAULT '{$defaultvalue}' ";
							   break;
							   case "TINYINT":	
							   case "SMALLINT":	
							   case "BIGINT":	
							   case "INT":
							   case "FLOAT":
							   case "DOUBLE":
							   if(empty($defaultvalue)){ $defaultvalue=0;}
							   if(!is_numeric($defaultvalue)){ $defaultvalue=0;}
							   $sqlalt=$sqlalt.$fdtype." NULL DEFAULT '{$defaultvalue}' ";
							   break;
							default:
								$sqlalt=$sqlalt.$fdtype." NULL ";
						}
					}
					if($fdtype!="TEXT" && $fdtype!="MEDIUMTEXT" && $fdtype!="LONGTEXT"){
						if($data['isindex']==1)//加索引
						{
							$sqlalt=$sqlalt." , ADD INDEX (  `{$fdname}` ) ";
						}	
						if($data['isunique']==1)//加唯一
						{   
							if($fdtype!="VARCHAR"){
							  $sqlalt=$sqlalt." , ADD UNIQUE (  `{$fdname}` ) ";
							}
						}			
					  }
				    $keysql=$this->db->query($sqlalt);
					
					if(!$keysql){
				          $this->db->Autocommit_rollback(); 
					 }
					 else{
				          $this->db->Autocommit_commit(); 
					 }
					
					$doing="添加{$curmodel['modelname']}模型{$fdtitle}字段——".$fdname."——".$realtablename;
					$yyact="insertfields";
					insert_admlogs($doing,$yyact);
					messagebox("字段添加成功",url_admin('fieldslist','yunyecmsmodel',array('modelid'=>$modelid)),"success");
					/*				   
					ALTER TABLE  `yunyecms_products` CHANGE  `ccc`  `ccc` FLOAT( 10, 2 ) NULL DEFAULT NULL ;
					ALTER TABLE  `yunyecms_products` DROP  `ccc` ;
					*/
				  }else{
				      messagebox('字段添加失败!',$_SERVER['HTTP_REFERER'],"info");
				}
			}
	  }	
	
	private function update_modelfields($id,$dbpre,$oldfdname,$modelid,$fdname,$fdtitle,$fdtitle_en,$fdtype,$fdlen,$defaultvalue,$language,$isdisplay,$formctrl,$formsize,$formwidth,$formheight,$formvalue,$istougao,$isallowdel,$isindex,$isunique,$ispage,$ordernum,$isadd,$issearch,$isrequired){
		  $this->db->Autocommit_start();
		 if(empty($fdname)||empty($id)){
			   messagebox("该字段不存在或参数错误",$_SERVER['HTTP_REFERER'],"warn");				
			 }
		  if($fdname!=$oldfdname){
						$checkfieldcnt=$this->db->GetCount("select count(*) from  `#yunyecms_modelfields` where modelid={$modelid} and fdname='{$fdname}' and id<>$id  ");
						if($checkfieldcnt>0){
						messagebox("该字段已经存在，请重新输入!",$_SERVER['HTTP_REFERER'],"warn");		
						exit;
						}	
				   }		
			 if(!is_numeric($id)){
			    messagebox("参数错误!，字段ID必须为数字",$_SERVER['HTTP_REFERER'],"warn");				
			   }
			 if(empty($modelid)){
			      messagebox("参数错误!，模型ID不存在!",$_SERVER['HTTP_REFERER'],"warn");				
				} 
			  if(!is_numeric($modelid)){
			      messagebox("参数错误!，模型参数错误!",$_SERVER['HTTP_REFERER'],"warn");				
			   }
			  $curmodel=$this->db->find("select * from `#yunyecms_model` where `modelid`= {$modelid}");
			  if(empty($curmodel)){
				  messagebox(Lan('model_not_exist'),url_admin('fieldsadd','yunyecmsmodel',array('id'=>$id)),"warn");		
			   }
		
			  $curmodelfields=$this->db->find("select * from `#yunyecms_modelfields` where `id`= {$id}");
			  if(empty($curmodelfields)){
			     messagebox("字段不存在!",$_SERVER['HTTP_REFERER'],"warn");				
				  }
		   if(empty($fdname)){
			     messagebox("字段名不能为空，谢谢!",$_SERVER['HTTP_REFERER'],"warn");				
		   }
		   if(empty($fdtitle)){
			     messagebox("字段标识不能为空，谢谢!",$_SERVER['HTTP_REFERER'],"warn");				
		   }
		   if(!is_numeric($language)){
			     messagebox("语言必须为数字，谢谢!",$_SERVER['HTTP_REFERER'],"warn");				
			 }
		
			$data['id']=$id;
			$data['modelid']=$modelid;
			$data['fdname']=$fdname;
			$data['fdtitle']=$fdtitle;
			$data['fdtitle_en']=$fdtitle_en;
			$data['fdlen']=$fdlen;
			$data['defaultvalue']=$defaultvalue;
			$data['language']=$language;
			$data['isdisplay']=$isdisplay;
			$data['formctrl']=$formctrl;
			$data['formsize']=$formsize;
			$data['formwidth']=$formwidth;
			$data['formheight']=$formheight;
			$data['formvalue']=$formvalue;
			$data['istougao']=$istougao;
			$data['isallowdel']=$isallowdel;
			$data['isindex']=$isindex;
			$data['isunique']=$isunique;
			$data['ispage']=$ispage;
			$data['ordernum']= $ordernum;
			$data['isadd']= $isadd;
			$data['issearch']= $issearch;
			$data['isrequired']=$isrequired;
		    if($curmodelfields['fdtitle']!=$fdtitle){
						$checkfieldcnt=$this->db->GetCount("select count(*) from  `#yunyecms_modelfields` where modelid={$modelid} and fdtitle='{$fdtitle}' and id<>$id  ");
						if($checkfieldcnt>0){
						messagebox("该字段名已经存在，请重新输入!",$_SERVER['HTTP_REFERER'],"warn");		
						exit;				
			   }
			}
		    if(!is_letternum($fdname)){
				messagebox("字段名必须是字母、数字、下划线!",$_SERVER['HTTP_REFERER'],"warn");		
			}
			  $tablename="m_".$curmodel['tablename'];
			  $realtablename=$dbpre."m_".$curmodel['tablename'];
			 if($curmodelfields['fdname']!=$fdname){
				 if($this->db->field_exists($fdname,$tablename)){
					 messagebox("该字段已经存在，请重新输入!",$_SERVER['HTTP_REFERER'],"warn");		
				   }					
			 }		
			 $reid=$this->db->update($data,"id={$id}","modelfields");
				if($reid !== false){
					$sqlalt="ALTER TABLE  `{$realtablename}` CHANGE `{$curmodelfields['fdname']}` `{$fdname}`  ";
					if(!empty($fdtype)){
						switch($fdtype){
							case "VARCHAR":	
									if(!empty($fdlen)) {$sqlalt=$sqlalt.$fdtype."({$fdlen}) NULL"; }
								   else{
									  $sqlalt=$sqlalt.$fdtype."(500) NULL"; 
									 }
								     if(empty($defaultvalue)){ $defaultvalue="";}
								     $sqlalt=$sqlalt." DEFAULT '{$defaultvalue}' ";
							   break;
							 case "CHAR":	
									 if(!empty($fdlen)) {
										   $fdlen= $fdlen>=255 ? 255 : $fdlen; 
										   $sqlalt=$sqlalt.$fdtype."({$fdlen}) NULL"; 
									   }
									   else{
										  $sqlalt=$sqlalt.$fdtype."(255) NULL"; 
										 }
									  if(empty($defaultvalue)){ $defaultvalue="";}
									  $sqlalt=$sqlalt." DEFAULT '{$defaultvalue}' ";
							   break;
							   case "TINYINT":	
							   case "SMALLINT":	
							   case "BIGINT":	
							   case "INT":
							   case "FLOAT":
							   case "DOUBLE":
							   if(empty($defaultvalue)){ $defaultvalue=0;}
							   if(!is_numeric($defaultvalue)){ $defaultvalue=0;}
							   $sqlalt=$sqlalt.$fdtype." NULL DEFAULT '{$defaultvalue}' ";
							   break;
							default:
								$sqlalt=$sqlalt.$fdtype." NULL ";
						}
					}
				    if($fdtype!="TEXT" && $fdtype!="MEDIUMTEXT" && $fdtype!="LONGTEXT"){
						if($data['isindex']==1)//加索引
						{
							$sqlalt=$sqlalt." , ADD INDEX (  `{$fdname}` ) ";
						}	
						if($data['isunique']==1)//加唯一
						{   
							if($fdtype!="VARCHAR"){
							  $sqlalt=$sqlalt." , ADD UNIQUE (  `{$fdname}` ) ";
							}
						}			
					  }
					$keysql=$this->db->query($sqlalt);
					if(!$keysql){
				          $this->db->Autocommit_rollback(); 
					 }
					 else{
				          $this->db->Autocommit_commit(); 
					 }
					
					$doing="修改{$curmodel['modelname']}模型{$curmodelfields['fdtitle']}字段——{$curmodelfields['fdname']}——$realtablename";
					$yyact="updatefields";
					insert_admlogs($doing,$yyact);					
					messagebox("字段修改成功",url_admin('fieldslist','yunyecmsmodel',array('modelid'=>$modelid)),"success");			
					/*				   
					ALTER TABLE  `yunyecms_products` CHANGE  `ccc`  `ccc` FLOAT( 10, 2 ) NULL DEFAULT NULL ;
					ALTER TABLE  `yunyecms_products` DROP  `ccc` ;
					*/
				  }else{
					 messagebox("字段修改失败",url_admin('fieldslist','yunyecmsmodel',array('modelid'=>$modelid)),"warn");			
				 }
	    }	
	
		function delfields(){
			 if(!getroot('model','fieldsdel')){
				messagebox(Lan('no_permission_fieldsdel'),'back',"warn");			
			 }	
			 global $yunyecms_dbconfig;
			 $dbpre=$yunyecms_dbconfig['tablepre'];
			 $id=$_REQUEST["id"];
			 if(empty($id)){
				  messagebox("字段修改失败",$_SERVER['HTTP_REFERER'],"warn");			
				} 
			 if(!is_numeric($id)){
				  messagebox("参数错误!，字段ID必须为数字",$_SERVER['HTTP_REFERER'],"warn");			
			   }
			 $id=usafestr(trim($id));
		      $curmodelfields=$this->db->find("select * from `#yunyecms_modelfields` where `id`= {$id}");
			  if(empty($curmodelfields)){
			     messagebox("字段不存在!",$_SERVER['HTTP_REFERER'],"warn");				
				  }else{
					$modelid=$curmodelfields['modelid'];
				  
				  $curmodel=$this->db->find("select * from `#yunyecms_model` where `modelid`= {$modelid}");
				  if(empty($curmodel)){
					  messagebox(Lan('model_not_exist'),$_SERVER['HTTP_REFERER'],"warn");	
				   }				  
				}
			  $map['id']=$id;
			  if($curmodelfields['issys']==1){
				   messagebox("操作失败，系统字段不允许删除!",url_admin('fieldslist','yunyecmsmodel',array('modelid'=>$modelid)),"warn");			
			  }
			  if($curmodelfields['isallowdel']==0){
				   messagebox("操作失败，该字段不允许删除!",url_admin('fieldslist','yunyecmsmodel',array('modelid'=>$modelid)),"warn");			
			  }			
			  $redel=$this->db->delete($map,"modelfields");
			  $tablename="m_".$curmodel['tablename'];
			  $realtablename=$dbpre."m_".$curmodel['tablename'];
			 if($redel!== false){
					$sqlalt="ALTER TABLE  `{$realtablename}` DROP `{$curmodelfields['fdname']}` ";
				  	$keysql=$this->db->query($sqlalt);
					if(!$keysql){
				          $this->db->Autocommit_rollback(); 
					 }
					 else{
				          $this->db->Autocommit_commit(); 
					 }
				  if($keysql!== false){
						$doing="删除{$curmodel['modelname']}模型{$curmodelfields['fdtitle']}字段——{$curmodelfields['fdname']}——".$realtablename;
						$yyact="deletefields";
						insert_admlogs($doing,$yyact);					  
					   messagebox("删除字段成功",url_admin('fieldslist','yunyecmsmodel',array('modelid'=>$modelid)),"success");			
				  }else{
					    messagebox("删除失败",url_admin('fieldslist','yunyecmsmodel',array('modelid'=>$modelid)),"warn");			
				  }
				 
			  }else{
					    messagebox("删除失败",url_admin('fieldslist','yunyecmsmodel',array('modelid'=>$modelid)),"warn");			
			  }
		}
		
	
	
	
}




?>
