<?php
/**
 * model.php	基础数据操作类
 * @copyright			(C) 2019 YUNYECMS
 * @lastmodify			2019-2-24
 */
core::load_class("yymysqli",0);
class model {
	//数据库配置
	protected $db_config = '';
	//数据库连接
	protected $db = '';
	//数据表名
	protected $tablename = '';
	protected $dbname = '';
	//表前缀
	public  static $db_tablepre = '';	
	//public  static $strtablepre = 'NDE2YTI0NzE3Nzk5MDBiYzIxSTNsMWJubGxZMjF6WHc9PTI5NDMwMjJkY2Y3M2I4NzExN2ZhNzEzNzhhN2JkOGE0NGRl';	
	public  static $strtablepre = '#yunyecms_';	
	public $Autocommit = '';
	public function __construct() {
	    global $yunyecms_dbconfig;
		if(empty($this->db_config)){
			$this->db_config = $yunyecms_dbconfig;
		}
		//self::$strtablepre=yunyecms_strdecode(self::$strtablepre);
		self::$db_tablepre = $this->db_config['tablepre'];
		$this->dbname=$this->db_config['database'];
		$this->tablename = $this->db_config['tablepre'].$this->tablename;
		$this->db = yymysqli::GetObject($this->db_config);
	}
	
	//设置表名称
	final public function tablename($tablename){
		if($tablename)$this->tablename=$this->db_config['tablepre'].$tablename;
	}	
	
	//根据sql语句获取数据列表
	final public function select($sql,$info=array('type'=>1,'key'=>'')){
		if(empty($sql))return false;
		if(!is_array($info))return false;	
		$sql=self::replace_tablepre($sql);
		$this->db->execute($sql);
		$type=isset($info['type']) ? $info['type'] : 1;
		$key=isset($info['key']) ? $info['key'] : '';		
		return $this->db->get_fetch_array($type,$key);
	}
	
	//根据sql语句获取单条数据
	final public function find($sql,$info=array('type'=>1)){
		if(empty($sql))return false;
		if(!is_array($info))return false;	
		$type=isset($info['type']) ? $info['type'] : 1;
		$sql=self::replace_tablepre($sql);	
		$this->db->execute($sql);
		return $this->db->get_one(NULL,$type);
	}
		/**
	 * 获取单条数据
	 * @param $where 		查询条件[例`name`='$name']
	 * @param $fields 		需要查询的字段值[例`name`,`gender`,`birthday`]
	 * @param $order 		排序方式	[默认按数据库默认方式排序]
	 * @param $group 		分组方式	[默认为空]
	 * @param $key          返回数组按键名排序
	 * @return array		查询结果集数组
	 */
	final public function getone($where = '',  $order = '',$fields = '*',$table,$group = '',$info=array('type'=>1,'key'=>'')) {
		 if (is_array($where)) $where = $this->arraytosql($where);
		 $where = $where == '' ? '' : ' WHERE '.$where;
		 $order = $order == '' ? '' : ' ORDER BY '.$order;
		 $group = $group == '' ? '' : ' GROUP BY '.$group;
		 $limit = ' LIMIT 1';
		 $field = explode(',', $fields);
		 array_walk($field, array($this->db, 'add_special_char'));
		 $data = implode(',', $field);
		  if(empty($table)){
			$table=$this->tablename;
		  }else{
		  $table=self::$db_tablepre.$table;
		  }
		$sql = 'SELECT '.$data.' FROM `'.$this->dbname.'`.`'.$table.'`'.$where.$group.$order.$limit;;
		$type=isset($info['type']) ? $info['type'] : 1;
		$sql=self::replace_tablepre($sql);	
		$this->db->execute($sql);
		return $this->db->get_one(NULL,$type);
	}
	/**
	 * 执行sql查询
	 * @param $where 		查询条件[例`name`='$name']
	 * @param $fields 		需要查询的字段值[例`name`,`gender`,`birthday`]
	 * @param $limit 		返回结果范围[例：10或10,10 默认为空]
	 * @param $order 		排序方式	[默认按数据库默认方式排序]
	 * @param $group 		分组方式	[默认为空]
	 * @param $key          返回数组按键名排序
	 * @return array		查询结果集数组
	 */
	final public function getlist($where = '',  $limit = '20', $order = '',$fields = '*',$table,$group = '',$info=array('type'=>1,'key'=>'')) {
		if (is_array($where)) $where = $this->arraytosql($where);
		 if(empty($table)){
			$table=$this->tablename;
		  }else{
		    $table=self::$db_tablepre.$table;
		  }
		return $this->db->getlist($fields, $table, $where, $limit, $order, $group, $info);
	 }	
	
