2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/29/2004 *
4 * =============== Last change: 08/29/2004 *
6 * -------------------------------------------------------------------- *
7 * File : lib-mysql3.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Database layer for MySQL +3.x server *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Datenbankschicht fuer MySQL +3.x Server *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2008 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
46 function SQL_QUERY ($sql_string, $F, $L) {
48 if (!SQL_IS_LINK_UP()) return false;
50 // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
51 $sql_string = str_replace("\t", " ", str_replace("\n", " ", str_replace("\r", " ", $sql_string)));
53 // Replace {!_MYSQL_PREFIX!} with constant, closes #84. Thanks to profi-concept
54 $sql_string = str_replace("{!_MYSQL_PREFIX!}", constant('_MYSQL_PREFIX'), $sql_string);
56 // Replace {!_TABLE_TYPE!} with constant
57 $sql_string = str_replace("{!_TABLE_TYPE!}", constant('_TABLE_TYPE'), $sql_string);
60 $querytimeBefore = array_sum(explode(' ', microtime()));
63 //* DEBUG: */ echo $sql_string."<br />\n";
64 $result = mysql_query($sql_string, SQL_GET_LINK())
65 or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error()."<br />
70 $querytimeAfter = array_sum(explode(' ', microtime()));
72 // Calculate query time
73 $queryTime = $querytimeAfter - $querytimeBefore;
75 // Save last successfull query
76 setConfigEntry('db_last_query', $sql_string);
79 incrementConfigEntry('sql_count');
82 //* DEBUG: */ print "Query=<pre>".$sql_string."</pre>, affected=<strong>".SQL_AFFECTEDROWS()."</strong>, numrows=<strong>".SQL_NUMROWS($result)."</strong><br />\n";
83 if (($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1") && (isDebugModeEnabled()) && (isBooleanConstantAndTrue('DEBUG_SQL'))) {
87 $fp = fopen(constant('PATH')."inc/cache/mysql.log", 'a') or mxchange_die("Cannot write mysql.log!");
88 if (!isset($GLOBALS['sql_first_entry'])) {
90 fwrite($fp, "Module=".$GLOBALS['module']."\n");
91 $GLOBALS['sql_first_entry'] = true;
93 fwrite($fp, $F."(LINE=".$L."|NUM=".SQL_NUMROWS($result)."|AFFECTED=".SQL_AFFECTEDROWS()."|QUERYTIME:".$queryTime."): ".str_replace('\r', "", str_replace('\n', " ", $sql_string))."\n");
98 if (!isConfigEntrySet('db_hits_run')) {
99 // Count in dummy variable
100 setConfigEntry('db_hits_run', 1);
102 // Count to config array
103 incrementConfigEntry('db_hits_run');
111 function SQL_NUMROWS ($result) {
112 // Is the result a valid resource?
113 if (is_resource($result)) {
114 // Get the count of rows from database
115 $lines = mysql_num_rows($result);
117 // Is the result empty? Then we have an error!
118 if (empty($lines)) $lines = 0;
120 // No resource given, no lines found!
127 function SQL_AFFECTEDROWS() {
128 // Valid link resource?
129 if (!SQL_IS_LINK_UP()) return false;
132 $lines = mysql_affected_rows(SQL_GET_LINK());
139 function SQL_FETCHROW ($result) {
140 // Is a result resource set?
141 if (!is_resource($result)) return false;
143 // Fetch the data and return it
144 return mysql_fetch_row($result);
148 function SQL_FETCHARRAY($res, $nr=0, $remove_numerical=true) {
149 // Is a result resource set?
150 if (!is_resource($res)) return false;
155 // Load row from database
156 $row = mysql_fetch_array($res);
158 // Return only arrays here
159 if (is_array($row)) {
160 // Shall we remove numerical data here automatically?
161 if ($remove_numerical) {
162 // So let's remove all numerical elements to save memory!
164 for ($idx = 0; $idx < ($max / 2); $idx++) {
173 // Return a false here...
179 function SQL_RESULT ($res, $row, $field = 0) {
181 if (!is_resource($res)) return false;
183 // Run the result command and return the result
184 $result = mysql_result($res, $row, $field);
189 function SQL_CONNECT ($host, $login, $password, $F, $L) {
191 $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
193 // Set the link resource
194 SQL_SET_LINK($connect);
197 // SQL select database
198 function SQL_SELECT_DB ($dbName, $F, $L) {
199 // Is there still a valid link? If not, skip it.
200 if (!SQL_IS_LINK_UP()) return false;
203 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
207 function SQL_CLOSE ($F, $L) {
208 if (!SQL_IS_LINK_UP()) {
213 // Do we need to update cache/db counter?
214 //* DEBUG: */ echo "DB=".getConfig('db_hits').",CACHE=".getConfig('cache_hits')."<br />\n";
215 if ((GET_EXT_VERSION("cache") >= "0.0.7") && (getConfig('db_hits') > 0) && (getConfig('cache_hits') > 0) && (isCacheInstanceValid())) {
217 incrementConfigEntry('db_hits', getConfig('db_hits_run'));
219 // Update counter for db/cache
220 UPDATE_CONFIG(array("db_hits", "cache_hits"), array(getConfig(('db_hits')), getConfig(('cache_hits'))));
223 // Close database link and forget the link
224 $close = mysql_close(SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
234 function SQL_FREERESULT ($result) {
235 if (!is_resource($result)) {
240 $res = mysql_free_result($result);
244 // SQL string escaping
245 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true) {
247 if (!SQL_IS_LINK_UP()) return false;
252 if ($strip === true) {
258 $eval = "\$query = sprintf(\"".$qstring."\"";
259 foreach ($data as $var) {
260 if ((!empty($var)) || ($var === 0)) {
261 $eval .= ", SQL_ESCAPE(\"".$var."\",true,".$strip.")";
270 //* DEBUG: */ $fp = fopen(constant('PATH')."inc/cache/escape_debug.log", 'a') or mxchange_die("Cannot write debug.log!");
271 //* DEBUG: */ fwrite($fp, $F."(".$L."): ".str_replace("\r", "", str_replace("\n", " ", $eval))."\n");
272 //* DEBUG: */ fclose($fp);
277 // Was the eval() command fine?
278 if ($query == "failed") {
279 // Something went wrong?
280 debug_report_bug("eval={$eval}");
284 // Run SQL query (default)
285 return SQL_QUERY($query, $F, $L);
287 // Return secured string
292 // Get ID from last INSERT command
293 function SQL_INSERTID () {
294 if (!SQL_IS_LINK_UP()) return false;
295 return mysql_insert_id();
298 // Escape a string for the database
299 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
300 // Secure string first? (which is the default behaviour!)
303 $str = secureString($str, $strip);
306 if (!SQL_IS_LINK_UP()) {
307 // Fall-back to smartAddSlashes() when there is no link
308 return smartAddSlashes($str);
309 } elseif (function_exists('mysql_real_escape_string')) {
310 // The new and improved version
311 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):str={$str}<br />\n";
312 return mysql_real_escape_string($str, SQL_GET_LINK());
313 } elseif (function_exists('mysql_escape_string')) {
314 // The obsolete function
315 return mysql_escape_string($str, SQL_GET_LINK());
317 // If nothing else works, fall back to smartAddSlashes()
318 return smartAddSlashes($str);
322 // SELECT query string from table, columns and so on... ;-)
323 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
324 // Is columns an array?
325 if (!is_array($columns)) {
327 trigger_error(sprintf("columns is not array. %s!=array", gettype($columns)));
330 // Prepare the SQL statement
331 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{!_MYSQL_PREFIX!}_%s` WHERE ``='%s' LIMIT 1";
334 return SQL_QUERY_ESC($sql,
342 // ALTER TABLE wrapper function
343 function SQL_ALTER_TABLE ($sql, $F, $L) {
344 // This is the default result...
347 // Determine index/fulltext/unique word
348 // 12 3 3 2 2 3 3 2 2 3 3 21
349 $noIndex = ((ereg("INDEX", $sql) == false) && (ereg("FULLTEXT", $sql) == false) && (ereg("UNIQUE", $sql) == false));
351 // Extract table name
352 $tableArray = explode(" ", $sql);
353 $tableName = str_replace("`", "", $tableArray[2]);
355 // Shall we add/drop?
356 if (((ereg("ADD", $sql)) || (ereg("DROP", $sql))) && ($noIndex)) {
357 // And column name as well
358 $columnName = str_replace("`", "", $tableArray[4]);
360 // Get column information
361 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM %s LIKE '%s'",
362 array($tableName, $columnName), __FILE__, __LINE__);
364 // Do we have no entry on ADD or an entry on DROP?
365 // 123 4 4 3 3 4 432 23 4 4 3 3 4 4321
366 if (((SQL_NUMROWS($result) == 0) && (ereg("ADD", $sql))) || ((SQL_NUMROWS($result) == 1) && (ereg("DROP", $sql)))) {
368 //* DEBUG: */ print __LINE__.":".$sql."<br />\n";
369 $result = SQL_QUERY($sql, $F, $L, false);
371 } elseif ((constant('_TABLE_TYPE') == "InnoDB") && (ereg("FULLTEXT", $sql))) {
372 // Skip this query silently
373 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
374 } elseif (!$noIndex) {
375 // And column name as well
376 $columnName = str_replace("`", "", $tableArray[4]);
378 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
379 if (in_array(strtoupper($columnName), array("INDEX", "UNIQUE", "KEY", "FULLTEXT"))) {
381 $begin = 1; $columnName = ",";
382 while (strpos($columnName, ",") !== false) {
384 $columnName = str_replace("`", "", $tableArray[count($tableArray) - $begin]);
385 //* DEBUG: */ print __LINE__.":".$columnName."----------------".$begin."<br />\n";
388 $columnName = str_replace("(", "", str_replace(")", "", $columnName));
389 //* DEBUG: */ print __LINE__.":".$columnName."----------------".$begin."<br />\n";
397 $result = SQL_QUERY_ESC("SHOW INDEX FROM %s",
398 array($tableName), __FILE__, __LINE__);
402 while ($content = SQL_FETCHARRAY($result)) {
404 //* DEBUG: */ print "<pre>".print_r($content, true)."</pre>";
405 if (($content['Column_name'] == $columnName) || ($content['Key_name'] == $columnName)) {
407 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Skiped: %s", $sql));
414 SQL_FREERESULT($result);
418 // Send it to the SQL_QUERY() function
419 //* DEBUG: */ print __LINE__.":".$sql."<br />\n";
420 $result = SQL_QUERY($sql, $F, $L, false);
423 // Other ALTER TABLE query
424 //* DEBUG: */ print __LINE__.":".$sql."<br />\n";
425 $result = SQL_QUERY($sql, $F, $L, false);
432 // Getter for SQL link
433 function SQL_GET_LINK () {
437 // Is it in the globals?
438 if (isset($GLOBALS['sql_link'])) {
440 $link = $GLOBALS['sql_link'];
448 function SQL_SET_LINK ($link) {
449 // Is this a resource or null?
450 if ((!is_resource($link)) && (!is_null($link))) {
451 // This should never happen!
452 trigger_error(sprintf("link is not resource or null. Type: %s", gettype($link)));
456 $GLOBALS['sql_link'] = $link;
459 // Checks if the link is up
460 function SQL_IS_LINK_UP () {
462 $link = SQL_GET_LINK();
465 return (is_resource($link));