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 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
46 function SQL_QUERY ($sqlString, $F, $L, $enableCodes = true) {
48 $sqlString = trim($sqlString);
51 if (!SQL_IS_LINK_UP()) {
52 // We should not quietly ignore this!
53 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
59 // Return 'false' because it has failed
61 } elseif (empty($sqlString)) {
63 debug_report_bug(__FUNCTION__, __LINE__, sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
68 // This is invalid, of course
72 // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
73 $sqlString = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlString)));
75 // Compile config entries out
76 $GLOBALS['last_sql'] = SQL_PREPARE_SQL_STRING($sqlString, $enableCodes);
79 $querytimeBefore = microtime(true);
82 //* DEBUG: */ debugOutput('F=' . basename($F) . ',L=' . $L . 'sql=' . encodeEntities($GLOBALS['last_sql']));
83 $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
84 or debug_report_bug($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . "\n".
85 'Query string:' . $GLOBALS['last_sql']);
86 //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS());
88 // Calculate query time
89 $queryTime = microtime(true) - $querytimeBefore;
91 // Add this query to array including timing
92 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
94 // Save last successfull query
95 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
97 // Count all query times
98 incrementConfigEntry('sql_time', $queryTime);
101 incrementConfigEntry('sql_count');
104 if ((!isCssOutputMode()) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
106 // Debugging stuff...
108 $fp = fopen(getCachePath() . 'mysql.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write mysql.log!');
109 if (!isset($GLOBALS['sql_first_entry'])) {
111 fwrite($fp, 'Module=' . getModule() . "\n");
112 $GLOBALS['sql_first_entry'] = true;
114 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $GLOBALS['last_sql'])) . "\n");
119 if (!isStatsEntrySet('db_hits')) {
120 // Count in dummy variable
121 setStatsEntry('db_hits', 1);
123 // Count to config array
124 incrementStatsEntry('db_hits');
132 function SQL_NUMROWS ($resource) {
133 // Valid link resource?
134 if (!SQL_IS_LINK_UP()) return false;
136 // Link is not up, no rows by default
139 // Is the result a valid resource?
140 if (isset($GLOBALS['sql_numrows'][$resource])) {
142 $lines = $GLOBALS['sql_numrows'][intval($resource)];
143 } elseif (is_resource($resource)) {
144 // Get the count of rows from database
145 $lines = mysql_num_rows($resource);
147 // Remember it in cache
148 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
150 // No resource given, please fix this
151 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
159 function SQL_AFFECTEDROWS() {
160 // Valid link resource?
161 if (!SQL_IS_LINK_UP()) return false;
164 $lines = mysql_affected_rows(SQL_GET_LINK());
171 function SQL_FETCHROW ($resource) {
172 // Is a result resource set?
173 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
175 // Fetch the data and return it
176 return mysql_fetch_row($resource);
180 function SQL_FETCHARRAY ($res) {
181 // Is a result resource set?
182 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
184 // Load row from database
185 $row = mysql_fetch_assoc($res);
187 // Return only arrays here
188 if (is_array($row)) {
192 // Return a false, else some loops would go endless...
198 function SQL_RESULT ($resource, $row, $field = '0') {
199 // Is $resource valid?
200 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
202 // Run the result command
203 $result = mysql_result($resource, $row, $field);
205 // ... and return the result
210 function SQL_CONNECT ($host, $login, $password, $F, $L) {
212 $linkResource = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
214 // Set the link resource
215 SQL_SET_LINK($linkResource);
218 unset($GLOBALS['is_sql_link_up']);
221 // SQL select database
222 function SQL_SELECT_DB ($dbName, $F, $L) {
223 // Is there still a valid link? If not, skip it.
224 if (!SQL_IS_LINK_UP()) return false;
227 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
231 function SQL_CLOSE ($F, $L) {
232 if (!SQL_IS_LINK_UP()) {
237 // Close database link and forget the link
238 $close = mysql_close(SQL_GET_LINK())
239 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
245 unset($GLOBALS['is_sql_link_up']);
252 function SQL_FREERESULT ($resource) {
253 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
259 $res = mysql_free_result($resource);
261 // And return that result of freeing it...
265 // SQL string escaping
266 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
268 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
271 $dataSecured['__sql_string'] = $sqlString;
272 foreach ($data as $key => $value) {
273 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
277 $query = call_user_func_array('sprintf', $dataSecured);
281 //* DEBUG: */ $fp = fopen(getCachePath() . 'escape_debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write debug.log!');
282 //* DEBUG: */ fwrite($fp, $F . '(' . $L . '): ' . str_replace("\r", '', str_replace("\n", ' ', $eval)) . "\n");
283 //* DEBUG: */ fclose($fp);
286 // Run SQL query (default)
287 return SQL_QUERY($query, $F, $L);
289 // Return secured string
294 // Get id from last INSERT command
295 function SQL_INSERTID () {
296 if (!SQL_IS_LINK_UP()) return false;
297 return mysql_insert_id();
300 // Escape a string for the database
301 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
303 if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
304 // Secure string first? (which is the default behaviour!)
305 if ($secureString === true) {
307 $str = secureString($str, $strip);
310 if (!SQL_IS_LINK_UP()) {
311 // Fall-back to escapeQuotes() when there is no link
312 $ret = escapeQuotes($str);
313 } elseif (function_exists('mysql_real_escape_string')) {
314 // The new and improved version
315 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
316 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
317 } elseif (function_exists('mysql_escape_string')) {
318 // The obsolete function
319 $ret = mysql_escape_string($str, SQL_GET_LINK());
321 // If nothing else works, fall back to escapeQuotes() again
322 $ret = escapeQuotes($str);
326 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
330 return $GLOBALS['sql_escapes'][''.$str.''];
333 // SELECT query string from table, columns and so on... ;-)
334 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
335 // Is columns an array?
336 if (!is_array($columns)) {
338 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
344 // Abort here with 'false'
348 // Prepare the SQL statement
349 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
352 return SQL_QUERY_ESC($sql,
361 // ALTER TABLE wrapper function
362 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = true) {
363 // Abort if link is down
364 if (!SQL_IS_LINK_UP()) return false;
366 // This is the default result...
369 // Determine index/fulltext/unique word
372 strpos($sql, 'INDEX') === false
374 strpos($sql, 'KEY') === false
376 strpos($sql, 'FULLTEXT') === false
378 strpos($sql, 'UNIQUE') === false
382 // Extract table name
383 $tableArray = explode(' ', $sql);
384 $tableName = str_replace('`', '', $tableArray[2]);
386 // Shall we add/drop?
387 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
388 // Try two columns, one should fix
389 foreach (array(4,5) as $idx) {
390 // And column name as well
391 $columnName = str_replace('`', '', $tableArray[$idx]);
393 // Get column information
394 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
395 array($tableName, $columnName), __FUNCTION__, __LINE__);
397 // Do we have no entry on ADD or an entry on DROP?
398 // 123 4 4 3 3 4 4 32 23 4 4 3 3 4 4 321
399 if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
401 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
402 $result = SQL_QUERY($sql, $F, $L, false);
404 // Skip further attempt(s)
406 } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
407 // Abort here because it is alreay there
408 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
410 } elseif ($columnName != 'KEY') {
411 // Something didn't fit
412 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
415 } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
416 // Skip this query silently
417 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
418 } elseif ($noIndex === false) {
419 // And column name as well
420 //* DEBUG: */ debugOutput(__LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
421 $keyName = str_replace('`', '', $tableArray[5]);
423 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
424 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
426 $begin = 1; $keyName = ',';
427 while (strpos($keyName, ',') !== false) {
429 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
430 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
433 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
434 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
442 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
444 // Non-skipping is default for ADD
447 // But should we DROP?
448 if ($tableArray[3] == 'DROP') {
449 // Then skip if nothing found!
451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
455 while ($content = SQL_FETCHARRAY($result)) {
457 //* DEBUG: */ debugOutput(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
458 if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
460 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
463 } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
465 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
472 SQL_FREERESULT($result);
475 if ($skip === false) {
476 // Send it to the SQL_QUERY() function
477 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
478 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
481 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
484 // Other ALTER TABLE query
485 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
486 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
493 // Getter for SQL link
494 function SQL_GET_LINK () {
498 // Is it in the globals?
499 if (isset($GLOBALS['sql_link'])) {
501 $link = $GLOBALS['sql_link'];
509 function SQL_SET_LINK ($link) {
510 // Is this a resource or null?
511 if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
512 // This may happen in installation phase
514 } elseif ((!is_resource($link)) && (!is_null($link))) {
515 // This should never happen!
516 debug_report_bug(__FUNCTION__, __LINE__, sprintf("link is not resource or null. Type: %s", gettype($link)));
520 $GLOBALS['sql_link'] = $link;
523 // Checks if the link is up
524 function SQL_IS_LINK_UP () {
528 // Do we have cached this?
529 if (isset($GLOBALS['is_sql_link_up'])) {
531 $linkUp = $GLOBALS['is_sql_link_up'];
534 $linkUp = is_resource(SQL_GET_LINK());
537 $GLOBALS['is_sql_link_up'] = $linkUp;
544 // Wrapper function to make code more readable
545 function SQL_HASZERONUMS ($result) {
546 // Just pass it through
547 return (SQL_NUMROWS($result) === 0);
550 // Private function to prepare the SQL query string
551 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
552 // Is it already cached?
553 if (!isset($GLOBALS['sql_strings'][$sqlString])) {
554 // Compile config+expression code
555 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
557 // Do final compilation
558 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
559 //die($sqlString.'<br />'.$sqlString2.'<br />'.$GLOBALS['sql_strings'][$sqlString]);
563 return $GLOBALS['sql_strings'][$sqlString];