	final public function getbyid($id,$table,$fields="id"){
		 if(empty($table)){
			$table=$this->tablename;
		  }else{
		  $table=self::$db_tablepre.$table;
		  }
		$strsql="select * from  `{$table}`  where $fields=$id";
		return $this->find($strsql);
	}
	final public function getfield($field,$id,$table,$fields="id"){
		if(empty($table)){
			$table=$this->tablename;
		  }else{
		  $table=self::$db_tablepre.$table;
		  }
		$strsql="select $field from  `{$table}`  where $fields=$id";
		$re=$this->find($strsql);
		if($re) {
			return $re[$field];
		}else{
			return false;
		}
	}		
	
	//根据sql语句获取分页数据
	  final public function pagelist($sqlcnt,$sqlquery,$where='',$strorder='order by `id` desc',$listRows='20') {
		if(is_numeric($sqlcnt)){
            $count = $sqlcnt;
		 }else{
		    $sqlcnt=$sqlcnt." ".$where;
		    $sqlcnt=self::replace_tablepre($sqlcnt);
            $count = $this->GetCount($sqlcnt);
		 }
		$returnarray=array();
		$returnarray["count"]=$count;
         if($count > 0){
		   if(defined("LAN")&&LAN=='en'){
              core::load_class("page_eng",0);
		    }else{
              core::load_class("page",0);
		   }
            if (!empty($_REQUEST ['pagesize'])&&is_numeric($_REQUEST ['pagesize'])) {
                $listRows = $_REQUEST ['pagesize'];
            }
            $p = new Page($count, $listRows);
			$sqlquery=$sqlquery." ".$where." ".$strorder ." limit {$p->firstRow},{$p->listRows}";
			$sqlquery=self::replace_tablepre($sqlquery);
            $query = $this->select($sqlquery);
            if(!empty($_POST)){
				  foreach ($_POST as $key => $val) {
					  if (!is_array($val)) {
						  $p->parameter .= "$key=" . urlencode($val) . "&";
					  }
				  }
				}
			  if(!empty($_GET)){
				  foreach ($_GET as $key => $val) {
					  if (!is_array($val)) {
						  $p->parameter .= "$key=" . urlencode($val) . "&";
					  }
				  }
				}
            $page = $p->show();
			$returnarray["query"]=$query;
			$returnarray["page"]=$page;
        }
        return $returnarray;
    }
	
	
  final public function htmlpagelist($sqlcnt,$sqlquery,$where='',$strorder='order by `id` desc',$curpage,$listRows='20',$urlpath) {
		if(is_numeric($sqlcnt)){
            $count = $sqlcnt;
		 }else{
		    $sqlcnt=$sqlcnt." ".$where;
		    $sqlcnt=self::replace_tablepre($sqlcnt);
            $count = $this->GetCount($sqlcnt);
		 }
		$returnarray=array();
		$returnarray["count"]=$count;
         if($count > 0){
		   if(defined("LAN")&&LAN=='en'){
			  core::load_app_class('page_eng','htmlpage','addons',0);
		    }else{
			  core::load_app_class('page','htmlpage','addons',0);
		   }
            $p = new Page($count, $listRows,$curpage,$urlpath);
			$sqlquery=$sqlquery." ".$where." ".$strorder ." limit {$p->firstRow},{$p->listRows}";
			$sqlquery=self::replace_tablepre($sqlquery);
            $query = $this->select($sqlquery);
            if(!empty($_POST)){
				  foreach ($_POST as $key => $val) {
					  if (!is_array($val)) {
						  $p->parameter .= "$key=" . urlencode($val) . "&";
					  }
				  }
				}
			  if(!empty($_GET)){
				  foreach ($_GET as $key => $val) {
					  if (!is_array($val)) {
						  $p->parameter .= "$key=" . urlencode($val) . "&";
					  }
				  }
				}
            $page = $p->show();
			$returnarray["query"]=$query;
			$returnarray["page"]=$page;
        }
        return $returnarray;
    }	
	
	
	
