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 * -------------------------------------------------------------------- *
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 version I have heard
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: */ debugOutput('F=' . basename($F) . ',L=' . $L . 'sql=' . encodeEntities($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());
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())) {
104 // Debugging stuff...
106 $fp = fopen(getCachePath() . 'mysql.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write mysql.log!');
107 if (!isset($GLOBALS['sql_first_entry'])) {
109 fwrite($fp, 'Module=' . getModule() . "\n");
110 $GLOBALS['sql_first_entry'] = true;
112 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $GLOBALS['last_sql'])) . "\n");
117 if (!isStatsEntrySet('db_hits')) {
118 // Count in dummy variable
119 setStatsEntry('db_hits', 1);
121 // Count to config array
122 incrementStatsEntry('db_hits');
130 function SQL_NUMROWS ($resource) {
131 // Valid link resource?
132 if (!SQL_IS_LINK_UP()) return false;
134 // Link is not up, no rows by default
137 // Is the result a valid resource?
138 if (isset($GLOBALS['sql_numrows'][$resource])) {
140 $lines = $GLOBALS['sql_numrows'][intval($resource)];
141 } elseif (is_resource($resource)) {
142 // Get the count of rows from database
143 $lines = mysql_num_rows($resource);
145 // Remember it in cache
146 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
148 // No resource given, please fix this
149 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
157 function SQL_AFFECTEDROWS() {
158 // Valid link resource?
159 if (!SQL_IS_LINK_UP()) return false;
162 $lines = mysql_affected_rows(SQL_GET_LINK());
169 function SQL_FETCHROW ($resource) {
170 // Is a result resource set?
171 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
173 // Fetch the data and return it
174 return mysql_fetch_row($resource);
178 function SQL_FETCHARRAY ($res) {
179 // Is a result resource set?
180 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
182 // Load row from database
183 $row = mysql_fetch_assoc($res);
185 // Return only arrays here
186 if (is_array($row)) {
190 // Return a false, else some loops would go endless...
196 function SQL_RESULT ($resource, $row, $field = '0') {
197 // Is $resource valid?
198 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
200 // Run the result command
201 $result = mysql_result($resource, $row, $field);
203 // ... and return the result
208 function SQL_CONNECT ($host, $login, $password, $F, $L) {
210 $linkResource = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
212 // Set the link resource
213 SQL_SET_LINK($linkResource);
216 unset($GLOBALS['is_sql_link_up']);
219 // SQL select database
220 function SQL_SELECT_DB ($dbName, $F, $L) {
221 // Is there still a valid link? If not, skip it.
222 if (!SQL_IS_LINK_UP()) return false;
225 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
229 function SQL_CLOSE ($F, $L) {
230 if (!SQL_IS_LINK_UP()) {
235 // Close database link and forget the link
236 $close = mysql_close(SQL_GET_LINK())
237 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
243 unset($GLOBALS['is_sql_link_up']);
250 function SQL_FREERESULT ($resource) {
251 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
257 $res = mysql_free_result($resource);
259 // And return that result of freeing it...
263 // SQL string escaping
264 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
266 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
269 $dataSecured['__sql_string'] = $sqlString;
270 foreach ($data as $key => $value) {
271 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
275 $query = call_user_func_array('sprintf', $dataSecured);
279 //* DEBUG: */ $fp = fopen(getCachePath() . 'escape_debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write debug.log!');
280 //* DEBUG: */ fwrite($fp, $F . '(' . $L . '): ' . str_replace("\r", '', str_replace("\n", ' ', $eval)) . "\n");
281 //* DEBUG: */ fclose($fp);
284 // Run SQL query (default)
285 return SQL_QUERY($query, $F, $L);
287 // Return secured string
292 // Get id from last INSERT command
293 function SQL_INSERTID () {
294 if (!SQL_IS_LINK_UP()) return false;
295 return mysql_insert_id();
298 // Escape a string for the database
299 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
301 if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
302 // Secure string first? (which is the default behaviour!)
303 if ($secureString === true) {
305 $str = secureString($str, $strip);
308 if (!SQL_IS_LINK_UP()) {
309 // Fall-back to escapeQuotes() when there is no link
310 $ret = escapeQuotes($str);
311 } elseif (function_exists('mysql_real_escape_string')) {
312 // The new and improved version
313 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
314 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
315 } elseif (function_exists('mysql_escape_string')) {
316 // The obsolete function
317 $ret = mysql_escape_string($str, SQL_GET_LINK());
319 // If nothing else works, fall back to escapeQuotes() again
320 $ret = escapeQuotes($str);
324 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
328 return $GLOBALS['sql_escapes'][''.$str.''];
331 // SELECT query string from table, columns and so on... ;-)
332 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
333 // Is columns an array?
334 if (!is_array($columns)) {
336 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
342 // Abort here with 'false'
346 // Prepare the SQL statement
347 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
350 return SQL_QUERY_ESC($sql,
359 // ALTER TABLE wrapper function
360 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = true) {
361 // Abort if link is down
362 if (!SQL_IS_LINK_UP()) return false;
364 // This is the default result...
367 // Determine index/fulltext/unique word
370 strpos($sql, 'INDEX') === false
372 strpos($sql, 'KEY') === false
374 strpos($sql, 'FULLTEXT') === false
376 strpos($sql, 'UNIQUE') === false
380 // Extract table name
381 $tableArray = explode(' ', $sql);
382 $tableName = str_replace('`', '', $tableArray[2]);
384 // Shall we add/drop?
385 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
386 // Try two columns, one should fix
387 foreach (array(4,5) as $idx) {
388 // And column name as well
389 $columnName = str_replace('`', '', $tableArray[$idx]);
391 // Get column information
392 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
393 array($tableName, $columnName), __FUNCTION__, __LINE__);
395 // Do we have no entry on ADD or an entry on DROP?
396 // 123 4 4 3 3 4 4 32 23 4 4 3 3 4 4 321
397 if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
399 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
400 $result = SQL_QUERY($sql, $F, $L, false);
402 // Skip further attempt(s)
404 } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
405 // Abort here because it is alreay there
406 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
408 } elseif ($columnName != 'KEY') {
409 // Something didn't fit
410 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
413 } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
414 // Skip this query silently
415 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
416 } elseif ($noIndex === false) {
417 // And column name as well
418 //* DEBUG: */ debugOutput(__LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
419 $keyName = str_replace('`', '', $tableArray[5]);
421 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
422 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
424 $begin = 1; $keyName = ',';
425 while (strpos($keyName, ',') !== false) {
427 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
428 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
431 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
432 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
440 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
442 // Non-skipping is default for ADD
445 // But should we DROP?
446 if ($tableArray[3] == 'DROP') {
447 // Then skip if nothing found!
449 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
453 while ($content = SQL_FETCHARRAY($result)) {
455 //* DEBUG: */ debugOutput(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
456 if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
458 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
461 } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
463 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
470 SQL_FREERESULT($result);
473 if ($skip === false) {
474 // Send it to the SQL_QUERY() function
475 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
476 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
479 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
482 // Other ALTER TABLE query
483 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
484 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
491 // Getter for SQL link
492 function SQL_GET_LINK () {
496 // Is it in the globals?
497 if (isset($GLOBALS['sql_link'])) {
499 $link = $GLOBALS['sql_link'];
507 function SQL_SET_LINK ($link) {
508 // Is this a resource or null?
509 if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
510 // This may happen in installation phase
512 } elseif ((!is_resource($link)) && (!is_null($link))) {
513 // This should never happen!
514 debug_report_bug(__FUNCTION__, __LINE__, sprintf("link is not resource or null. Type: %s", gettype($link)));
518 $GLOBALS['sql_link'] = $link;
521 // Checks if the link is up
522 function SQL_IS_LINK_UP () {
526 // Do we have cached this?
527 if (isset($GLOBALS['is_sql_link_up'])) {
529 $linkUp = $GLOBALS['is_sql_link_up'];
532 $linkUp = is_resource(SQL_GET_LINK());
535 $GLOBALS['is_sql_link_up'] = $linkUp;
542 // Wrapper function to make code more readable
543 function SQL_HASZERONUMS ($result) {
544 // Just pass it through
545 return (SQL_NUMROWS($result) === 0);
548 // Private function to prepare the SQL query string
549 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
550 // Is it already cached?
551 if (!isset($GLOBALS['sql_strings'][$sqlString])) {
552 // Compile config+expression code
553 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
555 // Do final compilation
556 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
557 //die($sqlString.'<br />'.$sqlString2.'<br />'.$GLOBALS['sql_strings'][$sqlString]);
561 return $GLOBALS['sql_strings'][$sqlString];