<?php
/**
 * $db = new DB( array ( array('192.168.1.239','3306', 'socialgame', 'socialgame', '')));
 * @author zhangkui
 *
 */
class DBI{
	private $host;//主机
	private $port;//端口
	private $user;//用户
	private $password;//密码
	private $dbname;//db名
	/**
	 * 
	 * Enter description here ...
	 * @var mysqli
	 */
	static private $mysqli;//mysqli对象
	static $isConnected = false; 
	/**
	 * 为了兼容老版 采用二维数组
	 * 参数 array ( array('192.168.1.239:3306', 'socialgame', 'socialgame', ''))
	 * @param unknown_type $servers
	 */
	public function __construct( $servers){
		$servers = $servers[0];//为了兼容老版
		$aHost = explode(':', $servers[0]);
		$this->host = $aHost[0];
		$this->port = isset( $aHost[1]) ? $aHost[1] : '3306';//默认端口3306
		$this->user = $servers[1];
		$this->password = $servers[2];
		$this->dbname = $servers[3];
	}
	/**
	 * 检查并连接数据库
	 * @return mysqli
	 */
	public function connect(){
		if ( self::$isConnected) {//如果已经连接
			return self::$mysqli;
		}
		if ( ! class_exists( mysqli)) {
			die('This Lib Requires The Mysqli Extention!');
		}

		$conn = mysqli_init(); 
		mysqli_options($conn, MYSQLI_OPT_LOCAL_INFILE, true); 
		mysqli_real_connect($conn, $this->host, $this->user, $this->password, $this->dbname, $this->port);

		self::$mysqli = $conn;
		if ( $error = mysqli_connect_error()) {
			$this->errorlog( $error);
		}
		self::$isConnected = true;
		self::$mysqli->query("SET SQL_MODE='',CHARACTER_SET_CONNECTION='utf8',CHARACTER_SET_RESULTS='utf8',CHARACTER_SET_CLIENT='binary',NAMES 'utf8'");
		return self::$mysqli;
	}
	/**
	 * 执行sql
	 * @param unknown_type $query
	 */
	public function query( $query){
		$this->connect();
		$result = self::$mysqli->query( $query);
		$error = mysqli_error( self::$mysqli);
		if ( $error) { 
			$this->errorlog( $error);
		}
		return $result;
	}
	//查询一条记录
	public function getOne($query, $mode = MYSQL_BOTH){
		$result = $this->query($query);
		if ( ! is_object( $result)) {
			return array();
		}
		return $result->fetch_array( $mode);
	}
	//查询多条记录
	public function getAll($query, $mode = MYSQL_BOTH){
		$result = $this->query($query);
		if ( ! is_object( $result)) {
			return array();
		}
		$dataList = array();
		while ($row = $result->fetch_array( $mode)) {
			$dataList[] = $row;
		}
		return $dataList;
	}
//	/**
//	 * 缓存多行数据
//	 */
//	public function getCacheAll($sql, $expire, $mode=MYSQL_BOTH, $key=false){
//		$key = $key===false ? md5($sql) : $key;
//		if( ($temp = ocache::cache()->get($key)) === false){
//			$temp = $this->getAll($sql, $mode);
//			ocache::cache()->set($key, $temp, $expire);
//		}
//		return $temp;
//	}
//
//	/**
//	 * 缓存一行数据
//	 */
//	public function getCacheOne($sql, $expire, $mode=MYSQL_BOTH, $key=false){
//		$key = $key===false ? md5($sql) : $key;
//		if( ($temp = ocache::cache()->get($key)) === false){
//			$temp = $this->getOne($sql, $mode);
//			ocache::cache()->set($key, $temp, $expire);
//		}
//		return $temp;
//	}
	//获取最新插入的记录ID
	public function insertID(){
	    return self::$mysqli->insert_id;
	}
	/**
	 * 
	 * sql执行的影响行数
	 */
	public function affectedRows(){
		return self::$mysqli->affected_rows;
	}
	/**
	 * 
	 * 关闭数据库
	 */
	public function close(){
		if( self::$isConnected){
			self::$isConnected = false;
			self::$mysqli->close();
		}
	}
	/**
	 * 安全性检测.调用escape存入的,一定要调unescape取出
	 */
	public function escape( $string){
		if ( oo::functions()->isPhpVersion()) {
			return addslashes( trim($string));
		}
		return mysql_escape_string( trim($string));
	}

	public function unescape( $string){
		return stripslashes( $string);
	}
	/**
	 * 事务处理章节
	 */
	public function Start(){
		$this->connect();
		self::$mysqli->autocommit( FALSE);
	}
	public function Commit(){
		self::$mysqli->commit();
	}
	public function CommitId(){
		$aId = $this->getOne('SELECT LAST_INSERT_ID()', MYSQL_NUM);
		return (int)$aId[0];
	}
	public function Rollback(){
		self::$mysqli->rollback();
	}
	/**
	 * MYSQL报错日志
	 * @param string $msg
	 */
	private function errorlog( $msg='' ){
		$date = date( 'Ymd');
		$dir = PATH_DAT . 'phperror';
        $file = '/' . $date . '.log';
		$error = '';
		if ( ! file_exists( $file)) {
			//$error = "<?php\nexit();\n";
		}
		if ( ! is_dir( $dir)) {
			mkdir( PATH_DAT . 'mysql',  0777);
            chgrp_chown($dir);
		}
        if ( ! file_exists( $file)) {
            touch($file) && chmod($file, PRODUCTION_SERVER ? 0664 : 0666);
            chgrp_chown($file);
        }
		//$error = date('H:i:s') . " ". mysqli_errno( self::$mysqli) . " msg:". $msg . ";";
		$error = mysqli_errno( self::$mysqli) . " msg:". $msg . ";";

        $data = ['log_level' => 'error', 'log_module' => 'mysqli_error', 'time' => date('Y-m-d H:i:s'), 'host_ip' => SERVER_INT_IP, 'content' => $error];
		@file_put_contents($file, json_encode($data)."\n", FILE_APPEND | LOCK_EX);

		//@file_put_contents( $file, $error . " \n ", FILE_APPEND | LOCK_EX);
// 		oo::funModel('logs')->debug($error, 'mysql'.$date);
		die('DB Invalid!!!');
	}
    function chgrp_chown($f){
        if(function_exists('chgrp')&&php_sapi_name()=='cli'){//防止root创建www无权限
            @chgrp($f,'www');
            @chown($f,'www');
        }
    }
}
