<?php
/*
'#################################################################
'# 程序名称：中环CMSV2.0
'# 授权方式：免费软件
'# 作者：善
'# 联系QQ:9118847
'# 作者网站:http://www.ps173.com
'# 发布时间：2015-6-10
'# 声明：欢迎广大的PHP爱好者一起共同探讨
'# 声明：各种用途均可免费使用、自由传播，但必须保留程序代码中的版权信息。
'#################################################################
 */

//数据库类

class Model extends Db{
	protected $tabname;
	protected $tabkey = array();
	protected $query = array("field"=>"", "where"=>"", "order"=>"",  "limit"=>"");


	//初始化属性
	protected function setnull(){
		$this->query = array("field"=>"", "where"=>"", "order"=>"", "limit"=>"");
	}

	//连贯操作调用 $query 的属性
	public function __call($metthod, $args){
		$metthod=strtolower($metthod);
		if(array_key_exists($metthod, $this->query)){
			if(empty($args[0]) || (is_string($args[0]) && trim($args[0])==='')){
				$this->query[$metthod] = "";
			}else{
				$this->query[$metthod] = $args;
			}

			if($metthod == "limit"){
				if($args[0] == "0")
					$this->query[$metthod]=$args;
			}
		}else{
			val::mess("调用".get_class($this)."中的方法{$metthod}()不存在", "close");
		}
		return $this;
	}

	//将数据写进库
	protected function add($post = null){
		if(is_null($post))
			$post = $_POST;

		$post = $this->clean_html($post);
		$query = "INSERT INTO {$this->tabname}(".implode(',', array_keys($post)).") VALUES(".implode(',', array_fill(0, count($post), '?')) .")";
		return $this->query($query, __FUNCTION__, array_values($post));	
	}

	//修改数据
	protected function mod($post = null){
		if(is_null($post))
			$post = $_POST;
		
		$data = array();
		if(is_array($post)){
			if(array_key_exists($this->tabkey["0"], $post)){
				$pri_value = $post[$this->tabkey["0"]];
				unset($post[$this->tabkey["0"]]);

			}

			$post = $this->clean_html($post);
			$s = '';
			foreach ($post as $key => $val) {
				$s .="{$key}=?,";
				$data[] = $val;
			}
			$s = rtrim($s, ",");
			$setfield = $s;
		}else{
			$setfield = $post;
			$pri_value='';
		}

		$order = $this->query["order"] != "" ? " ORDER BY {$this->query["order"][0]}" : "";
		$limit = $this->query["limit"] != "" ? $this->tolimit($this->query["limit"]) : "";

		if($this->query["where"] != ""){
			$where = $this->towhere($this->query["where"]);
			$query = "UPDATE {$this->tabname} SET {$setfield}".$where["where"];
			if(!empty($where["data"])){
				foreach ($where["data"] as $val) {
					$data[] = $val;
				}
			}
			$query .=$order.$limit;
		}else{
			$query ="UPDATE {$this->tabname} SET {$setfield} WHERE {$this->tabkey["0"]}=?";
			$data[] = $pri_value;

		}

		return $this->query($query, __FUNCTION__, $data);
		
	}

	//删除数据
	protected function del(){
		$where = "";
		$data = array();

		$args = func_get_args();
		if(count($args) > 0){
			$where = $this->towhere($args);
			$data = $where["data"];
			$where = $where["where"];
		}else if($this->query["where"] != ""){
			$where = $this->towhere($this->query["where"]);
			$data = $where["data"];
			$where = $where["where"];
		}

		$order = $this->query["order"] != "" ? " ORDER BY {$this->query["order"][0]}" : "";
		$limit = $this->query["limit"] != "" ? $this->tolimit($this->query["limit"]) : "";

		if($where == "" && $limit == ""){
			$where =" where {$this->tabkey["id"]}=''";
		}

		$query = "DELETE FROM {$this->tabname}{$where}{$order}{$limit}";
		return $this->query($query, __FUNCTION__, $data);
	}

