includes/db/mysql.php
author indvdum (gotoindvdum[at]gmail[dot]com)
Wed, 07 Mar 2012 23:06:09 +0400
changeset 6 40f90a92f114
parent 0 ceef6d64c21d
permissions -rw-r--r--
Game logo
     1 <?php
     2 /**
     3 *
     4 * @package dbal
     5 * @version $Id$
     6 * @copyright (c) 2005 phpBB Group
     7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
     8 *
     9 */
    10 
    11 /**
    12 * @ignore
    13 */
    14 if (!defined('IN_PHPBB'))
    15 {
    16 	exit;
    17 }
    18 
    19 include_once($phpbb_root_path . 'includes/db/dbal.' . $phpEx);
    20 
    21 /**
    22 * MySQL4 Database Abstraction Layer
    23 * Compatible with:
    24 * MySQL 3.23+
    25 * MySQL 4.0+
    26 * MySQL 4.1+
    27 * MySQL 5.0+
    28 * @package dbal
    29 */
    30 class dbal_mysql extends dbal
    31 {
    32 	var $multi_insert = true;
    33 
    34 	/**
    35 	* Connect to server
    36 	* @access public
    37 	*/
    38 	function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
    39 	{
    40 		$this->persistency = $persistency;
    41 		$this->user = $sqluser;
    42 		$this->server = $sqlserver . (($port) ? ':' . $port : '');
    43 		$this->dbname = $database;
    44 
    45 		$this->sql_layer = 'mysql4';
    46 
    47 		$this->db_connect_id = ($this->persistency) ? @mysql_pconnect($this->server, $this->user, $sqlpassword) : @mysql_connect($this->server, $this->user, $sqlpassword, $new_link);
    48 
    49 		if ($this->db_connect_id && $this->dbname != '')
    50 		{
    51 			if (@mysql_select_db($this->dbname, $this->db_connect_id))
    52 			{
    53 				// Determine what version we are using and if it natively supports UNICODE
    54 				if (version_compare($this->sql_server_info(true), '4.1.0', '>='))
    55 				{
    56 					@mysql_query("SET NAMES 'utf8'", $this->db_connect_id);
    57 
    58 					// enforce strict mode on databases that support it
    59 					if (version_compare($this->sql_server_info(true), '5.0.2', '>='))
    60 					{
    61 						$result = @mysql_query('SELECT @@session.sql_mode AS sql_mode', $this->db_connect_id);
    62 						$row = @mysql_fetch_assoc($result);
    63 						@mysql_free_result($result);
    64 						$modes = array_map('trim', explode(',', $row['sql_mode']));
    65 
    66 						// TRADITIONAL includes STRICT_ALL_TABLES and STRICT_TRANS_TABLES
    67 						if (!in_array('TRADITIONAL', $modes))
    68 						{
    69 							if (!in_array('STRICT_ALL_TABLES', $modes))
    70 							{
    71 								$modes[] = 'STRICT_ALL_TABLES';
    72 							}
    73 
    74 							if (!in_array('STRICT_TRANS_TABLES', $modes))
    75 							{
    76 								$modes[] = 'STRICT_TRANS_TABLES';
    77 							}
    78 						}
    79 
    80 						$mode = implode(',', $modes);
    81 						@mysql_query("SET SESSION sql_mode='{$mode}'", $this->db_connect_id);
    82 					}
    83 				}
    84 				else if (version_compare($this->sql_server_info(true), '4.0.0', '<'))
    85 				{
    86 					$this->sql_layer = 'mysql';
    87 				}
    88 
    89 				return $this->db_connect_id;
    90 			}
    91 		}
    92 
    93 		return $this->sql_error('');
    94 	}
    95 
    96 	/**
    97 	* Version information about used database
    98 	* @param bool $raw if true, only return the fetched sql_server_version
    99 	* @param bool $use_cache If true, it is safe to retrieve the value from the cache
   100 	* @return string sql server version
   101 	*/
   102 	function sql_server_info($raw = false, $use_cache = true)
   103 	{
   104 		global $cache;
   105 
   106 		if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('mysql_version')) === false)
   107 		{
   108 			$result = @mysql_query('SELECT VERSION() AS version', $this->db_connect_id);
   109 			$row = @mysql_fetch_assoc($result);
   110 			@mysql_free_result($result);
   111 
   112 			$this->sql_server_version = $row['version'];
   113 
   114 			if (!empty($cache) && $use_cache)
   115 			{
   116 				$cache->put('mysql_version', $this->sql_server_version);
   117 			}
   118 		}
   119 
   120 		return ($raw) ? $this->sql_server_version : 'MySQL ' . $this->sql_server_version;
   121 	}
   122 
   123 	/**
   124 	* SQL Transaction
   125 	* @access private
   126 	*/
   127 	function _sql_transaction($status = 'begin')
   128 	{
   129 		switch ($status)
   130 		{
   131 			case 'begin':
   132 				return @mysql_query('BEGIN', $this->db_connect_id);
   133 			break;
   134 
   135 			case 'commit':
   136 				return @mysql_query('COMMIT', $this->db_connect_id);
   137 			break;
   138 
   139 			case 'rollback':
   140 				return @mysql_query('ROLLBACK', $this->db_connect_id);
   141 			break;
   142 		}
   143 
   144 		return true;
   145 	}
   146 
   147 	/**
   148 	* Base query method
   149 	*
   150 	* @param	string	$query		Contains the SQL query which shall be executed
   151 	* @param	int		$cache_ttl	Either 0 to avoid caching or the time in seconds which the result shall be kept in cache
   152 	* @return	mixed				When casted to bool the returned value returns true on success and false on failure
   153 	*
   154 	* @access	public
   155 	*/
   156 	function sql_query($query = '', $cache_ttl = 0)
   157 	{
   158 		if ($query != '')
   159 		{
   160 			global $cache;
   161 
   162 			// EXPLAIN only in extra debug mode
   163 			if (defined('DEBUG_EXTRA'))
   164 			{
   165 				$this->sql_report('start', $query);
   166 			}
   167 
   168 			$this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
   169 			$this->sql_add_num_queries($this->query_result);
   170 
   171 			if ($this->query_result === false)
   172 			{
   173 				if (($this->query_result = @mysql_query($query, $this->db_connect_id)) === false)
   174 				{
   175 					$this->sql_error($query);
   176 				}
   177 
   178 				if (defined('DEBUG_EXTRA'))
   179 				{
   180 					$this->sql_report('stop', $query);
   181 				}
   182 
   183 				if ($cache_ttl && method_exists($cache, 'sql_save'))
   184 				{
   185 					$this->open_queries[(int) $this->query_result] = $this->query_result;
   186 					$cache->sql_save($query, $this->query_result, $cache_ttl);
   187 				}
   188 				else if (strpos($query, 'SELECT') === 0 && $this->query_result)
   189 				{
   190 					$this->open_queries[(int) $this->query_result] = $this->query_result;
   191 				}
   192 			}
   193 			else if (defined('DEBUG_EXTRA'))
   194 			{
   195 				$this->sql_report('fromcache', $query);
   196 			}
   197 		}
   198 		else
   199 		{
   200 			return false;
   201 		}
   202 
   203 		return $this->query_result;
   204 	}
   205 
   206 	/**
   207 	* Build LIMIT query
   208 	*/
   209 	function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
   210 	{
   211 		$this->query_result = false;
   212 
   213 		// if $total is set to 0 we do not want to limit the number of rows
   214 		if ($total == 0)
   215 		{
   216 			// Having a value of -1 was always a bug
   217 			$total = '18446744073709551615';
   218 		}
   219 
   220 		$query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total);
   221 
   222 		return $this->sql_query($query, $cache_ttl);
   223 	}
   224 
   225 	/**
   226 	* Return number of affected rows
   227 	*/
   228 	function sql_affectedrows()
   229 	{
   230 		return ($this->db_connect_id) ? @mysql_affected_rows($this->db_connect_id) : false;
   231 	}
   232 
   233 	/**
   234 	* Fetch current row
   235 	*/
   236 	function sql_fetchrow($query_id = false)
   237 	{
   238 		global $cache;
   239 
   240 		if ($query_id === false)
   241 		{
   242 			$query_id = $this->query_result;
   243 		}
   244 
   245 		if (isset($cache->sql_rowset[$query_id]))
   246 		{
   247 			return $cache->sql_fetchrow($query_id);
   248 		}
   249 
   250 		return ($query_id !== false) ? @mysql_fetch_assoc($query_id) : false;
   251 	}
   252 
   253 	/**
   254 	* Seek to given row number
   255 	* rownum is zero-based
   256 	*/
   257 	function sql_rowseek($rownum, &$query_id)
   258 	{
   259 		global $cache;
   260 
   261 		if ($query_id === false)
   262 		{
   263 			$query_id = $this->query_result;
   264 		}
   265 
   266 		if (isset($cache->sql_rowset[$query_id]))
   267 		{
   268 			return $cache->sql_rowseek($rownum, $query_id);
   269 		}
   270 
   271 		return ($query_id !== false) ? @mysql_data_seek($query_id, $rownum) : false;
   272 	}
   273 
   274 	/**
   275 	* Get last inserted id after insert statement
   276 	*/
   277 	function sql_nextid()
   278 	{
   279 		return ($this->db_connect_id) ? @mysql_insert_id($this->db_connect_id) : false;
   280 	}
   281 
   282 	/**
   283 	* Free sql result
   284 	*/
   285 	function sql_freeresult($query_id = false)
   286 	{
   287 		global $cache;
   288 
   289 		if ($query_id === false)
   290 		{
   291 			$query_id = $this->query_result;
   292 		}
   293 
   294 		if (isset($cache->sql_rowset[$query_id]))
   295 		{
   296 			return $cache->sql_freeresult($query_id);
   297 		}
   298 
   299 		if (isset($this->open_queries[(int) $query_id]))
   300 		{
   301 			unset($this->open_queries[(int) $query_id]);
   302 			return @mysql_free_result($query_id);
   303 		}
   304 
   305 		return false;
   306 	}
   307 
   308 	/**
   309 	* Escape string used in sql query
   310 	*/
   311 	function sql_escape($msg)
   312 	{
   313 		if (!$this->db_connect_id)
   314 		{
   315 			return @mysql_real_escape_string($msg);
   316 		}
   317 
   318 		return @mysql_real_escape_string($msg, $this->db_connect_id);
   319 	}
   320 
   321 	/**
   322 	* Build LIKE expression
   323 	* @access private
   324 	*/
   325 	function _sql_like_expression($expression)
   326 	{
   327 		return $expression;
   328 	}
   329 
   330 	/**
   331 	* Build db-specific query data
   332 	* @access private
   333 	*/
   334 	function _sql_custom_build($stage, $data)
   335 	{
   336 		switch ($stage)
   337 		{
   338 			case 'FROM':
   339 				$data = '(' . $data . ')';
   340 			break;
   341 		}
   342 
   343 		return $data;
   344 	}
   345 
   346 	/**
   347 	* return sql error array
   348 	* @access private
   349 	*/
   350 	function _sql_error()
   351 	{
   352 		if (!$this->db_connect_id)
   353 		{
   354 			return array(
   355 				'message'	=> @mysql_error(),
   356 				'code'		=> @mysql_errno()
   357 			);
   358 		}
   359 
   360 		return array(
   361 			'message'	=> @mysql_error($this->db_connect_id),
   362 			'code'		=> @mysql_errno($this->db_connect_id)
   363 		);
   364 	}
   365 
   366 	/**
   367 	* Close sql connection
   368 	* @access private
   369 	*/
   370 	function _sql_close()
   371 	{
   372 		return @mysql_close($this->db_connect_id);
   373 	}
   374 
   375 	/**
   376 	* Build db-specific report
   377 	* @access private
   378 	*/
   379 	function _sql_report($mode, $query = '')
   380 	{
   381 		static $test_prof;
   382 
   383 		// current detection method, might just switch to see the existance of INFORMATION_SCHEMA.PROFILING
   384 		if ($test_prof === null)
   385 		{
   386 			$test_prof = false;
   387 			if (version_compare($this->sql_server_info(true), '5.0.37', '>=') && version_compare($this->sql_server_info(true), '5.1', '<'))
   388 			{
   389 				$test_prof = true;
   390 			}
   391 		}
   392 
   393 		switch ($mode)
   394 		{
   395 			case 'start':
   396 
   397 				$explain_query = $query;
   398 				if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
   399 				{
   400 					$explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
   401 				}
   402 				else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
   403 				{
   404 					$explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
   405 				}
   406 
   407 				if (preg_match('/^SELECT/', $explain_query))
   408 				{
   409 					$html_table = false;
   410 
   411 					// begin profiling
   412 					if ($test_prof)
   413 					{
   414 						@mysql_query('SET profiling = 1;', $this->db_connect_id);
   415 					}
   416 
   417 					if ($result = @mysql_query("EXPLAIN $explain_query", $this->db_connect_id))
   418 					{
   419 						while ($row = @mysql_fetch_assoc($result))
   420 						{
   421 							$html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
   422 						}
   423 					}
   424 					@mysql_free_result($result);
   425 
   426 					if ($html_table)
   427 					{
   428 						$this->html_hold .= '</table>';
   429 					}
   430 
   431 					if ($test_prof)
   432 					{
   433 						$html_table = false;
   434 
   435 						// get the last profile
   436 						if ($result = @mysql_query('SHOW PROFILE ALL;', $this->db_connect_id))
   437 						{
   438 							$this->html_hold .= '<br />';
   439 							while ($row = @mysql_fetch_assoc($result))
   440 							{
   441 								// make <unknown> HTML safe
   442 								if (!empty($row['Source_function']))
   443 								{
   444 									$row['Source_function'] = str_replace(array('<', '>'), array('&lt;', '&gt;'), $row['Source_function']);
   445 								}
   446 
   447 								// remove unsupported features
   448 								foreach ($row as $key => $val)
   449 								{
   450 									if ($val === null)
   451 									{
   452 										unset($row[$key]);
   453 									}
   454 								}
   455 								$html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
   456 							}
   457 						}
   458 						@mysql_free_result($result);
   459 
   460 						if ($html_table)
   461 						{
   462 							$this->html_hold .= '</table>';
   463 						}
   464 
   465 						@mysql_query('SET profiling = 0;', $this->db_connect_id);
   466 					}
   467 				}
   468 
   469 			break;
   470 
   471 			case 'fromcache':
   472 				$endtime = explode(' ', microtime());
   473 				$endtime = $endtime[0] + $endtime[1];
   474 
   475 				$result = @mysql_query($query, $this->db_connect_id);
   476 				while ($void = @mysql_fetch_assoc($result))
   477 				{
   478 					// Take the time spent on parsing rows into account
   479 				}
   480 				@mysql_free_result($result);
   481 
   482 				$splittime = explode(' ', microtime());
   483 				$splittime = $splittime[0] + $splittime[1];
   484 
   485 				$this->sql_report('record_fromcache', $query, $endtime, $splittime);
   486 
   487 			break;
   488 		}
   489 	}
   490 }
   491 
   492 ?>