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 - 2009 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')) {
45 function SQL_QUERY ($sqlString, $F, $L) {
47 $sqlString = trim($sqlString);
50 if (!SQL_IS_LINK_UP()) {
51 // We should not quietly ignore this!
52 debug_report_bug(sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
58 // Return 'false' because it has failed
60 } elseif (empty($sqlString)) {
62 debug_report_bug(sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
67 // This is invalid, of course
71 // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
72 $sqlString = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlString)));
75 $sqlString = FILTER_COMPILE_CONFIG($sqlString);
78 $querytimeBefore = array_sum(explode(' ', microtime()));
81 //* DEBUG: */ print($sqlString . '<br />');
82 $result = mysql_query($sqlString, SQL_GET_LINK())
83 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error() . '<br />
86 //* DEBUG: */ print(__LINE__ . ': numRows=' . SQL_NUMROWS($result) . ',affected=' . SQL_AFFECTEDROWS() . "<br />");
89 $querytimeAfter = array_sum(explode(' ', microtime()));
91 // Calculate query time
92 $queryTime = $querytimeAfter - $querytimeBefore;
94 // Add this query to array including timing
95 addSqlToDebug($result, $sqlString, $queryTime, $F, $L);
97 // Save last successfull query
98 setConfigEntry('db_last_query', $sqlString);
100 // Count all query times
101 incrementConfigEntry('sql_time', $queryTime);
104 incrementConfigEntry('sql_count');
107 if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y')) {
109 // Debugging stuff...
111 $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write mysql.log!");
112 if (!isset($GLOBALS['sql_first_entry'])) {
114 fwrite($fp, 'Module=' . getModule() . "\n");
115 $GLOBALS['sql_first_entry'] = true;
117 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $sqlString)) . "\n");
122 if (!isStatsEntrySet('db_hits_run')) {
123 // Count in dummy variable
124 setStatsEntry('db_hits_run', 1);
126 // Count to config array
127 incrementStatsEntry('db_hits_run');
135 function SQL_NUMROWS ($result) {
136 // Link is not up, no rows by default
139 // Is the result a valid resource?
140 if (is_resource($result)) {
141 // Get the count of rows from database
142 $lines = mysql_num_rows($result);
144 // Is the result empty? Then we have an error!
145 if (empty($lines)) $lines = 0;
146 } elseif (SQL_IS_LINK_UP()) {
147 // No resource given, no lines found!
156 function SQL_AFFECTEDROWS() {
157 // Valid link resource?
158 if (!SQL_IS_LINK_UP()) return false;
161 $lines = mysql_affected_rows(SQL_GET_LINK());
168 function SQL_FETCHROW ($result) {
169 // Is a result resource set?
170 if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) return false;
172 // Fetch the data and return it
173 return mysql_fetch_row($result);
177 function SQL_FETCHARRAY ($res, $nr=0, $remove_numerical=true) {
178 // Is a result resource set?
179 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
184 // Load row from database
185 $row = mysql_fetch_array($res);
187 // Return only arrays here
188 if (is_array($row)) {
189 // Shall we remove numerical data here automatically?
190 if ($remove_numerical) {
191 // So let's remove all numerical elements to save memory!
193 for ($idx = 0; $idx < ($max / 2); $idx++) {
202 // Return a false here...
208 function SQL_RESULT ($res, $row, $field = 0) {
210 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
212 // Run the result command and return the result
213 $result = mysql_result($res, $row, $field);
218 function SQL_CONNECT ($host, $login, $password, $F, $L) {
220 $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
222 // Set the link resource
223 SQL_SET_LINK($connect);
226 unset($GLOBALS['sql_link_res']);
229 // SQL select database
230 function SQL_SELECT_DB ($dbName, $F, $L) {
231 // Is there still a valid link? If not, skip it.
232 if (!SQL_IS_LINK_UP()) return false;
235 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
239 function SQL_CLOSE ($F, $L) {
240 if (!SQL_IS_LINK_UP()) {
245 // Close database link and forget the link
246 $close = mysql_close(SQL_GET_LINK())
247 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
253 unset($GLOBALS['sql_link_res']);
256 incrementStatsEntry('db_hits', getStatsEntry('db_hits_run'));
263 function SQL_FREERESULT ($result) {
264 if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) {
269 $res = mysql_free_result($result);
273 // SQL string escaping
274 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure=true) {
276 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
280 $dataSecured['__sql_string'] = $qstring;
281 foreach ($data as $key => $value) {
282 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
286 $query = call_user_func_array('sprintf', $dataSecured);
288 /* Old eval() way... *
292 if ($strip === true) {
298 if ($secure === true) {
304 $eval = "\$query = sprintf(\"" . $qstring . "\"";
305 foreach ($data as $var) {
306 if ((!empty($var)) || ($var === 0)) {
307 $eval .= ", SQL_ESCAPE('" . $var . "', " . $secure . ', ' . $strip . ')';
317 //* DEBUG: */ $fp = fopen(getConfig('CACHE_PATH') . 'escape_debug.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write debug.log!");
318 //* DEBUG: */ fwrite($fp, $F.'('.$L."): ".str_replace("\r", '', str_replace("\n", " ", $eval))."\n");
319 //* DEBUG: */ fclose($fp);
325 // Was the eval() command fine?
326 if ($query == 'failed') {
327 // Something went wrong?
328 debug_report_bug('eval=' . $eval);
333 // Run SQL query (default)
334 return SQL_QUERY($query, $F, $L);
336 // Return secured string
341 // Get ID from last INSERT command
342 function SQL_INSERTID () {
343 if (!SQL_IS_LINK_UP()) return false;
344 return mysql_insert_id();
347 // Escape a string for the database
348 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
350 if (isset($GLOBALS['sql_escapes'][$str])) {
351 // Then use it instead
352 return $GLOBALS['sql_escapes'][$str];
355 // Secure string first? (which is the default behaviour!)
356 if ($secureString === true) {
358 $str = secureString($str, $strip);
361 if (!SQL_IS_LINK_UP()) {
362 // Fall-back to smartAddSlashes() when there is no link
363 $ret = smartAddSlashes($str);
364 } elseif (function_exists('mysql_real_escape_string')) {
365 // The new and improved version
366 //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):str={$str}<br />");
367 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
368 } elseif (function_exists('mysql_escape_string')) {
369 // The obsolete function
370 $ret = mysql_escape_string($str, SQL_GET_LINK());
372 // If nothing else works, fall back to smartAddSlashes() again
373 $ret = smartAddSlashes($str);
377 $GLOBALS['sql_escapes'][$str] = $ret;
383 // SELECT query string from table, columns and so on... ;-)
384 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
385 // Is columns an array?
386 if (!is_array($columns)) {
388 debug_report_bug(sprintf("columns is not an array. %s != array, file=%s, line=%s",
394 // Abort here with 'false'
398 // Prepare the SQL statement
399 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
402 return SQL_QUERY_ESC($sql,
411 // ALTER TABLE wrapper function
412 function SQL_ALTER_TABLE ($sql, $F, $L) {
413 // Abort if link is down
414 if (!SQL_IS_LINK_UP()) return false;
416 // This is the default result...
419 // Determine index/fulltext/unique word
422 strpos($sql, 'INDEX') === false
424 strpos($sql, 'FULLTEXT') === false
426 strpos($sql, 'UNIQUE') === false
430 // Extract table name
431 $tableArray = explode(" ", $sql);
432 $tableName = str_replace('`', '', $tableArray[2]);
434 // Shall we add/drop?
435 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
436 // And column name as well
437 $columnName = str_replace('`', '', $tableArray[4]);
439 // Get column information
440 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
441 array($tableName, $columnName), __FILE__, __LINE__);
443 // Do we have no entry on ADD or an entry on DROP?
444 // 123 4 4 3 3 4 4 32 23 4 4 3 3 4 4 321
445 if (((SQL_NUMROWS($result) == 0) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
447 //* DEBUG: */ print(__LINE__.':'.$sql."<br />");
448 $result = SQL_QUERY($sql, $F, $L, false);
450 } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
451 // Skip this query silently
452 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
453 } elseif ($noIndex === false) {
454 // And column name as well
455 $columnName = str_replace('`', '', $tableArray[4]);
457 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
458 if (in_array(strtoupper($columnName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
460 $begin = 1; $columnName = ',';
461 while (strpos($columnName, ',') !== false) {
463 $columnName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
464 //* DEBUG: */ print(__LINE__.':'.$columnName."----------------".$begin."<br />");
467 $columnName = str_replace('(', '', str_replace(')', '', $columnName));
468 //* DEBUG: */ print(__LINE__.':'.$columnName."----------------".$begin."<br />");
476 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`",
477 array($tableName), __FILE__, __LINE__);
481 while ($content = SQL_FETCHARRAY($result)) {
483 //* DEBUG: */ print("<pre>".print_r($content, true)."</pre>");
484 if (($content['Column_name'] == $columnName) || ($content['Key_name'] == $columnName)) {
486 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skiped: %s", $sql));
493 SQL_FREERESULT($result);
496 if ($skip === false) {
497 // Send it to the SQL_QUERY() function
498 //* DEBUG: */ print(__LINE__.':'.$sql."<br />");
499 $result = SQL_QUERY($sql, $F, $L, false);
502 // Other ALTER TABLE query
503 //* DEBUG: */ print(__LINE__.':'.$sql."<br />");
504 $result = SQL_QUERY($sql, $F, $L, false);
511 // Getter for SQL link
512 function SQL_GET_LINK () {
516 // Is it in the globals?
517 if (isset($GLOBALS['sql_link'])) {
519 $link = $GLOBALS['sql_link'];
527 function SQL_SET_LINK ($link) {
528 // Is this a resource or null?
529 if ((!is_resource($link)) && (!is_null($link))) {
530 // This should never happen!
531 debug_report_bug(sprintf("link is not resource or null. Type: %s", gettype($link)));
535 $GLOBALS['sql_link'] = $link;
538 // Checks if the link is up
539 function SQL_IS_LINK_UP () {
543 // Do we have cached this?
544 if (isset($GLOBALS['sql_link_res'])) {
546 $linkUp = $GLOBALS['sql_link_res'];
549 $linkUp = is_resource(SQL_GET_LINK());
552 $GLOBALS['sql_link_res'] = $linkUp;