	//查询一条数据
	protected function one($pri = ""){
		$fields = $this->query["field"] != "" ? $this->query["field"][0] : implode(",", $this->tabkey);
		if($pri == ""){
			$where = $this->towhere($this->query["where"]);
			$data = $where["data"];
			$where = $this->query["where"] != "" ? $where["where"] : "";
		}else{
			$where = " where {$this->tabkey["id"]}=?";
			$data[] = $pri;
		}

		$order = $this->query["order"] != "" ? "ORDER BY {$this->query["order"][0]}" : "";
		$query = "SELECT {$fields} FROM {$this->tabname}{$where}{$order} LIMIT 1";
		return $this->query($query, __FUNCTION__, $data);

	}

	//查询多条数据
	protected function all(){
		$fields = $this->query["field"] != "" ? $this->query["field"][0] : implode(",", $this->tabkey);
		$where = "";
		$data = array();

		$args=func_get_args();
		if(count($args) > 0){
			$where = $this->towhere($args);
			$data = $where["data"];
			$where = $where["where"];
		}else if($this->query["where"] != ""){
			$where = $this->towhere($this->query["where"]);
			$data = $where["data"];
			$where = $where["where"];
		}

		$order = $this->query["order"] != "" ? " ORDER BY {$this->query["order"][0]}" : " ORDER BY {$this->tabkey["0"]} ASC";
		$limit = $this->query["limit"] != "" ? $this->tolimit($this->query["limit"]) : "";
		$query = "SELECT {$fields} FROM {$this->tabname}{$where}{$order}{$limit}";
		return $this->query($query, __FUNCTION__, $data);
	}

	//获取数据库总数
	protected function total(){
		$where = "";
		$data = array();

		$args=func_get_args();
		if(count($args) > 0){
			$where = $this->towhere($args);
			$data = $where["data"];
			$where = $where["where"];
		}else if($this->query["where"] != ""){
			$where = $this->towhere($this->query["where"]);
			$data = $where["data"];
			$where = $where["where"];
		}

		$query = "SELECT COUNT(*) AS count FROM {$this->tabname}{$where}";
		return $this->query($query, __FUNCTION__, $data);
	}

	//获取LIMIT
	private function tolimit($args){
		if(count($args) == 2){
			return " LIMIT {$args[0]}, $args[1]}";
		}else if(count($args)==1){
			return " LIMIT {$args[0]}";
		}else{
			return '';
		}

	}


	private function towhere($args){
		$where = ' WHERE ';
		$data = array();

		if(empty($args))
			return array("where"=>"", "data"=>$data);

		foreach ($args as $option) {	
			if(empty($option)){
				$where = '';
				continue;
			}else if(is_string($option)){
				if(is_numeric($option[0])){
					$option = explode(',', $option);
					$where .="{$this->tabkey["0"]} IN(" . implode(',', array_fill(0, count($option), '?')) . ")";
					$data = $option;
					continue;
				}else{
					$where .= $option;
					continue;
				}

			}else if(is_numeric($option)){
				$where .= "{$this->tabkey["0"]}=?";
				$data[0] = $option;
				continue;
			}else if(is_array($option)){
				if(isset($option[0])){
					$where .= "{$this->tabkey["0"]} IN(" . implode(',', array_fill(0, count($option), '?')) . ")";
					$data = $option;
					continue;
				}

				foreach ($option as $key => $val) {
					if(is_array($val)){
						$where .="{$key} IN(" . implode(',', array_fill(0, count($val), '?')) . ")";
						foreach ($val as $value) {
							$data[] = $value;
						}
					}else if(strpos($key, ' ')){
						$where .="{$key}?";
						$data[] = $val;
					}else if(isset($val[0]) && $val[0] == '%' && substr($val, -1) == '%'){	
						$where .="{$key} LIKE ?";
						$data[] = $val;
					}else{
						$where .= "{$key}=?";
						$data[] = $val;
					}

					$where .=" AND ";
				}

				$where =rtrim($where, "AND ");
				$where.=" OR";
				continue;
			}
		}
		$where=rtrim($where, "OR ");
		return array("where"=>$where, "data"=>$data);
	}

