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, 2010 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])) {
48 $sqlStringModified = trim($sqlString);
50 // Empty query string or link is not up?
51 if (empty($sqlStringModified)) {
53 debug_report_bug(__FUNCTION__, __LINE__, sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
57 } elseif (!SQL_IS_LINK_UP()) {
58 // We should not quietly ignore this
59 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
66 // Remove \t, \n and \r from queries they may confuse some MySQL versions
67 $sqlStringModified = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlStringModified)));
69 // Compile config entries out
70 $sqlStringModified = SQL_PREPARE_SQL_STRING($sqlStringModified, $enableCodes);
72 // Cache it and remember as last SQL query
73 $GLOBALS[__FUNCTION__][$sqlString] = $sqlStringModified;
74 $GLOBALS['last_sql'] = $sqlStringModified;
76 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used!');
78 // Use cache (to save a lot function calls
79 $sqlString = $GLOBALS[__FUNCTION__][$sqlString];
83 $querytimeBefore = microtime(true);
86 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
87 $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
88 or debug_report_bug($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . "\n".
89 'Query string:' . $GLOBALS['last_sql']);
90 //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
92 // Calculate query time
93 $queryTime = microtime(true) - $querytimeBefore;
95 // Add this query to array including timing
96 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
98 // Save last successfull query
99 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
101 // Count all query times
102 incrementConfigEntry('sql_time', $queryTime);
105 incrementConfigEntry('sql_count');
108 if ((!isCssOutputMode()) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
109 // Is this the first call?
110 if (!isset($GLOBALS['sql_first_entry'])) {
112 appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
113 $GLOBALS['sql_first_entry'] = true;
117 appendLineToFile(getCachePath() . 'mysql.log', $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $GLOBALS['last_sql'])));
121 if (!isStatsEntrySet('db_hits')) {
122 // Count in dummy variable
123 setStatsEntry('db_hits', 1);
125 // Count to config array
126 incrementStatsEntry('db_hits');
134 function SQL_NUMROWS ($resource) {
135 // Valid link resource?
136 if (!SQL_IS_LINK_UP()) return false;
138 // Link is not up, no rows by default
141 // Is the result a valid resource?
142 if (isset($GLOBALS['sql_numrows'][$resource])) {
144 $lines = $GLOBALS['sql_numrows'][intval($resource)];
145 } elseif (is_resource($resource)) {
146 // Get the count of rows from database
147 $lines = mysql_num_rows($resource);
149 // Remember it in cache
150 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
152 // No resource given, please fix this
153 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
161 function SQL_AFFECTEDROWS() {
162 // Valid link resource?
163 if (!SQL_IS_LINK_UP()) return false;
166 $lines = mysql_affected_rows(SQL_GET_LINK());
173 function SQL_FETCHROW ($resource) {
174 // Is a result resource set?
175 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
177 // Fetch the data and return it
178 return mysql_fetch_row($resource);
182 function SQL_FETCHARRAY ($res) {
183 // Is a result resource set?
184 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
186 // Load row from database
187 $row = mysql_fetch_assoc($res);
189 // Return only arrays here
190 if (is_array($row)) {
194 // Return a false, else some loops would go endless...
200 function SQL_RESULT ($resource, $row, $field = '0') {
201 // Is $resource valid?
202 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
204 // Run the result command
205 $result = mysql_result($resource, $row, $field);
207 // ... and return the result
212 function SQL_CONNECT ($host, $login, $password, $F, $L) {
214 $linkResource = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
216 // Set the link resource
217 SQL_SET_LINK($linkResource);
220 unset($GLOBALS['is_sql_link_up']);
223 // SQL select database
224 function SQL_SELECT_DB ($dbName, $F, $L) {
225 // Is there still a valid link? If not, skip it.
226 if (!SQL_IS_LINK_UP()) return false;
229 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
233 function SQL_CLOSE ($F, $L) {
234 if (!SQL_IS_LINK_UP()) {
239 // Close database link and forget the link
240 $close = mysql_close(SQL_GET_LINK())
241 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
247 unset($GLOBALS['is_sql_link_up']);
254 function SQL_FREERESULT ($resource) {
255 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
261 $res = mysql_free_result($resource);
263 // And return that result of freeing it...
267 // SQL string escaping
268 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
270 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
273 $dataSecured['__sql_string'] = $sqlString;
274 foreach ($data as $key => $value) {
275 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
279 $query = call_user_func_array('sprintf', $dataSecured);
282 // Run SQL query (default)
283 return SQL_QUERY($query, $F, $L);
285 // Return secured string
290 // Get id from last INSERT command
291 function SQL_INSERTID () {
292 if (!SQL_IS_LINK_UP()) return false;
293 return mysql_insert_id();
296 // Escape a string for the database
297 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
299 if (!isset($GLOBALS['sql_escapes'][''.$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 // Prepare the SQL statement
344 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
347 return SQL_QUERY_ESC($sql,
356 // ALTER TABLE wrapper function
357 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = true) {
358 // Abort if link is down
359 if (!SQL_IS_LINK_UP()) return false;
361 // This is the default result...
364 // Determine index/fulltext/unique word
367 strpos($sql, 'INDEX') === false
369 strpos($sql, 'KEY') === false
371 strpos($sql, 'FULLTEXT') === false
373 strpos($sql, 'UNIQUE') === false
377 // Extract table name
378 $tableArray = explode(' ', $sql);
379 $tableName = str_replace('`', '', $tableArray[2]);
382 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName);
384 // Shall we add/drop?
385 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false) || (strpos($sql, 'CHANGE') !== false)) && ($noIndex === true)) {
386 // Try two columns, one should fix
387 foreach (array(4,5) as $idx) {
388 // If an entry is not set, abort here
389 if (!isset($tableArray[$idx])) {
391 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
395 // And column name as well
396 $columnName = str_replace('`', '', $tableArray[$idx]);
398 // Get column information
399 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
400 array($tableName, $columnName), __FUNCTION__, __LINE__);
403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)));
405 // Do we have no entry on ADD or an entry on DROP/CHANGE?
406 // 123 4 43 3 4 4 32 23 4 4 3 3 4 4 32 23 4 43 3 4 4 3 3 321
407 if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'CHANGE') !== false) && ($idx == 4))) {
409 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
410 $result = SQL_QUERY($sql, $F, $L, false);
412 // Skip further attempt(s)
414 // 1234 5 54 4 5 5 43 34 5 54 4 5 5 43 3 4 4 32 2 21
415 } elseif ((((!SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) || (strpos($sql, 'CHANGE') !== false)) && ($columnName != 'KEY')) {
416 // Abort here because it is alreay there
417 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
419 } elseif ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) {
420 // Abort here because we tried to drop a column which is not there (never created maybe)
421 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
423 } elseif ($columnName != 'KEY') {
424 // Something didn't fit, we better log it
425 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)) . '');
428 } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
429 // Skip this query silently
430 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s", $sql, $tableName, intval((is_bool($result)) ? 0 : SQL_HASZERONUMS($result)), $F, $L));
431 } elseif ($noIndex === false) {
432 // And column name as well
433 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
434 $keyName = str_replace('`', '', $tableArray[5]);
436 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
437 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
439 $begin = 1; $keyName = ',';
440 while (strpos($keyName, ',') !== false) {
442 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
443 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
446 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
447 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
455 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
457 // Non-skipping is default for ADD
460 // But should we DROP?
461 if ($tableArray[3] == 'DROP') {
462 // Then skip if nothing found!
464 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
468 while ($content = SQL_FETCHARRAY($result)) {
470 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
471 if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
473 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
476 } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
478 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
485 SQL_FREERESULT($result);
488 if ($skip === false) {
489 // Send it to the SQL_QUERY() function
490 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
491 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
494 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
497 // Other ALTER TABLE query
498 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
499 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
506 // Getter for SQL link
507 function SQL_GET_LINK () {
511 // Is it in the globals?
512 if (isset($GLOBALS['sql_link'])) {
514 $link = $GLOBALS['sql_link'];
522 function SQL_SET_LINK ($link) {
523 // Is this a resource or null?
524 if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
525 // This may happen in installation phase
527 } elseif ((!is_resource($link)) && (!is_null($link))) {
528 // This should never happen!
529 debug_report_bug(__FUNCTION__, __LINE__, sprintf("link is not resource or null. Type: %s", gettype($link)));
533 $GLOBALS['sql_link'] = $link;
536 // Checks if the link is up
537 function SQL_IS_LINK_UP () {
541 // Do we have cached this?
542 if (isset($GLOBALS['is_sql_link_up'])) {
544 $linkUp = $GLOBALS['is_sql_link_up'];
547 $linkUp = is_resource(SQL_GET_LINK());
550 $GLOBALS['is_sql_link_up'] = $linkUp;
557 // Wrapper function to make code more readable
558 function SQL_HASZERONUMS ($result) {
559 // Just pass it through
560 return (SQL_NUMROWS($result) === 0);
563 // Wrapper function to make code more readable
564 function SQL_HASZEROAFFECTED () {
565 // Just pass it through
566 return (SQL_AFFECTEDROWS() === 0);
569 // Private function to prepare the SQL query string
570 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
571 // Is it already cached?
572 if (!isset($GLOBALS['sql_strings'][$sqlString])) {
573 // Compile config+expression code
574 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
576 // Do final compilation
577 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
578 //die($sqlString.'<br />'.$sqlString2.'<br />'.$GLOBALS['sql_strings'][$sqlString]);
582 return $GLOBALS['sql_strings'][$sqlString];