		/**
	 * 根据传递参数获取分页数据
	 * @param $where 		查询条件[例`name`='$name']
	 * @param $fields 		需要查询的字段值[例`name`,`gender`,`birthday`]
	 * @param $listRows     每页的条数
	 * @param $order 		排序方式	[默认按数据库默认方式排序]
	 * @param $group 		分组方式	[默认为空]
	 * @param $key          返回数组按键名排序
	 * @return array		查询结果集数组
	 */
	  final public function infolist($where = '',$listRows='20', $order = '',$fields = '*',$table='',$group = '') {
		 $where = $where == '' ? '' : ' WHERE '.$where;
		 $order = $order == '' ? '' : ' ORDER BY '.$order;
		 $group = $group == '' ? '' : ' GROUP BY '.$group;
		 $field = explode(',', $fields);
		 array_walk($field, array($this->db, 'add_special_char'));
		 $data = implode(',', $field);
		  if(empty($table)){
			$table=$this->tablename;
		  }else{
		  $table=self::$db_tablepre.$table;
		  }
		 $sqlcnt = 'SELECT count(*) FROM `'.$this->dbname.'`.`'.$table.'`'.$where; 
         $count = $this->GetCount($sqlcnt);
		 $returnarray=array();
		 $returnarray["count"]=$count;
         if($count > 0){
		   if(defined("LAN")&&LAN=='en'){
              core::load_class("page_eng",0);
		    }else{
              core::load_class("page",0);
		   }
           if (!empty($_REQUEST ['pagesize'])) {
                $listRows = $_REQUEST ['pagesize'];
            }
            $p = new Page($count, $listRows);
		    $sqlquery = 'SELECT '.$data.' FROM `'.$this->dbname.'`.`'.$table.'`'.$where.$group.$order." limit {$p->firstRow},{$p->listRows}";
            $query = $this->select($sqlquery);
            if(!empty($_POST)){
				  foreach ($_POST as $key => $val) {
					  if (!is_array($val)) {
						  $p->parameter .= "$key=" . urlencode($val) . "&";
					  }
				  }
				}
			  if(!empty($_GET)){
				  foreach ($_GET as $key => $val) {
					  if (!is_array($val)) {
						  $p->parameter .= "$key=" . urlencode($val) . "&";
					  }
				  }
				}
            $page = $p->show();
			$returnarray["query"]=$query;
			$returnarray["page"]=$page;
        }
        return $returnarray;
    }	
	
	
	
	//获取数据总数1
	final public function GetCount($sql){	
		if(empty($sql))return false;		
		$sql=self::replace_tablepre($sql);
		$sql = preg_replace ("/^SELECT (.*) FROM/i", "SELECT COUNT(*) FROM",$sql);		
		$lastresult=$this->db->execute($sql);
		return $this->db->num_count($lastresult);
	}
	//获取数据总数2
	final public function GetNum($sql){
		if(empty($sql))return false;
		$sql=self::replace_tablepre($sql);
		$lastresult=$this->db->execute($sql);
		return $this->db->num_rows($lastresult);
	}	
	
