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://www.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() . "\n".
94 'Query string:' . $GLOBALS['last_sql']);
95 //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
97 // Calculate query time
98 $queryTime = microtime(true) - $querytimeBefore;
100 // Add this query to array including timing
101 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
103 // Save last successfull query
104 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
106 // Count all query times
107 incrementConfigEntry('sql_time', $queryTime);
110 incrementConfigEntry('sql_count');
113 if ((!isCssOutputMode()) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
114 // Is this the first call?
115 if (!isset($GLOBALS['sql_first_entry'])) {
117 appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
118 $GLOBALS['sql_first_entry'] = true;
122 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'])));
126 if (!isStatsEntrySet('db_hits')) {
127 // Count in dummy variable
128 setStatsEntry('db_hits', 1);
130 // Count to config array
131 incrementStatsEntry('db_hits');
139 function SQL_NUMROWS ($resource) {
140 // Valid link resource?
141 if (!SQL_IS_LINK_UP()) return false;
143 // Link is not up, no rows by default
146 // Is the result a valid resource?
147 if (isset($GLOBALS['sql_numrows'][$resource])) {
149 $lines = $GLOBALS['sql_numrows'][intval($resource)];
150 } elseif (is_resource($resource)) {
151 // Get the count of rows from database
152 $lines = mysql_num_rows($resource);
154 // Remember it in cache
155 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
157 // No resource given, please fix this
158 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
166 function SQL_AFFECTEDROWS() {
167 // Valid link resource?
168 if (!SQL_IS_LINK_UP()) return false;
171 $lines = mysql_affected_rows(SQL_GET_LINK());
178 function SQL_FETCHROW ($resource) {
179 // Is a result resource set?
180 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
182 // Fetch the data and return it
183 return mysql_fetch_row($resource);
187 function SQL_FETCHARRAY ($res) {
188 // Is a result resource set?
189 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
191 // Load row from database
192 $row = mysql_fetch_assoc($res);
194 // Return only arrays here
195 if (is_array($row)) {
199 // Return a false, else some loops would go endless...
205 function SQL_RESULT ($resource, $row, $field = '0') {
206 // Is $resource valid?
207 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
209 // Run the result command
210 $result = mysql_result($resource, $row, $field);
212 // ... and return the result
217 function SQL_CONNECT ($host, $login, $password, $F, $L) {
219 $linkResource = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
221 // Set the link resource
222 SQL_SET_LINK($linkResource);
225 // SQL select database
226 function SQL_SELECT_DB ($dbName, $F, $L) {
227 // Is there still a valid link? If not, skip it.
228 if (!SQL_IS_LINK_UP()) return false;
231 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
235 function SQL_CLOSE ($F, $L) {
236 if (!SQL_IS_LINK_UP()) {
241 // Close database link and forget the link
242 $close = mysql_close(SQL_GET_LINK())
243 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
253 function SQL_FREERESULT ($resource) {
254 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
260 $res = mysql_free_result($resource);
262 // And return that result of freeing it...
266 // SQL string escaping
267 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
269 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
272 $dataSecured['__sql_string'] = $sqlString;
273 foreach ($data as $key => $value) {
274 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
278 $query = call_user_func_array('sprintf', $dataSecured);
281 // Run SQL query (default)
282 return SQL_QUERY($query, $F, $L);
284 // Return secured string
289 // Get id from last INSERT command
290 function SQL_INSERTID () {
291 if (!SQL_IS_LINK_UP()) return false;
292 return mysql_insert_id();
295 // Escape a string for the database
296 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
298 if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
299 // Secure string first? (which is the default behaviour!)
300 if ($secureString === true) {
302 $str = secureString($str, $strip);
305 if (!SQL_IS_LINK_UP()) {
306 // Fall-back to escapeQuotes() when there is no link
307 $ret = escapeQuotes($str);
308 } elseif (function_exists('mysql_real_escape_string')) {
309 // The new and improved version
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, $enableCodes = true) {
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]);
381 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
383 // Shall we add/drop?
384 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false) || (strpos($sql, 'CHANGE') !== false)) && ($noIndex === true)) {
385 // Try two columns, one should fix
386 foreach (array(4,5) as $idx) {
387 // If an entry is not set, abort here
388 if (!isset($tableArray[$idx])) {
390 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
394 // And column name as well
395 $columnName = $tableArray[$idx];
398 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(isSqlTableColumnFound($tableName, $columnName)));
400 // Do we have no entry on ADD or an entry on DROP/CHANGE?
401 // 123 4 43 3 4 4 32 23 4 43 3 4 4 32 23 4 43 3 4 4 3 3 3 3 4 4321
402 if (((!isSqlTableColumnFound($tableName, $columnName)) && (strpos($sql, 'ADD') !== false)) || ((isSqlTableColumnFound($tableName, $columnName)) && (strpos($sql, 'DROP') !== false)) || ((isSqlTableColumnFound($tableName, $columnName)) && (strpos($sql, 'CHANGE') !== false) && ($idx == 4) && (!isSqlTableColumnFound($tableName, $tableArray[5])))) {
404 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
405 $result = SQL_QUERY($sql, $F, $L, false);
407 // Skip further attempt(s)
409 // 1234 5 54 4 5 5 43 34 5 54 4 5 5 43 3 4 4 32 2 21
410 } elseif ((((isSqlTableColumnFound($tableName, $columnName)) && (strpos($sql, 'ADD') !== false)) || ((isSqlTableColumnFound($tableName, $columnName)) && (strpos($sql, 'DROP') !== false)) || (strpos($sql, 'CHANGE') !== false)) && ($columnName != 'KEY')) {
411 // Abort here because it is alreay there
412 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
414 } elseif ((!isSqlTableColumnFound($tableName, $columnName)) && (strpos($sql, 'DROP') !== false)) {
415 // Abort here because we tried to drop a column which is not there (never created maybe)
416 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
418 } elseif ($columnName != 'KEY') {
419 // Something didn't fit, we better log it
420 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(isSqlTableColumnFound($tableName, $columnName)) . '');
423 } elseif ((getTableType() == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
424 // Skip this query silently because InnoDB does not understand fulltext indexes
425 //* 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));
426 } elseif ($noIndex === false) {
427 // And column name as well without backticks
428 $keyName = str_replace('`', '', $tableArray[5]);
429 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
431 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
432 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
436 while (strpos($keyName, ',') !== false) {
438 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
439 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
442 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
443 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
451 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
452 if ((!isSqlTableIndexAdded($tableName, $tableArray[3], $keyName)) && ($tableArray[3] == 'ADD')) {
453 // Send it to the SQL_QUERY() function to add it
454 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
455 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
456 } elseif ((isSqlTableIndexAdded($tableName, $tableArray[3], $keyName)) && ($tableArray[3] == 'DROP')) {
457 // Send it to the SQL_QUERY() function to drop it
458 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
459 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
462 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
465 // Other ALTER TABLE query
466 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
467 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
474 // Getter for SQL link
475 function SQL_GET_LINK () {
479 // Is it in the globals?
480 if (isset($GLOBALS['sql_link'])) {
482 $link = $GLOBALS['sql_link'];
490 function SQL_SET_LINK ($link) {
491 // Is this a resource or null?
492 if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
493 // This may happen in installation phase
495 } elseif ((!is_resource($link)) && (!is_null($link))) {
496 // This should never happen!
497 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Type of link is not resource or null, type=%s", gettype($link)));
501 $GLOBALS['sql_link'] = $link;
504 $GLOBALS['is_sql_link_up'] = is_resource($link);
507 // Checks if the link is up
508 function SQL_IS_LINK_UP () {
512 // Do we have cached this?
513 if (isset($GLOBALS['is_sql_link_up'])) {
515 $linkUp = $GLOBALS['is_sql_link_up'];
518 $linkUp = is_resource(SQL_GET_LINK());
521 $GLOBALS['is_sql_link_up'] = $linkUp;
528 // Wrapper function to make code more readable
529 function SQL_HASZERONUMS ($result) {
530 // Just pass it through
531 return (SQL_NUMROWS($result) === 0);
534 // Wrapper function to make code more readable
535 function SQL_HASZEROAFFECTED () {
536 // Just pass it through
537 return (SQL_AFFECTEDROWS() === 0);
540 // Private function to prepare the SQL query string
541 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
542 // Is it already cached?
543 if (!isset($GLOBALS['sql_strings'][$sqlString])) {
544 // Compile config+expression code
545 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
547 // Do final compilation
548 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
549 //die($sqlString.'<br />'.$sqlString2.'<br />'.$GLOBALS['sql_strings'][$sqlString]);
553 return $GLOBALS['sql_strings'][$sqlString];
556 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
557 function SQL_EPOCHE_TO_TIMESTAMP ($timestamp) {
558 return generateDateTime($timestamp, 7);
561 // Check if there is a SQL table created
562 function isSqlTableCreated ($tableName) {
564 if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
565 // Check if the table is there
566 $result = SQL_QUERY_ESC("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
567 array($tableName), __FILE__, __LINE__);
569 // Is there an entry?
570 $GLOBALS[__FUNCTION__][$tableName] = (SQL_NUMROWS($result) == 1);
571 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
575 return $GLOBALS[__FUNCTION__][$tableName];
578 // Is a table column there?
579 function isSqlTableColumnFound ($tableName, $columnName) {
581 if (!isset($GLOBALS[__FUNCTION__][$tableName][$columnName])) {
582 // And column name as well
583 $columnName = str_replace('`', '', $columnName);
585 // Get column information
586 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
587 array($tableName, $columnName), __FUNCTION__, __LINE__);
590 $GLOBALS[__FUNCTION__][$tableName][$columnName] = (!SQL_HASZERONUMS($result));
591 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)) . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]));
594 SQL_FREERESULT($result);
598 return $GLOBALS[__FUNCTION__][$tableName][$columnName];
601 // Checks depending on the mode if the table is there
602 function isSqlTableIndexAdded ($tableName, $mode, $keyName) {
604 if (!isset($GLOBALS[__FUNCTION__][$tableName][$mode])) {
606 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
608 // Non-skipping is default for ADD
609 $GLOBALS[__FUNCTION__][$tableName][$mode] = false;
611 // But should we DROP?
612 if ($mode == 'DROP') {
613 // Then skip if nothing found
614 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
615 $GLOBALS[__FUNCTION__][$tableName][$mode] = true;
619 while ($content = SQL_FETCHARRAY($result)) {
621 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
622 if (($content['Key_name'] == $keyName) && ($mode == 'ADD')) {
624 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
625 $GLOBALS[__FUNCTION__][$tableName][$mode] = true;
627 } elseif (($content['Key_name'] == $keyName) && ($mode == 'DROP')) {
629 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
630 $GLOBALS[__FUNCTION__][$tableName][$mode] = false;
636 SQL_FREERESULT($result);
640 return $GLOBALS[__FUNCTION__][$tableName][$mode];