2 /************************************************************************
3 * Mailer v0.2.1-FINAL 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 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
46 function SQL_QUERY ($sqlString, $F, $L) {
48 $sqlString = trim($sqlString);
51 if (!SQL_IS_LINK_UP()) {
52 // We should not quietly ignore this!
53 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
59 // Return 'false' because it has failed
61 } elseif (empty($sqlString)) {
63 debug_report_bug(__FUNCTION__, __LINE__, sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
68 // This is invalid, of course
72 // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
73 $sqlString = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlString)));
75 // Compile config entries out
76 $GLOBALS['last_sql'] = SQL_PREPARE_SQL_STRING($sqlString);
79 $querytimeBefore = microtime(true);
82 //* DEBUG: */ print('F=' . basename($F) . ',L=' . $L . 'sql=' . htmlentities($GLOBALS['last_sql']) . '<br />');
83 $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
84 or debug_report_bug($F, $L, 'file='. $F . ',line=' . $L . ':mysql_error()=' . mysql_error() . "\n".
85 'Query string:' . $GLOBALS['last_sql']);
86 //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS());
88 // Calculate query time
89 $queryTime = microtime(true) - $querytimeBefore;
91 // Add this query to array including timing
92 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
94 // Save last successfull query
95 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
97 // Count all query times
98 incrementConfigEntry('sql_time', $queryTime);
101 incrementConfigEntry('sql_count');
104 if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
106 // Debugging stuff...
108 $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write mysql.log!');
109 if (!isset($GLOBALS['sql_first_entry'])) {
111 fwrite($fp, 'Module=' . getModule() . "\n");
112 $GLOBALS['sql_first_entry'] = true;
114 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $GLOBALS['last_sql'])) . "\n");
119 if (!isStatsEntrySet('db_hits')) {
120 // Count in dummy variable
121 setStatsEntry('db_hits', 1);
123 // Count to config array
124 incrementStatsEntry('db_hits');
132 function SQL_NUMROWS ($resource) {
133 // Valid link resource?
134 if (!SQL_IS_LINK_UP()) return false;
136 // Link is not up, no rows by default
139 // Is the result a valid resource?
140 if (is_resource($resource)) {
141 // Get the count of rows from database
142 $lines = mysql_num_rows($resource);
144 // No resource given, please fix this
145 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
153 function SQL_AFFECTEDROWS() {
154 // Valid link resource?
155 if (!SQL_IS_LINK_UP()) return false;
158 $lines = mysql_affected_rows(SQL_GET_LINK());
165 function SQL_FETCHROW ($resource) {
166 // Is a result resource set?
167 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
169 // Fetch the data and return it
170 return mysql_fetch_row($resource);
174 function SQL_FETCHARRAY ($res, $nr=0) {
175 // Is a result resource set?
176 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
178 // Load row from database
179 $row = mysql_fetch_assoc($res);
181 // Return only arrays here
182 if (is_array($row)) {
186 // Return a false, else some loops would go endless...
192 function SQL_RESULT ($resource, $row, $field = '0') {
193 // Is $resource valid?
194 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
196 // Run the result command
197 $result = mysql_result($resource, $row, $field);
199 // ... and return the result
204 function SQL_CONNECT ($host, $login, $password, $F, $L) {
206 $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
208 // Set the link resource
209 SQL_SET_LINK($connect);
212 unset($GLOBALS['is_sql_link_up']);
215 // SQL select database
216 function SQL_SELECT_DB ($dbName, $F, $L) {
217 // Is there still a valid link? If not, skip it.
218 if (!SQL_IS_LINK_UP()) return false;
221 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
225 function SQL_CLOSE ($F, $L) {
226 if (!SQL_IS_LINK_UP()) {
231 // Close database link and forget the link
232 $close = mysql_close(SQL_GET_LINK())
233 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
239 unset($GLOBALS['is_sql_link_up']);
246 function SQL_FREERESULT ($resource) {
247 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
253 $res = mysql_free_result($resource);
255 // And return that result of freeing it...
259 // SQL string escaping
260 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
262 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
265 $dataSecured['__sql_string'] = $sqlString;
266 foreach ($data as $key => $value) {
267 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
271 $query = call_user_func_array('sprintf', $dataSecured);
275 //* DEBUG: */ $fp = fopen(getConfig('CACHE_PATH') . 'escape_debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write debug.log!');
276 //* DEBUG: */ fwrite($fp, $F . '(' . $L . '): ' . str_replace("\r", '', str_replace("\n", ' ', $eval)) . "\n");
277 //* DEBUG: */ fclose($fp);
280 // Run SQL query (default)
281 return SQL_QUERY($query, $F, $L);
283 // Return secured string
288 // Get id from last INSERT command
289 function SQL_INSERTID () {
290 if (!SQL_IS_LINK_UP()) return false;
291 return mysql_insert_id();
294 // Escape a string for the database
295 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
297 if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
298 // Secure string first? (which is the default behaviour!)
299 if ($secureString === true) {
301 $str = secureString($str, $strip);
304 if (!SQL_IS_LINK_UP()) {
305 // Fall-back to escapeQuotes() when there is no link
306 $ret = escapeQuotes($str);
307 } elseif (function_exists('mysql_real_escape_string')) {
308 // The new and improved version
309 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
310 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
311 } elseif (function_exists('mysql_escape_string')) {
312 // The obsolete function
313 $ret = mysql_escape_string($str, SQL_GET_LINK());
315 // If nothing else works, fall back to escapeQuotes() again
316 $ret = escapeQuotes($str);
320 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
324 return $GLOBALS['sql_escapes'][''.$str.''];
327 // SELECT query string from table, columns and so on... ;-)
328 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
329 // Is columns an array?
330 if (!is_array($columns)) {
332 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
338 // Abort here with 'false'
342 // Prepare the SQL statement
343 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
346 return SQL_QUERY_ESC($sql,
355 // ALTER TABLE wrapper function
356 function SQL_ALTER_TABLE ($sql, $F, $L) {
357 // Abort if link is down
358 if (!SQL_IS_LINK_UP()) return false;
360 // This is the default result...
363 // Determine index/fulltext/unique word
366 strpos($sql, 'INDEX') === false
368 strpos($sql, 'KEY') === false
370 strpos($sql, 'FULLTEXT') === false
372 strpos($sql, 'UNIQUE') === false
376 // Extract table name
377 $tableArray = explode(' ', $sql);
378 $tableName = str_replace('`', '', $tableArray[2]);
380 // Shall we add/drop?
381 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
382 // Try two columns, one should fix
383 foreach (array(4,5) as $idx) {
384 // And column name as well
385 $columnName = str_replace('`', '', $tableArray[$idx]);
387 // Get column information
388 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
389 array($tableName, $columnName), __FUNCTION__, __LINE__);
391 // Do we have no entry on ADD or an entry on DROP?
392 // 123 4 4 3 3 4 4 32 23 4 4 3 3 4 4 321
393 if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
395 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
396 $result = SQL_QUERY($sql, $F, $L, false);
398 // Skip further attempt(s)
400 } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
401 // Abort here because it is alreay there
402 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
404 } elseif ($columnName != 'KEY') {
405 // Something didn't fit
406 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
409 } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
410 // Skip this query silently
411 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
412 } elseif ($noIndex === false) {
413 // And column name as well
414 //* DEBUG: */ print __LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>';
415 $keyName = str_replace('`', '', $tableArray[5]);
417 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
418 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
420 $begin = 1; $keyName = ',';
421 while (strpos($keyName, ',') !== false) {
423 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
424 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
427 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
428 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
436 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
438 // Non-skipping is default for ADD
441 // But should we DROP?
442 if ($tableArray[3] == 'DROP') {
443 // Then skip if nothing found!
445 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
449 while ($content = SQL_FETCHARRAY($result)) {
451 //* DEBUG: */ print(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
452 if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
454 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
457 } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
459 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
466 SQL_FREERESULT($result);
469 if ($skip === false) {
470 // Send it to the SQL_QUERY() function
471 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
472 $result = SQL_QUERY($sql, $F, $L, false);
475 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
478 // Other ALTER TABLE query
479 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
480 $result = SQL_QUERY($sql, $F, $L, false);
487 // Getter for SQL link
488 function SQL_GET_LINK () {
492 // Is it in the globals?
493 if (isset($GLOBALS['sql_link'])) {
495 $link = $GLOBALS['sql_link'];
503 function SQL_SET_LINK ($link) {
504 // Is this a resource or null?
505 if ((!is_resource($link)) && (!is_null($link))) {
506 // This should never happen!
507 debug_report_bug(__FUNCTION__, __LINE__, sprintf("link is not resource or null. Type: %s", gettype($link)));
511 $GLOBALS['sql_link'] = $link;
514 // Checks if the link is up
515 function SQL_IS_LINK_UP () {
519 // Do we have cached this?
520 if (isset($GLOBALS['is_sql_link_up'])) {
522 $linkUp = $GLOBALS['is_sql_link_up'];
525 $linkUp = is_resource(SQL_GET_LINK());
528 $GLOBALS['is_sql_link_up'] = $linkUp;
535 // Wrapper function to make code more readable
536 function SQL_HASZERONUMS ($result) {
537 // Just pass it through
538 return (SQL_NUMROWS($result) === 0);
541 // Private function to prepare the SQL query string
542 function SQL_PREPARE_SQL_STRING ($sqlString) {
543 // Is it already cached?
544 if (!isset($GLOBALS['sql_strings'][$sqlString])) {
545 // Compile config+expression code
546 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
548 // Do final compilation
549 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false);
553 return $GLOBALS['sql_strings'][$sqlString];