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) {
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)));
76 $sqlString = str_replace('{PER}', '%', $sqlString);
78 // Compile config entries out
79 $sqlString = SQL_PREPARE_SQL_STRING($sqlString);
82 $querytimeBefore = microtime(true);
85 //* DEBUG: */ print('F=' . basename($F) . ',L=' . $L . 'sql=' . htmlentities($sqlString) . '<br />');
86 $result = mysql_query($sqlString, SQL_GET_LINK())
87 or debug_report_bug(__FUNCTION__, __LINE__, 'file='. $F . ',line=' . $L . ':mysql_error()=' . mysql_error() . "\n".
88 'Query string:' . $sqlString);
89 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sqlString . ',numRows=' . SQL_NUMROWS($result) . ',affected=' . SQL_AFFECTEDROWS());
91 // Calculate query time
92 $queryTime = microtime(true) - $querytimeBefore;
94 // Add this query to array including timing
95 addSqlToDebug($result, $sqlString, $queryTime, $F, $L);
97 // Save last successfull query
98 setConfigEntry('db_last_query', $sqlString);
100 // Count all query times
101 incrementConfigEntry('sql_time', $queryTime);
104 incrementConfigEntry('sql_count');
107 if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
109 // Debugging stuff...
111 $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write mysql.log!');
112 if (!isset($GLOBALS['sql_first_entry'])) {
114 fwrite($fp, 'Module=' . getModule() . "\n");
115 $GLOBALS['sql_first_entry'] = true;
117 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $sqlString)) . "\n");
122 if (!isStatsEntrySet('db_hits')) {
123 // Count in dummy variable
124 setStatsEntry('db_hits', 1);
126 // Count to config array
127 incrementStatsEntry('db_hits');
135 function SQL_NUMROWS ($resource) {
136 // Valid link resource?
137 if (!SQL_IS_LINK_UP()) return false;
139 // Link is not up, no rows by default
142 // Is the result a valid resource?
143 if (is_resource($resource)) {
144 // Get the count of rows from database
145 $lines = mysql_num_rows($resource);
147 // No resource given, please fix this
148 trigger_error('No resource given! result[]=' . gettype($resource));
156 function SQL_AFFECTEDROWS() {
157 // Valid link resource?
158 if (!SQL_IS_LINK_UP()) return false;
161 $lines = mysql_affected_rows(SQL_GET_LINK());
168 function SQL_FETCHROW ($resource) {
169 // Is a result resource set?
170 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
172 // Fetch the data and return it
173 return mysql_fetch_row($resource);
177 function SQL_FETCHARRAY ($res, $nr=0) {
178 // Is a result resource set?
179 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
181 // Load row from database
182 $row = mysql_fetch_assoc($res);
184 // Return only arrays here
185 if (is_array($row)) {
189 // Return a false, else some loops would go endless...
195 function SQL_RESULT ($resource, $row, $field = '0') {
196 // Is $resource valid?
197 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
199 // Run the result command
200 $result = mysql_result($resource, $row, $field);
202 // ... and return the result
207 function SQL_CONNECT ($host, $login, $password, $F, $L) {
209 $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
211 // Set the link resource
212 SQL_SET_LINK($connect);
215 unset($GLOBALS['is_sql_link_up']);
218 // SQL select database
219 function SQL_SELECT_DB ($dbName, $F, $L) {
220 // Is there still a valid link? If not, skip it.
221 if (!SQL_IS_LINK_UP()) return false;
224 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
228 function SQL_CLOSE ($F, $L) {
229 if (!SQL_IS_LINK_UP()) {
234 // Close database link and forget the link
235 $close = mysql_close(SQL_GET_LINK())
236 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
242 unset($GLOBALS['is_sql_link_up']);
249 function SQL_FREERESULT ($resource) {
250 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
256 $res = mysql_free_result($resource);
258 // And return that result of freeing it...
262 // SQL string escaping
263 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
265 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
268 $dataSecured['__sql_string'] = $sqlString;
269 foreach ($data as $key => $value) {
270 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
274 $query = call_user_func_array('sprintf', $dataSecured);
278 //* DEBUG: */ $fp = fopen(getConfig('CACHE_PATH') . 'escape_debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write debug.log!');
279 //* DEBUG: */ fwrite($fp, $F . '(' . $L . '): ' . str_replace("\r", '', str_replace("\n", ' ', $eval)) . "\n");
280 //* DEBUG: */ fclose($fp);
283 // Run SQL query (default)
284 return SQL_QUERY($query, $F, $L);
286 // Return secured string
291 // Get id from last INSERT command
292 function SQL_INSERTID () {
293 if (!SQL_IS_LINK_UP()) return false;
294 return mysql_insert_id();
297 // Escape a string for the database
298 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
300 if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
301 // Secure string first? (which is the default behaviour!)
302 if ($secureString === true) {
304 $str = secureString($str, $strip);
307 if (!SQL_IS_LINK_UP()) {
308 // Fall-back to escapeQuotes() when there is no link
309 $ret = escapeQuotes($str);
310 } elseif (function_exists('mysql_real_escape_string')) {
311 // The new and improved version
312 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
313 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
314 } elseif (function_exists('mysql_escape_string')) {
315 // The obsolete function
316 $ret = mysql_escape_string($str, SQL_GET_LINK());
318 // If nothing else works, fall back to escapeQuotes() again
319 $ret = escapeQuotes($str);
323 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
327 return $GLOBALS['sql_escapes'][''.$str.''];
330 // SELECT query string from table, columns and so on... ;-)
331 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
332 // Is columns an array?
333 if (!is_array($columns)) {
335 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
341 // Abort here with 'false'
345 // Prepare the SQL statement
346 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
349 return SQL_QUERY_ESC($sql,
358 // ALTER TABLE wrapper function
359 function SQL_ALTER_TABLE ($sql, $F, $L) {
360 // Abort if link is down
361 if (!SQL_IS_LINK_UP()) return false;
363 // This is the default result...
366 // Determine index/fulltext/unique word
369 strpos($sql, 'INDEX') === false
371 strpos($sql, 'KEY') === false
373 strpos($sql, 'FULLTEXT') === false
375 strpos($sql, 'UNIQUE') === false
379 // Extract table name
380 $tableArray = explode(' ', $sql);
381 $tableName = str_replace('`', '', $tableArray[2]);
383 // Shall we add/drop?
384 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
385 // Try two columns, one should fix
386 foreach (array(4,5) as $idx) {
387 // And column name as well
388 $columnName = str_replace('`', '', $tableArray[$idx]);
390 // Get column information
391 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
392 array($tableName, $columnName), __FUNCTION__, __LINE__);
394 // Do we have no entry on ADD or an entry on DROP?
395 // 123 4 4 3 3 4 4 32 23 4 4 3 3 4 4 321
396 if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
398 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
399 $result = SQL_QUERY($sql, $F, $L, false);
401 // Skip further attempt(s)
403 } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
404 // Abort here because it is alreay there
405 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
407 } elseif ($columnName != 'KEY') {
408 // Something didn't fit
409 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
412 } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
413 // Skip this query silently
414 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
415 } elseif ($noIndex === false) {
416 // And column name as well
417 //* DEBUG: */ print __LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>';
418 $keyName = str_replace('`', '', $tableArray[5]);
420 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
421 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
423 $begin = 1; $keyName = ',';
424 while (strpos($keyName, ',') !== false) {
426 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
427 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
430 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
431 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
439 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
441 // Non-skipping is default for ADD
444 // But should we DROP?
445 if ($tableArray[3] == 'DROP') {
446 // Then skip if nothing found!
448 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
452 while ($content = SQL_FETCHARRAY($result)) {
454 //* DEBUG: */ print(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
455 if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
457 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
460 } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
462 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
469 SQL_FREERESULT($result);
472 if ($skip === false) {
473 // Send it to the SQL_QUERY() function
474 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
475 $result = SQL_QUERY($sql, $F, $L, false);
478 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
481 // Other ALTER TABLE query
482 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
483 $result = SQL_QUERY($sql, $F, $L, false);
490 // Getter for SQL link
491 function SQL_GET_LINK () {
495 // Is it in the globals?
496 if (isset($GLOBALS['sql_link'])) {
498 $link = $GLOBALS['sql_link'];
506 function SQL_SET_LINK ($link) {
507 // Is this a resource or null?
508 if ((!is_resource($link)) && (!is_null($link))) {
509 // This should never happen!
510 debug_report_bug(__FUNCTION__, __LINE__, sprintf("link is not resource or null. Type: %s", gettype($link)));
514 $GLOBALS['sql_link'] = $link;
517 // Checks if the link is up
518 function SQL_IS_LINK_UP () {
522 // Do we have cached this?
523 if (isset($GLOBALS['is_sql_link_up'])) {
525 $linkUp = $GLOBALS['is_sql_link_up'];
528 $linkUp = is_resource(SQL_GET_LINK());
531 $GLOBALS['is_sql_link_up'] = $linkUp;
538 // Wrapper function to make code more readable
539 function SQL_HASZERONUMS ($result) {
540 // Just pass it through
541 return (SQL_NUMROWS($result) === 0);
544 // Private function to prepare the SQL query string
545 function SQL_PREPARE_SQL_STRING ($sqlString) {
546 // Is it already cached?
547 if (!isset($GLOBALS['sql_strings'][$sqlString])) {
548 // No, then generate the eval() command
549 $eval = '$sql = "' . FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG(escapeQuotes($sqlString))) . '";';
553 $GLOBALS['sql_strings'][$sqlString] = $sql;
557 return $GLOBALS['sql_strings'][$sqlString];