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/4/5 server *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Datenbankschicht fuer MySQL 3/4/5 Server *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
44 function SQL_QUERY ($sqlString, $F, $L, $enableCodes = true) {
46 if (!isset($GLOBALS[__FUNCTION__][$sqlString])) {
47 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called: ' . $sqlString);
50 $sqlStringModified = trim($sqlString);
52 // Empty query string or link is not up?
53 if (empty($sqlStringModified)) {
55 debug_report_bug(__FUNCTION__, __LINE__, sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
59 } elseif (!SQL_IS_LINK_UP()) {
60 // We should not quietly ignore this
61 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
68 // Remove \t, \n and \r from queries they may confuse some MySQL versions
69 $sqlStringModified = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlStringModified)));
71 // Compile config entries out
72 $sqlStringModified = SQL_PREPARE_SQL_STRING($sqlStringModified, $enableCodes);
74 // Cache it and remember as last SQL query
75 $GLOBALS[__FUNCTION__][$sqlString] = $sqlStringModified;
76 $GLOBALS['last_sql'] = $sqlStringModified;
77 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Stored cache: ' . $sqlStringModified);
79 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
81 // Use cache (to save a lot function calls
82 $GLOBALS['last_sql'] = $GLOBALS[__FUNCTION__][$sqlString];
84 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache is: ' . $sqlString);
88 $querytimeBefore = microtime(true);
91 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
92 $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
93 or debug_report_bug($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . ',last_query=' . $GLOBALS['last_sql']);
94 //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
96 // Calculate query time
97 $queryTime = microtime(true) - $querytimeBefore;
99 // Add this query to array including timing
100 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
102 // Save last successfull query
103 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
105 // Count all query times
106 incrementConfigEntry('sql_time', $queryTime);
109 incrementConfigEntry('sql_count');
112 if ((!isCssOutputMode()) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
113 // Is this the first call?
114 if (!isset($GLOBALS['sql_first_entry'])) {
116 appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
117 $GLOBALS['sql_first_entry'] = true;
121 appendLineToFile(getCachePath() . 'mysql.log', basename($F) . '|LINE=' . $L . '|NUM=' . (is_resource($result) ? SQL_NUMROWS($result) : 'false') . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $GLOBALS['last_sql'])));
125 if (!isStatsEntrySet('db_hits')) {
126 // Count in dummy variable
127 setStatsEntry('db_hits', 1);
129 // Count to config array
130 incrementStatsEntry('db_hits');
138 function SQL_NUMROWS ($resource) {
139 // Valid link resource?
140 if (!SQL_IS_LINK_UP()) return false;
142 // Link is not up, no rows by default
145 // Is the result a valid resource?
146 if (isset($GLOBALS['sql_numrows'][$resource])) {
148 $lines = $GLOBALS['sql_numrows'][intval($resource)];
149 } elseif (is_resource($resource)) {
150 // Get the count of rows from database
151 $lines = mysql_num_rows($resource);
153 // Remember it in cache
154 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
156 // No resource given, please fix this
157 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
165 function SQL_AFFECTEDROWS() {
166 // Valid link resource?
167 if (!SQL_IS_LINK_UP()) return false;
170 $lines = mysql_affected_rows(SQL_GET_LINK());
177 function SQL_FETCHROW ($resource) {
178 // Is a result resource set?
179 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
181 // Fetch the data and return it
182 return mysql_fetch_row($resource);
186 function SQL_FETCHARRAY ($res) {
187 // Is a result resource set?
188 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
190 // Load row from database
191 $row = mysql_fetch_assoc($res);
193 // Return only arrays here
194 if (is_array($row)) {
198 // Return a false, else some loops would go endless...
204 function SQL_RESULT ($resource, $row, $field = '0') {
205 // Is $resource valid?
206 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
208 // Run the result command
209 $result = mysql_result($resource, $row, $field);
211 // ... and return the result
216 function SQL_CONNECT ($host, $login, $password, $F, $L) {
218 $linkResource = mysql_connect($host, $login, $password) or debug_report_bug(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
220 // Set the link resource
221 SQL_SET_LINK($linkResource);
224 // SQL select database
225 function SQL_SELECT_DB ($dbName, $F, $L) {
226 // Is there still a valid link? If not, skip it.
227 if (!SQL_IS_LINK_UP()) return false;
230 return mysql_select_db($dbName, SQL_GET_LINK()) or debug_report_bug(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
234 function SQL_CLOSE ($F, $L) {
235 if (!SQL_IS_LINK_UP()) {
240 // Close database link and forget the link
241 $close = mysql_close(SQL_GET_LINK()) or debug_report_bug(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
251 function SQL_FREERESULT ($resource) {
252 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
258 $res = mysql_free_result($resource);
260 // And return that result of freeing it...
264 // SQL string escaping
265 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
267 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
270 $dataSecured['__sql_string'] = $sqlString;
271 foreach ($data as $key => $value) {
272 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
276 $query = call_user_func_array('sprintf', $dataSecured);
279 // Run SQL query (default)
280 return SQL_QUERY($query, $F, $L);
282 // Return secured string
287 // Get id from last INSERT command
288 function SQL_INSERTID () {
289 if (!SQL_IS_LINK_UP()) return false;
290 return mysql_insert_id();
293 // Escape a string for the database
294 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
296 if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
297 // Prepare the string here
298 $str = SQL_PREPARE_SQL_STRING($str);
300 // Secure string first? (which is the default behaviour!)
301 if ($secureString === true) {
303 $str = secureString($str, $strip);
306 if (!SQL_IS_LINK_UP()) {
307 // Fall-back to escapeQuotes() when there is no link
308 $ret = escapeQuotes($str);
309 } elseif (function_exists('mysql_real_escape_string')) {
310 // The new and improved version
311 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
312 } elseif (function_exists('mysql_escape_string')) {
313 // The obsolete function
314 $ret = mysql_escape_string($str, SQL_GET_LINK());
316 // If nothing else works, fall back to escapeQuotes() again
317 $ret = escapeQuotes($str);
321 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
325 return $GLOBALS['sql_escapes'][''.$str.''];
328 // SELECT query string from table, columns and so on... ;-)
329 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
330 // Is columns an array?
331 if (!is_array($columns)) {
333 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
339 // Abort here with 'false'
343 // Is this is a simple array?
344 if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
345 // Begin with SQL query
348 // No, it comes from XML, so get it back from it
349 $sql .= getSqlPartFromXmlArray($columns);
352 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
354 // Yes, prepare the SQL statement
355 $sql = 'SELECT `' . implode('`,`', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
359 return SQL_QUERY_ESC($sql,
368 // ALTER TABLE wrapper function
369 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = true) {
370 // Abort if link is down
371 if (!SQL_IS_LINK_UP()) return false;
373 // This is the default result...
376 // Determine index/fulltext/unique word
379 isInString('INDEX', $sql)
381 isInString('KEY', $sql)
383 isInString('FULLTEXT', $sql)
385 isInString('UNIQUE', $sql)
389 // Extract table name
390 $tableArray = explode(' ', $sql);
391 $tableName = str_replace('`', '', $tableArray[2]);
394 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, true) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
396 // Shall we add/drop?
397 if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === false)) {
398 // Try two columns, one should fix
399 foreach (array(4,5) as $idx) {
400 // If an entry is not set, abort here
401 if (!isset($tableArray[$idx])) {
403 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
407 // And column name as well
408 $columnName = $tableArray[$idx];
411 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(isSqlTableColumnFound($tableName, $columnName)));
413 // Do we have no entry on ADD or an entry on DROP/CHANGE?
414 if (((!isSqlTableColumnFound($tableName, $columnName)) && (isInString('ADD', $sql))) || ((isSqlTableColumnFound($tableName, $columnName)) && ((isInString('DROP', $sql)) || ((isInString('CHANGE', $sql)) && ($idx == 4) && ((!isSqlTableColumnFound($tableName, $tableArray[5])) || ($columnName == $tableArray[5])))))) {
416 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
417 $result = SQL_QUERY($sql, $F, $L, false);
419 // Skip further attempt(s)
421 } elseif ((((isSqlTableColumnFound($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!isSqlTableColumnFound($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
422 // Abort here because it is alreay there
423 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
425 } elseif ((!isSqlTableColumnFound($tableName, $columnName)) && (isInString('DROP', $sql))) {
426 // Abort here because we tried to drop a column which is not there (never created maybe)
427 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
429 } elseif ($columnName != 'KEY') {
430 // Something didn't fit, we better log it
431 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(isSqlTableColumnFound($tableName, $columnName)) . '');
434 } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
435 // Skip this query silently because InnoDB does not understand fulltext indexes
436 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s", $sql, $tableName, intval((is_bool($result)) ? 0 : isSqlTableColumnFound($columnName)), $F, $L));
437 } elseif ($isAlterIndex === true) {
438 // And column name as well without backticks
439 $keyName = str_replace('`', '', $tableArray[5]);
440 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
442 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
443 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
447 while (isInString(',', $keyName)) {
449 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
450 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
454 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
455 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
463 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
464 if (($tableArray[3] == 'ADD') && (!isSqlTableIndexFound($tableName, $keyName))) {
465 // Send it to the SQL_QUERY() function to add it
466 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
467 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
468 } elseif (($tableArray[3] == 'DROP') && (isSqlTableIndexFound($tableName, $keyName))) {
469 // Send it to the SQL_QUERY() function to drop it
470 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
471 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
474 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
477 // Other ALTER TABLE query
478 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
479 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
486 // Getter for SQL link
487 function SQL_GET_LINK () {
491 // Is it in the globals?
492 if (isset($GLOBALS['sql_link'])) {
494 $link = $GLOBALS['sql_link'];
502 function SQL_SET_LINK ($link) {
503 // Is this a resource or null?
504 if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
505 // This may happen in installation phase
507 } elseif ((!is_resource($link)) && (!is_null($link))) {
508 // This should never happen!
509 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Type of link is not resource or null, type=%s", gettype($link)));
513 $GLOBALS['sql_link'] = $link;
516 $GLOBALS['is_sql_link_up'] = is_resource($link);
519 // Checks if the link is up
520 function SQL_IS_LINK_UP () {
524 // Do we have cached this?
525 if (isset($GLOBALS['is_sql_link_up'])) {
527 $linkUp = $GLOBALS['is_sql_link_up'];
530 $linkUp = is_resource(SQL_GET_LINK());
533 $GLOBALS['is_sql_link_up'] = $linkUp;
540 // Wrapper function to make code more readable
541 function SQL_HASZERONUMS ($result) {
542 // Just pass it through
543 return (SQL_NUMROWS($result) === 0);
546 // Wrapper function to make code more readable
547 function SQL_HASZEROAFFECTED () {
548 // Just pass it through
549 return (SQL_AFFECTEDROWS() === 0);
552 // Private function to prepare the SQL query string
553 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
554 // Is it already cached?
555 if (!isset($GLOBALS['sql_strings'][$sqlString])) {
556 // Compile URI codes+config+expression code
557 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG(compileUriCode($sqlString)));
559 // Do final compilation
560 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
564 return $GLOBALS['sql_strings'][$sqlString];
567 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
568 function SQL_EPOCHE_TO_TIMESTAMP ($timestamp) {
569 return generateDateTime($timestamp, 7);
572 // Check if there is a SQL table created
573 function isSqlTableCreated ($tableName) {
574 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
576 if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
577 // Check if the table is there
578 $result = SQL_QUERY_ESC("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
579 array($tableName), __FILE__, __LINE__);
581 // Is there an entry?
582 $GLOBALS[__FUNCTION__][$tableName] = (SQL_NUMROWS($result) == 1);
583 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
587 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
588 return $GLOBALS[__FUNCTION__][$tableName];
591 // Is a table column there?
592 function isSqlTableColumnFound ($tableName, $columnName) {
593 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
595 if (!isset($GLOBALS[__FUNCTION__][$tableName][$columnName])) {
596 // And column name as well
597 $columnName = str_replace('`', '', $columnName);
599 // Get column information
600 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
601 array($tableName, $columnName), __FUNCTION__, __LINE__);
604 $GLOBALS[__FUNCTION__][$tableName][$columnName] = (!SQL_HASZERONUMS($result));
605 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)) . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]));
608 SQL_FREERESULT($result);
612 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]) . ' - EXIT!');
613 return $GLOBALS[__FUNCTION__][$tableName][$columnName];
616 // Checks depending on the mode if the index is there
617 function isSqlTableIndexFound ($tableName, $keyName) {
618 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ' - ENTERED!');
620 if (!isset($GLOBALS[__FUNCTION__][$tableName][$keyName])) {
622 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
624 // The column is not found by default
625 $GLOBALS[__FUNCTION__][$tableName][$keyName] = false;
628 while ($content = SQL_FETCHARRAY($result)) {
629 // Add all entries for better caching behavior
630 $GLOBALS[__FUNCTION__][$tableName][$content['Key_name']] = true;
634 SQL_FREERESULT($result);
637 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$keyName]) . ' - CACHE!');
641 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$keyName]) . ' - EXIT!');
642 return $GLOBALS[__FUNCTION__][$tableName][$keyName];