<?php

if (!defined('IN_PHPMPS')) {
    die('Access Denied');
}

class mysql
{
    var $link    = NULL;
	var $settings   = array();
    var $queryCount = 0;
    var $queryTime  = '';
    var $queryLog   = array();
	var $cache_data_dir = 'data/sqlcache/';
    var $root_path      = '';
    var $error_message  = array();
    var $platform       = '';
    var $version        = '';
    var $dbhash         = '';
    var $starttime      = 0;
    var $timeline       = 0;
    var $timezone       = 0;
    var $mysql_config_cache_file_time = 0;
    var $max_cache_time = 300;
    var $mysql_disable_cache_tables = array();

    function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $quiet = 0)
    {
        $this->mysql($dbhost, $dbuser, $dbpw, $dbname, $pconnect, $quiet);
    }

    function mysql($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $quiet = 0)
    {
		global $charset;

        if (defined('PHPMPS_ROOT') && !$this->root_path) {
            $this->root_path = PHPMPS_ROOT;
        }

        if ($quiet) {
            $this->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, $quiet);
        } else {
            $this->settings = array('dbhost'=> $dbhost,'dbuser'=> $dbuser,'dbpw'=> $dbpw,'dbname'=>$dbname,'charset'=> $charset,'pconnect' => $pconnect);
        }
    }

    function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $quiet = 0)
    {
		global $dbcharset;

        if ($pconnect) {
            if (!($this->link = @mysql_pconnect($dbhost, $dbuser, $dbpw))) {
                if (!$quiet) {
                    $this->ErrorMsg("Can't Pconnect MySQL Server($dbhost)!<br><a href='http://bbs.phpmps.com'>Click Here</a>");
                }
                return false;
            }
        } else {
            if (PHP_VERSION >= '4.2') {
                $this->link = @mysql_connect($dbhost, $dbuser, $dbpw, true);
            } else {
                $this->link = @mysql_connect($dbhost, $dbuser, $dbpw);
                mt_srand((double)microtime() * 1000000); 
            }

            if (!$this->link) {
                if (!$quiet) {
                    $this->ErrorMsg("Can't Connect MySQL Server($dbhost)!");
                }
                return false;
            }
        }

        $this->dbhash  = md5($this->root_path . $dbhost . $dbuser . $dbpw . $dbname);
		$this->version = mysql_get_server_info($this->link);
        
		if ($this->version > '4.1') {
            if ($dbcharset != 'latin1')  {
                mysql_query("SET character_set_connection=$dbcharset, character_set_results=$dbcharset, character_set_client=binary", $this->link);
            }
            if ($this->version > '5.0.1') {
                mysql_query("SET sql_mode=''", $this->link);
            }
        }
		
		$sqlcache_config_file = $this->root_path . $this->cache_data_dir . 'sqlcache_config_file_' . $this->dbhash . '.php';

        @include($sqlcache_config_file);

        $this->starttime = time();

        if ($this->max_cache_time && $this->starttime > $this->mysql_config_cache_file_time + $this->max_cache_time)
        {
            if ($dbhost != '.')
            {
                $result = mysql_query("SHOW VARIABLES LIKE 'basedir'", $this->link);
                $row    = mysql_fetch_assoc($result);
                if (!empty($row['Value']{1}) && $row['Value']{1} == ':' && !empty($row['Value']{2}) && $row['Value']{2} == "\\")
                {
                    $this->platform = 'WINDOWS';
                }
                else
                {
                    $this->platform = 'OTHER';
                }
            }
            else
            {
                $this->platform = 'WINDOWS';
            }

            if ($this->platform == 'OTHER' &&
                ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306') ||
                (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC'))
            {
                $result = mysql_query("SELECT UNIX_TIMESTAMP() AS timeline, UNIX_TIMESTAMP('" . date('Y-m-d H:i:s', $this->starttime) . "') AS timezone", $this->link);
                $row    = mysql_fetch_assoc($result);

                if ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306')
                {
                    $this->timeline = $this->starttime - $row['timeline'];
                }

                if (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC')
                {
                    $this->timezone = $this->starttime - $row['timezone'];
                }
            }

            $content = '<' . "?php\r\n" .
                       '$this->mysql_config_cache_file_time = ' . $this->starttime . ";\r\n" .
                       '$this->timeline = ' . $this->timeline . ";\r\n" .
                       '$this->timezone = ' . $this->timezone . ";\r\n" .
                       '$this->platform = ' . "'" . $this->platform . "';\r\n?" . '>';

            @file_put_contents($sqlcache_config_file, $content);
        }

        if ($dbname) {
            if (mysql_select_db($dbname, $this->link) === false ) {
                if (!$quiet) {
                    $this->ErrorMsg("Can't Select MySQL database($dbname)!");
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    function query($sql, $type = '')
    {
		/* 如果查询的时候mysql断开链接，那么尝试连接mysql，然后处理查询*/
        if ($this->link === NULL) {
            $this->connect($this->settings['dbhost'],$this->settings['dbuser'],$this->settings['dbpw'],$this->settings['dbname'],$this->settings['charset'],$this->settings['pconnect']);
            $this->settings = array();
        }
        if ($this->queryCount++ <= 99) {
            $this->queryLog[] = $sql;
        }
        if ($this->queryTime == '') {
            if (PHP_VERSION >= '5.0.0') {
                $this->queryTime = microtime(true);
            } else {
                $this->queryTime = microtime();
            }
        }

		if(DEBUG_MODE=='1') 
		{
			$mtime = explode(' ', microtime());
			$sqlendttime = number_format(($mtime[1] + $mtime[0] - $_SGLOBAL['supe_starttime']), 6) * 1000;
			$sqltime = round(($sqlendttime - $sqlstarttime), 3);

			$explain = array();
			$info = mysql_info();
			if($query && preg_match("/^(select )/i", $sql)) {
				$explain = mysql_fetch_assoc(mysql_query('EXPLAIN '.$sql, $this->link));
			}
			$debug_query[] = array('sql'=>$sql, 'time'=>$sqltime, 'info'=>$info, 'explain'=>$explain);
			$this->pdebug($debug_query);
		}

        if (!($query = mysql_query($sql, $this->link)) && $type != 'SILENT') {
            $this->error_message[]['message'] = 'MySQL Query Error';
            $this->error_message[]['sql'] = $sql;
            $this->error_message[]['error'] = mysql_error($this->link);
            $this->error_message[]['errno'] = mysql_errno($this->link);

            $this->ErrorMsg();
            return false;
        }

        return $query;
    }

	function pdebug($debug_query)
	{
		echo'
		<style>
		.tclass, .tclass2 {
		text-align:left;width:900px;border:0;border-collapse:collapse;margin-bottom:5px;table-layout: fixed; word-wrap: break-word;background:#FFF;}
		.tclass table, .tclass2 table {width:100%;border:0;table-layout: fixed; word-wrap: break-word;}
		.tclass table td, .tclass2 table td {border-bottom:0;border-right:0;border-color: #ADADAD;}
		.tclass th, .tclass2 th {border:1px solid #000;background:#CCC;padding: 2px;font-family: Courier New, Arial;font-size: 11px;}
		.tclass td, .tclass2 td {border:1px solid #000;background:#FFFCCC;padding: 2px;font-family: Courier New, Arial;font-size: 11px;}
		.tclass2 th {background:#D5EAEA;}
		.tclass2 td {background:#FFFFFF;}
		.firsttr td {border-top:0;}
		.firsttd {border-left:none !important;}
		.bold {font-weight:bold;}
		</style>
		<div id="uchome_debug" style="display:;">';
		$class = 'tclass2';
		if(empty($debug_query)) $debug_query = array();
		foreach ($debug_query as $dkey => $debug) {
			($class == 'tclass')?$class = 'tclass2':$class = 'tclass';
			echo '<table cellspacing="0" class="'.$class.'"><tr><th rowspan="2" width="20">'.($dkey+1).'</th><td width="60">'.$debug['time'].' ms</td><td class="bold">'.htmlspecialchars_deep($debug['sql']).'</td></tr>';
			
			if(!empty($debug['explain'])) {
				echo '<tr><td>Explain</td><td><table cellspacing="0"><tr class="firsttr"><td width="5%" class="firsttd">id</td><td width="10%">select_type</td><td width="12%">table</td><td width="5%">type</td><td width="20%">possible_keys</td><td width="10%">key</td><td width="8%">key_len</td><td width="5%">ref</td><td width="5%">rows</td><td width="20%">Extra</td></tr><tr>';
				foreach ($debug['explain'] as $ekey => $explain) {
					($ekey == 'id')?$tdclass = ' class="firsttd"':$tdclass='';
					if(empty($explain)) $explain = '-';
					echo '<td'.$tdclass.'>'.$explain.'</td>';
				}
				echo '</tr></table></td></tr>';
			}
			echo '</table>';
		}
		echo '</div>';
	}

    function affected_rows()
    {
        return mysql_affected_rows($this->link);
    }
	function num_fields($query)
	{	
        return mysql_num_fields($query);
    }
    function error()
    {
        return mysql_error($this->link);
    }

    function errno()
    {
        return mysql_errno($this->link);
    }

    function num_rows($query)
    {
        return mysql_num_rows($query);
    }

    function insert_id()
    {
        return mysql_insert_id($this->link);
    }

    function fetchRow($query)
    {
        return mysql_fetch_assoc($query);
    }

	function fetcharray($query)
    {
        return mysql_fetch_array($query);
    }

    function version()
    {
        return $this->version;
    }

    function close()
    {
        return mysql_close($this->link);
    }

    function ErrorMsg($message = '', $sql = '')
    {
        if ($message) {
            echo "$message\n\n";
        } else {
            echo "<b>MySQL server error report:";
            print_r($this->error_message);
        }
        exit;
    }

    function getOne($sql, $limited = false)
    {
        if ($limited == true) {
            $sql = trim($sql . ' LIMIT 1');
        }

        $res = $this->query($sql);
        if ($res !== false) {
            $row = mysql_fetch_row($res);

            if ($row !== false) {
                return $row[0];
            } else {
                return '';
            }
        } else {
            return false;
        }
    }
	
	function getOneCached($sql, $cached = 'FILEFIRST')
    {
        $sql = trim($sql . ' LIMIT 1');

        $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;
        if (!$cachefirst) {
            return $this->getOne($sql, true);
        } else {
            $result = $this->getSqlCacheData($sql, $cached);print_r($data);
            if (empty($result['storecache']) == true) {
                return $result['data'];
            }
        }
        $arr = $this->getOne($sql, false);

        if ($arr !== false && $cachefirst) {
            $this->setSqlCacheData($result, $arr);
        }
        return $arr;
    }

    function getAll($sql)
    {
        $res = $this->query($sql);
        if ($res !== false) {
            $arr = array();
            while ($row = mysql_fetch_assoc($res)) {
                $arr[] = $row;
            }
            return $arr;
        } else {
            return false;
        }
    }
	
	function getAllCached($sql, $cached = 'FILEFIRST')
    {
        $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;
        if (!$cachefirst) {
            return $this->getAll($sql);
        } else {
            $result = $this->getSqlCacheData($sql, $cached);
            if (empty($result['storecache']) == true) {
                return $result['data'];
            }
        }
        $arr = $this->getAll($sql);

        if ($arr !== false && $cachefirst) {
            $this->setSqlCacheData($result, $arr);
        }
        return $arr;
    }

	function getCol($sql)
    {
        $res = $this->query($sql);
        if ($res !== false) {
            $arr = array();
            while ($row = mysql_fetch_row($res)) {
                $arr[] = $row[0];
            }
            return $arr;
        } else {
            return false;
        }
    }

	function getColCached($sql, $cached = 'FILEFIRST')
    {
        $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;
        if (!$cachefirst) {
            return $this->getCol($sql);
        } else {
            $result = $this->getSqlCacheData($sql, $cached);
            if (empty($result['storecache']) == true) {
                return $result['data'];
            }
        }
        $arr = $this->getCol($sql);

        if ($arr !== false && $cachefirst) {
            $this->setSqlCacheData($result, $arr);
        }
        return $arr;
    }

    function getRow($sql, $limited = false)
    {
        if ($limited == true) {
            $sql = trim($sql . ' LIMIT 1');
        }

        $res = $this->query($sql);
        if ($res !== false) {
            return mysql_fetch_assoc($res);
        } else {
            return false;
        }
    }
	
	function getRowCached($sql, $cached = 'FILEFIRST')
    {
        $sql = trim($sql . ' LIMIT 1');

        $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;
        if (!$cachefirst) {
            return $this->getRow($sql, true);
        } else {
            $result = $this->getSqlCacheData($sql, $cached);
            if (empty($result['storecache']) == true) {
                return $result['data'];
            }
        }
        $arr = $this->getRow($sql, true);

        if ($arr !== false && $cachefirst) {
            $this->setSqlCacheData($result, $arr);
        }
        return $arr;
    }

	function setMaxCacheTime($second)
    {
        $this->max_cache_time = $second;
    }

    function getMaxCacheTime()
    {
        return $this->max_cache_time;
    }

    function getSqlCacheData($sql, $cached = '')
    {
        $sql = trim($sql);

        $result = array();
        $result['filename'] = $this->root_path . $this->cache_data_dir . 'sqlcache_' . abs(crc32($this->dbhash . $sql)) . '_' . md5($this->dbhash . $sql) . '.php';

        $data = @file_get_contents($result['filename']);
        if (isset($data{23}))
        {
            $filetime = substr($data, 13, 10);
            $data     = substr($data, 23);

            if (($cached == 'FILEFIRST' && time() > $filetime + $this->max_cache_time) || ($cached == 'MYSQLFIRST' && $this->table_lastupdate($this->get_table_name($sql)) > $filetime)) {
                $result['storecache'] = true;
            } else {
                $result['data'] = @unserialize($data);
                if ($result['data'] === false) {
                    $result['storecache'] = true;
                } else {
                    $result['storecache'] = false;
                }
            }
        } else {
            $result['storecache'] = true;
        }

        return $result;
    }

    function setSqlCacheData($result, $data)
    {
        if ($result['storecache'] === true && $result['filename']) {
            @file_put_contents($result['filename'], '<?php exit;?>' . time() . serialize($data));
            clearstatcache();
        }
    }

	/* 设置不允许进行缓存的表 */
    function set_disable_cache_tables($tables)
    {
        if (!is_array($tables)) {
            $tables = explode(',', $tables);
        }
        foreach ($tables AS $table) {
            $this->mysql_disable_cache_tables[] = $table;
        }
        array_unique($this->mysql_disable_cache_tables);
    }
}
?>