	//设置表名
	public function settable($tabname){
		$this->tabname = TAB_FIX.$tabname;
		if($this->mysqli)
			$result = $this->mysqli->query("DESC {$this->tabname}");
		else
			return;

		$fields = array();
		while($row=$result->fetch_assoc()) {
			if($row["Key"]=="PRI"){
				$fields["pri"] = strtolower($row["Field"]);
			}else{
				$fields[] = strtolower($row["Field"]);
		}

		if(!array_key_exists("pri", $fields)){
			$fields["pri"] = array_shift($fields);
		  }

		$this->tabkey=$fields;
		
		}
	}

	protected function clean_html($data){
		$arr = array();
		if(is_array($data)){
			foreach ($data as $key => $val) {
				$key=strtolower($key);
				if(in_array($key, $this->tabkey) && $val !== ''){
					$arr[$key] = stripslashes(htmlspecialchars($val));
				}
			}
		}else{
			$arr = stripslashes((htmlspecialchars($data)));
		}

		return $arr;
	}

	//多组合查询
	protected function multi(){
		$args = func_get_args();
		if(count($args) == 0 || !is_array($args[0]))
			return false;

		$one = $this->all();
		$pri = $this->tabkey['0'];
		$pris = array();
		foreach ($one as $row) {
			$pris[]=$row[$pri];
		}

		foreach ($args as $tab) {
			list($tabname, $field, $fk) = $tab;
			if(!empty($fk)){
				if(!in_array($fk, explode(",", $field))){
					$field=$field.",".$fk;
				}else{
					$field = $field;
				}
			}else{
				$field = '';
			}
			if(!empty($tab[3])){
				$sub = $tab[3];
				if(is_array($sub)){
					$obj = D($tabname);
					$new = array();
					foreach ($one as $row) {
						$where = "{$fk} = {$row[$pri]}";
						if(!empty($sub[3])){
							$where.=" AND {$sub[3]}";
						}
						if(!empty($sub[1])){
							if(!empty($sub[2])){
								$row[$sub[0]] = $obj->field($field)->order($sub[1])->limit($sub[2])->where($where)->all();
							}else{
								$row[$sub[0]] = $obj->field($field->order($sub[1]))->where($where)->all();
							}
						}else{
							if(!empty($sub[2])){
								$row[$sub[0]] = $obj->field($field)->limit($sub[2])->where($where)->all();
							}else{
								$row[$sub[0]] = $obj->field($field)->where($where)->all();
							}
						}
						$new[] = $row;
					}
					$one = $new;
				}else{
					$new = array();
					$npris = array();

					foreach ($one as $row) {
						$npris[] = $row[$sub];
					}

					$where = array($fk=>$npris);
					if(!empty($where[$fk])){
						$data = D($tabname)->field($field)->where($where)->all();
						$i = 0;
						foreach ($one as $row) {
							foreach ($data as $read) {
								if($read[$fk] == $row[$sub]){
									foreach ($read as $k3 => $v3) {
										if(array_key_exists($k3, $row)){
											$row[$tabname.'_'.$k3] = $v3;
										}else{
											$row[$k3] = $v3;
										}
									}

									$new[$i] = $row;
									break;	
								}
							}

							if(empty($new[$i])){
								$new[$i] = $one[$i];
							}
							$i++;
						}
						$one = $new;
					}
				}
			}else{
				$new = array();
				$where = array($fk => $pris);
				if(!empty($where[$fk])){
					$data = D($tabname)->field($field)->where($where)->all();
					foreach ($data as $row) {
						foreach ($one as $read) {
							if($read[$pri] == $row[$fk]){
								foreach ($row as $k3 => $v3) {
									if(array_key_exists($k3, $read)){
										$read[$tabname.'_'.$k3] = $v3;
									}else{
										$read[$k3] = $v3;
									}
								}
								$new[] = $read;
							}
						}
					}
					$one = $new;
				}
			}
		}
		return $new;
	}
}

?>