	final static private function replace_tablepre($sql){		
		static $sqlarr=array();		
		$key=md5($sql);
		if(isset($sqlarr[$key])){
			return $sqlarr[$key];
		}
		$sqlarr[$key]=str_ireplace(self::$strtablepre,self::$db_tablepre,trim($sql));
		$sqlarr[$key]=preg_replace("/\s(?=\s)/","\\1",$sqlarr[$key]);
		return $sqlarr[$key];
	} 
	
	final public function insert($data,$table="", $return_insert_id = false, $replace = false) {
		   if(empty($table)){
			$table=$this->tablename;
		   }else{
		   $table=self::$db_tablepre.$table;
		   }
		 return $this->db->insert($data,$table,$return_insert_id, $replace);
	}	
	
	final public function update($data,$where = '',$table="") {
		if (is_array($where)) $where = $this->arraytosql($where);
		if(empty($table)){
			$table=$this->tablename;
		  }else{
		  $table=self::$db_tablepre.$table;
		  }
		if(empty($data)) return false;
		return $this->db->update($data,$table, $where);
	}
	/**
	 * 将数组转换为SQL语句
	 * @param array $where 要生成的数组
	 * @param string $font 连接串。
	 */
	final public function arraytosql($where, $font = ' AND ') {
		if (is_array($where)) {
			$sql = '';
			foreach ($where as $key=>$val) {
				$sql .= $sql ? " $font `$key` = '$val' " : " `$key` = '$val'";
			}
			return $sql;
		} else {
			return $where;
		}
	}
	
	//返回查询资源结果集
	public function query($sql,$error_exit=true){
		if(empty($sql))return false;
		$sql=self::replace_tablepre($sql);
		$this->db->execute($sql,$error_exit);	
		return $this->db->lastresult;
	}


	
	//返回插入最后一次的ID
	final public function insert_id(){	
		return $this->db->insert_id();
	}
	
	//影响的行数
	final public function affected_rows($link=null){
		if(empty($link))
			return $this->db->affected_rows();
		else		
			return mysql_affected_rows($link);
	}
	
	final public function delete( $where = '',$table) {
		  $where = $this->arraytosql($where);
		  if(empty($table)){
			$table=$this->tablename;
		   }else{
		   $table=self::$db_tablepre.$table;
		   }
		 return $this->db->delete($where,$table);
	}	
	
	/**
	 * 检查表是否存在
	 * @param $table 表名
	 * @return boolean
	 */
	public  function table_exists($table) {
		return $this->db->table_exists($table);
	}	
    /**
	 * 检查字段是否存在
	 * @param $tablename 表名
	 * @param $fieldname 字段名
	 * @return boolean
	 */
	function field_exists($fieldname,$tablename){
		$tablename=self::$db_tablepre.$tablename;
		if(empty($fieldname)) return false;
		if(empty($tablename)) return false;
		  $checkfield = $this->select("describe `{$tablename}`  `{$fieldname}`");
			if(empty($checkfield)){ 
			   return false;
			}else{
			   return true;
			}
	   }	
	/*
	*	bool 为真,返回段版本号
	*/
	public function GetVersion($bool=false){
		return $this->db->GetVersion($bool);
	}
	
	public function __destruct(){
		//mysql_close();
	}
	
	final public function Autocommit_off(){		
		$this->Query('SET AUTOCOMMIT=1');
	}
	final public function Autocommit_no(){		
		$this->Query('SET AUTOCOMMIT=0');
	}	
	//开启事务
	final public function Autocommit_start(){		
		$this->Query('START TRANSACTION');
		$this->Autocommit = 'start';
	}
	//成功执行
	final public function Autocommit_commit(){		
		$this->Query('COMMIT');
		$this->Autocommit = 'commit';
	}	
	//回滚事务
	final public function Autocommit_rollback(){
		$this->Query('ROLLBACK');
		$this->Autocommit = 'rollback';
	}
	

	
}
?>