<?php
	defined("rc_soft") or die("Access Denied");
	class db{
		private $dbms;
		private $host;
		private $port;
		private $dbName;
		private $dbUser;
		private $dbPass;
		public $conn;
		public $record;
		public $pageString;
		public $xlsConn;
		public $lastInsertId;
		public	$rowCount;
		function __construct($dbms="",$host="",$port="",$dbName="",$dbUser="",$dbPass=""){
			$this->dbms=$dbms;
			$this->host=$host;			
			$this->port=isNull($port)?3306:$port;
			$this->dbName=$dbName;
			$this->dbUser=$dbUser;
			$this->dbPass=$dbPass;
			$this->conn="";
			$this->record="";
			$this->pageString='';
			$this->xlsConn='';
			$this->lastInsertId=-1;
			$this->rowCount=0;
		}
		function condb(){
			try{
				$dsn=$this->dbms.":host=".$this->host.";port=".$this->port.";dbname=".$this->dbName;
				$this->conn=new PDO($dsn,$this->dbUser,$this->dbPass,array(PDO::ATTR_PERSISTENT=>true));
				$this->conn->setAttribute(PDO::ATTR_CASE,PDO::CASE_NATURAL);//强制查询结果中每个字段的名称字母为大写
				$this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//抛出错误
				$this->conn->exec("set names utf8");
				$this->conn->exec("set time_zone= '+8:00'");
			} catch(PDOException $e){
				echo $e->getMessage();
			}
		}
		
		function updateCache($sql=''){
			global $cg;
			$sql=(!preg_match("/(^select).*/i",$sql))?'':$sql;
			if(isNull($sql)){
				return false;
			}else{
				$md5=md5($sql);
				$folderPath=realpath($cg['cache']."/sql/".$md5{4}.$md5{6});
				if(is_dir($folderPath)){
					$filePath=realpath($folderPath."/{$md5}.php");
					if(is_file($filePath)){
						@chmod($filePath,0777);
						unlink($filePath);
						$row=$this->myQuery($sql,true);
						return $row;
					}
				}
				return false;
			}
		}
		
		//将SQL查询结果缓存到CACHE文件夹并返回数组查询结果，如果缓存文件已经存在，不执行查询，读取结果并返回数组结果
		function sqlCache($sql){
			global $cg;
			$fileName=md5($sql);
			$fFolder=$fileName{4}.$fileName{6};//取第4和6个字符作为SQL缓存文件所在文件夹的名称
			$folderPath="{$cg['cache']}/sql/{$fFolder}";
			if(!is_dir($folderPath)){
				mkdir($folderPath,0777);
			}
			$filePath=realpath("{$folderPath}/{$fileName}.php");
			if(is_file($filePath)){
				$t=filectime($filePath);
				if($t+$cg['cacheTime']*60<time()){
					unlink($filePath);
					return $this->sqlCache($sql);
				}else{
					$result=require($filePath);
					return $result;
				}
			}else{
				try{
					$rs=$this->conn->query($sql);
					$rs->setFetchMode(PDO::FETCH_ASSOC);
					$result=$rs->fetchAll();
					file_put_contents("{$folderPath}/{$fileName}.php","<?php \r\n defined('rc_soft') or die('Access Denied');\r\n return ".var_export($result,true).";?>");
				}catch(PDOException $e){
					$result=array();
				}
			}
			return $result;
		}
		
		function myQuery($sql,$cache=""){
			try{
				if(is_null($this->conn)){
					$this->condb();
				}
				$cache=(isNull($cache) || $cache==false)?false:true;
				if($cache){
					return $this->sqlCache($sql);
				}else{
					$rs=$this->conn->query($sql);
					$rs->setFetchMode(PDO::FETCH_ASSOC);
					return $rs->fetchAll();
				}		
			}catch(PDOException $e){
				return array();
			}
		}
		
		/*
			插入记录
			$useTran是否启用事务处理，默认FALSE不启用，设置为true则启用事务处理
		*/
		function execSql($sql,$useTran=false){
			$result=true;
			if(is_null($this->conn)){
				$this->condb();
			}
			try{
				if($useTran){
					try{
						$this->conn->beginTransaction();
						$this->conn->exec($sql);
						$this->conn->commit();
						if(preg_match("/^(insert){1}[ ]{1,}.{1,}/",$sql)){
							$this->lastInsertId=$this->conn->lastInsertId();
						}
					}catch(Exception $e){
						$this->conn->rollback();
						echo $e->getMessage();
						$result=false;
					}
				}else{
					try{
						$this->conn->exec($sql);
						if(preg_match("/^(insert){1}[ ]{1,}.{1,}/",$sql)){
							$this->lastInsertId=$this->conn->lastInsertId();
						}
					}catch(PDOException $e){
						echo $e->getMessage();
						$result=false;
					}
				}
			}catch(PDOException $e){
				$result=false();
			}
			return $result;
		}
		/*
		SQL查询分页，$sql接收传递来的查询语句，$rowSize接收传递来的每页显示的记录数
		如果查询成功，输出页码列表，并返回查询数据记录
		*/
		function page($sql,$rowSize,$page){
			global $cg;
			if(preg_match("/select.*?(?=from)from/i",$sql)){
				$sql=preg_replace("/limit[\s]{1,}[0-9]*[\,]{0,1}[0-9]*$/i","",$sql);
				$uri=$_SERVER['REQUEST_URI'];
				$url=$cg['domain'].$_SERVER['REQUEST_URI'];
				if(stripos($url,"?")){
					$url=preg_match("/page\=[0-9]*/i",$url)?$url:$url."page=1";
				}else{
					$url="{$url}?page=1";
				}
				$pageCount=1;//共有多少页
				$pageList=5;//当前页码号左右各显示多少个页码号
				$rowSize=(is_numeric($rowSize) && $rowSize>0)?(int)$rowSize:10;
				$newSql=preg_replace("/select.*?(?=from)from/i","select count(1) as recordCount from",$sql,1);
				$this->rowCount=$rowCount=$this->myQuery($newSql,false);
				$this->rowCount=$rowCount=(!is_array($rowCount) || count($rowCount)==0)?1:$rowCount[0]['recordCount'];
				@$pageCount=$this->rowCount%$rowSize==0?$this->rowCount/$rowSize:floor($this->rowCount/$rowSize)+1;
				$pageCount=$pageCount==0?1:$pageCount;
				$page=(isNull($page) || !is_numeric($page) || $page>$pageCount)?1:(int)($page);
				$roll=$pageList*2+1;
				$roll=$roll+$page>$pageCount?$pageCount-$page+$pageList+1:$roll;
				
				$temp=preg_replace("/page\=[0-9]*/i","page=1",$url);
				$pre=$page==1?"||&lt;&lt;":$pre="<a href=\"{$temp}\" target=\"_self\" class=\"pageA\" title=\"第1页\">||&lt;&lt;</a>";
				
				$this->pageString=<<<html
				<div id="pageBox">
				  <div class="pageNumber">共{$pageCount}页,当前第{$page}页</div>
				  <div class="pageNumber">{$pre}</div>
html;
				$k=$page-$pageList<=0?1:$page-$pageList;
				for($i=1;$i<=$roll && $i<=$pageCount;$i++){
					$uri=preg_replace("/page\=[0-9]*/i","page={$k}",$url);
					$a=$k==$page?$k:"<a href=\"$uri\" target=\"_self\" title=\"第{$k}页\">{$k}</a>";
					$this->pageString.=<<<html
					<div class="pageNumber">{$a}</div>
html;
					$k++;
				}
				
				$temp=preg_replace("/page\=[0-9]*/i","page={$pageCount}",$url);
				$last=$page==$pageCount?"&gt;&gt;||":"<a href=\"{$temp}\" target=\"_self\" title=\"最后一页\">&gt;&gt;||</a>";
				
				$this->pageString.=<<<html
				  <div class="pageNumber">{$last}</div>
				</div>
html;
				try{
					$start=$rowSize*$page-$rowSize;
					$end=$start+$rowSize;
					$sql="{$sql} limit {$start},{$rowSize}";
					return $this->myQuery($sql);//返回记录查询结果
				}catch(PDOException $e){
					return $e;
				}
				
			}else{
				return "SQL error!";
			}
		}
		/*
			连接EXCEL
		*/
		function connectExcel($ePath='',$tableName=''){
			$i=$j=-1;
			$ePath=strtolower($ePath);
			$i=strrpos($ePath,'.xlsx');
			if(!is_numeric($i)){
				$i=-1;
				$j=strrpos($ePath,'.xls');
				$j=is_numeric($j)?$j:-1;
			}
			if(!$i==-1 && $j==-1){
				return false;
			}
			$path=realpath($ePath);
			$this->xlsConn=new COM("Adodb.Connection",NULL,CP_UTF8) or die("Excel连接失败");
			if($i==-1){
				$conStr="Driver={Microsoft Excel Driver (*.xls)};DBQ={$path}";
			}else{
				$conStr="Driver={Microsoft Excel Driver (*.xlsx)};DBQ={$path}";
			}
			$this->xlsConn->open($conStr);
			$rs=new COM("ADODB.Recordset",NULL,CP_UTF8);
			$sql="select * from {$tableName}";
			$rs->open($sql,$this->xlsConn,1,3,1);
			return $rs;
		}
		
		/*
			返回当前数据库中所有数据表的基本信息
		*/
		function tables(){
			$sql="show table status;";
			$table=$this->myQuery($sql,false);
			return $table;
		}
	}
?>