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 $sqlString = trim($sqlString);
49 if (!SQL_IS_LINK_UP()) {
50 // We should not quietly ignore this!
51 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
57 // Return 'false' because it has failed
59 } elseif (empty($sqlString)) {
61 debug_report_bug(__FUNCTION__, __LINE__, sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
66 // This is invalid, of course
70 // Remove \t, \n and \r from queries they may confuse some MySQL versions
71 $sqlString = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlString)));
73 // Compile config entries out
74 $GLOBALS['last_sql'] = SQL_PREPARE_SQL_STRING($sqlString, $enableCodes);
77 $querytimeBefore = microtime(true);
80 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
81 $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
82 or debug_report_bug($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . "\n".
83 'Query string:' . $GLOBALS['last_sql']);
84 //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
86 // Calculate query time
87 $queryTime = microtime(true) - $querytimeBefore;
89 // Add this query to array including timing
90 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
92 // Save last successfull query
93 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
95 // Count all query times
96 incrementConfigEntry('sql_time', $queryTime);
99 incrementConfigEntry('sql_count');
102 if ((!isCssOutputMode()) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
103 // Is this the first call?
104 if (!isset($GLOBALS['sql_first_entry'])) {
106 appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
107 $GLOBALS['sql_first_entry'] = true;
111 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'])));
115 if (!isStatsEntrySet('db_hits')) {
116 // Count in dummy variable
117 setStatsEntry('db_hits', 1);
119 // Count to config array
120 incrementStatsEntry('db_hits');
128 function SQL_NUMROWS ($resource) {
129 // Valid link resource?
130 if (!SQL_IS_LINK_UP()) return false;
132 // Link is not up, no rows by default
135 // Is the result a valid resource?
136 if (isset($GLOBALS['sql_numrows'][$resource])) {
138 $lines = $GLOBALS['sql_numrows'][intval($resource)];
139 } elseif (is_resource($resource)) {
140 // Get the count of rows from database
141 $lines = mysql_num_rows($resource);
143 // Remember it in cache
144 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
146 // No resource given, please fix this
147 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
155 function SQL_AFFECTEDROWS() {
156 // Valid link resource?
157 if (!SQL_IS_LINK_UP()) return false;
160 $lines = mysql_affected_rows(SQL_GET_LINK());
167 function SQL_FETCHROW ($resource) {
168 // Is a result resource set?
169 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
171 // Fetch the data and return it
172 return mysql_fetch_row($resource);
176 function SQL_FETCHARRAY ($res) {
177 // Is a result resource set?
178 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
180 // Load row from database
181 $row = mysql_fetch_assoc($res);
183 // Return only arrays here
184 if (is_array($row)) {
188 // Return a false, else some loops would go endless...
194 function SQL_RESULT ($resource, $row, $field = '0') {
195 // Is $resource valid?
196 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
198 // Run the result command
199 $result = mysql_result($resource, $row, $field);
201 // ... and return the result
206 function SQL_CONNECT ($host, $login, $password, $F, $L) {
208 $linkResource = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
210 // Set the link resource
211 SQL_SET_LINK($linkResource);
214 unset($GLOBALS['is_sql_link_up']);
217 // SQL select database
218 function SQL_SELECT_DB ($dbName, $F, $L) {
219 // Is there still a valid link? If not, skip it.
220 if (!SQL_IS_LINK_UP()) return false;
223 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
227 function SQL_CLOSE ($F, $L) {
228 if (!SQL_IS_LINK_UP()) {
233 // Close database link and forget the link
234 $close = mysql_close(SQL_GET_LINK())
235 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
241 unset($GLOBALS['is_sql_link_up']);
248 function SQL_FREERESULT ($resource) {
249 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
255 $res = mysql_free_result($resource);
257 // And return that result of freeing it...
261 // SQL string escaping
262 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
264 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
267 $dataSecured['__sql_string'] = $sqlString;
268 foreach ($data as $key => $value) {
269 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
273 $query = call_user_func_array('sprintf', $dataSecured);
276 // Run SQL query (default)
277 return SQL_QUERY($query, $F, $L);
279 // Return secured string
284 // Get id from last INSERT command
285 function SQL_INSERTID () {
286 if (!SQL_IS_LINK_UP()) return false;
287 return mysql_insert_id();
290 // Escape a string for the database
291 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
293 if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
294 // Secure string first? (which is the default behaviour!)
295 if ($secureString === true) {
297 $str = secureString($str, $strip);
300 if (!SQL_IS_LINK_UP()) {
301 // Fall-back to escapeQuotes() when there is no link
302 $ret = escapeQuotes($str);
303 } elseif (function_exists('mysql_real_escape_string')) {
304 // The new and improved version
305 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
306 } elseif (function_exists('mysql_escape_string')) {
307 // The obsolete function
308 $ret = mysql_escape_string($str, SQL_GET_LINK());
310 // If nothing else works, fall back to escapeQuotes() again
311 $ret = escapeQuotes($str);
315 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
319 return $GLOBALS['sql_escapes'][''.$str.''];
322 // SELECT query string from table, columns and so on... ;-)
323 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
324 // Is columns an array?
325 if (!is_array($columns)) {
327 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
333 // Abort here with 'false'
337 // Prepare the SQL statement
338 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
341 return SQL_QUERY_ESC($sql,
350 // ALTER TABLE wrapper function
351 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = true) {
352 // Abort if link is down
353 if (!SQL_IS_LINK_UP()) return false;
355 // This is the default result...
358 // Determine index/fulltext/unique word
361 strpos($sql, 'INDEX') === false
363 strpos($sql, 'KEY') === false
365 strpos($sql, 'FULLTEXT') === false
367 strpos($sql, 'UNIQUE') === false
371 // Extract table name
372 $tableArray = explode(' ', $sql);
373 $tableName = str_replace('`', '', $tableArray[2]);
376 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName);
378 // Shall we add/drop?
379 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false) || (strpos($sql, 'CHANGE') !== false)) && ($noIndex === true)) {
380 // Try two columns, one should fix
381 foreach (array(4,5) as $idx) {
382 // If an entry is not set, abort here
383 if (!isset($tableArray[$idx])) {
385 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
389 // And column name as well
390 $columnName = str_replace('`', '', $tableArray[$idx]);
392 // Get column information
393 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
394 array($tableName, $columnName), __FUNCTION__, __LINE__);
397 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)));
399 // Do we have no entry on ADD or an entry on DROP/CHANGE?
400 // 123 4 43 3 4 4 32 23 4 4 3 3 4 4 32 23 4 43 3 4 4 3 3 321
401 if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'CHANGE') !== false) && ($idx == 4))) {
403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
404 $result = SQL_QUERY($sql, $F, $L, false);
406 // Skip further attempt(s)
408 // 1234 5 54 4 5 5 43 34 5 54 4 5 5 43 3 4 4 32 2 21
409 } elseif ((((!SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) || (strpos($sql, 'CHANGE') !== false)) && ($columnName != 'KEY')) {
410 // Abort here because it is alreay there
411 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
413 } elseif ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) {
414 // Abort here because we tried to drop a column which is not there (never created maybe)
415 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
417 } elseif ($columnName != 'KEY') {
418 // Something didn't fit, we better log it
419 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)) . '');
422 } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
423 // Skip this query silently
424 //* 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));
425 } elseif ($noIndex === false) {
426 // And column name as well
427 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
428 $keyName = str_replace('`', '', $tableArray[5]);
430 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
431 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
433 $begin = 1; $keyName = ',';
434 while (strpos($keyName, ',') !== false) {
436 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
437 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
440 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
441 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
449 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
451 // Non-skipping is default for ADD
454 // But should we DROP?
455 if ($tableArray[3] == 'DROP') {
456 // Then skip if nothing found!
458 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
462 while ($content = SQL_FETCHARRAY($result)) {
464 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
465 if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
470 } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
472 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
479 SQL_FREERESULT($result);
482 if ($skip === false) {
483 // Send it to the SQL_QUERY() function
484 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
485 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
488 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
491 // Other ALTER TABLE query
492 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
493 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
500 // Getter for SQL link
501 function SQL_GET_LINK () {
505 // Is it in the globals?
506 if (isset($GLOBALS['sql_link'])) {
508 $link = $GLOBALS['sql_link'];
516 function SQL_SET_LINK ($link) {
517 // Is this a resource or null?
518 if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
519 // This may happen in installation phase
521 } elseif ((!is_resource($link)) && (!is_null($link))) {
522 // This should never happen!
523 debug_report_bug(__FUNCTION__, __LINE__, sprintf("link is not resource or null. Type: %s", gettype($link)));
527 $GLOBALS['sql_link'] = $link;
530 // Checks if the link is up
531 function SQL_IS_LINK_UP () {
535 // Do we have cached this?
536 if (isset($GLOBALS['is_sql_link_up'])) {
538 $linkUp = $GLOBALS['is_sql_link_up'];
541 $linkUp = is_resource(SQL_GET_LINK());
544 $GLOBALS['is_sql_link_up'] = $linkUp;
551 // Wrapper function to make code more readable
552 function SQL_HASZERONUMS ($result) {
553 // Just pass it through
554 return (SQL_NUMROWS($result) === 0);
557 // Wrapper function to make code more readable
558 function SQL_HASZEROAFFECTED () {
559 // Just pass it through
560 return (SQL_AFFECTEDROWS() === 0);
563 // Private function to prepare the SQL query string
564 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
565 // Is it already cached?
566 if (!isset($GLOBALS['sql_strings'][$sqlString])) {
567 // Compile config+expression code
568 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
570 // Do final compilation
571 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
572 //die($sqlString.'<br />'.$sqlString2.'<br />'.$GLOBALS['sql_strings'][$sqlString]);
576 return $GLOBALS['sql_strings'][$sqlString];