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 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
45 function SQL_QUERY ($sqlString, $F, $L) {
47 $sqlString = trim($sqlString);
50 if (!SQL_IS_LINK_UP()) {
51 // We should not quietly ignore this!
52 debug_report_bug(sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
58 // Return 'false' because it has failed
60 } elseif (empty($sqlString)) {
62 debug_report_bug(sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
67 // This is invalid, of course
71 // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
72 $sqlString = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlString)));
75 $sqlString = FILTER_COMPILE_CONFIG($sqlString, true);
78 $querytimeBefore = microtime(true);
81 //* DEBUG: */ print('F=' . basename($F) . ',L=' . $L . 'sql=' . htmlentities($sqlString) . '<br />');
82 $result = mysql_query($sqlString, SQL_GET_LINK())
83 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error() . '<br />
86 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sqlString . ',numRows=' . SQL_NUMROWS($result) . ',affected=' . SQL_AFFECTEDROWS());
88 // Calculate query time
89 $queryTime = microtime(true) - $querytimeBefore;
91 // Add this query to array including timing
92 addSqlToDebug($result, $sqlString, $queryTime, $F, $L);
94 // Save last successfull query
95 setConfigEntry('db_last_query', $sqlString);
97 // Count all query times
98 incrementConfigEntry('sql_time', $queryTime);
101 incrementConfigEntry('sql_count');
104 if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y')) {
106 // Debugging stuff...
108 $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or app_die(__FILE__, __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", ' ', $sqlString)) . "\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 ($result) {
133 // Link is not up, no rows by default
136 // Is the result a valid resource?
137 if (is_resource($result)) {
138 // Get the count of rows from database
139 $lines = mysql_num_rows($result);
141 // Is the result empty? Then we have an error!
142 if (empty($lines)) $lines = '0';
143 } elseif (SQL_IS_LINK_UP()) {
144 // No resource given, no lines found!
153 function SQL_AFFECTEDROWS() {
154 // Valid link resource?
155 if (!SQL_IS_LINK_UP()) return false;
158 $lines = mysql_affected_rows(SQL_GET_LINK());
165 function SQL_FETCHROW ($result) {
166 // Is a result resource set?
167 if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) return false;
169 // Fetch the data and return it
170 return mysql_fetch_row($result);
174 function SQL_FETCHARRAY ($res, $nr=0, $remove_numerical=true) {
175 // Is a result resource set?
176 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
181 // Load row from database
182 $row = mysql_fetch_array($res);
184 // Return only arrays here
185 if (is_array($row)) {
186 // Shall we remove numerical data here automatically?
187 if ($remove_numerical) {
188 // So let's remove all numerical elements to save memory!
190 for ($idx = '0'; $idx < ($max / 2); $idx++) {
199 // Return a false here...
205 function SQL_RESULT ($res, $row, $field = '0') {
207 if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
209 // Run the result command and return the result
210 $result = mysql_result($res, $row, $field);
215 function SQL_CONNECT ($host, $login, $password, $F, $L) {
217 $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
219 // Set the link resource
220 SQL_SET_LINK($connect);
223 unset($GLOBALS['sql_link_res']);
226 // SQL select database
227 function SQL_SELECT_DB ($dbName, $F, $L) {
228 // Is there still a valid link? If not, skip it.
229 if (!SQL_IS_LINK_UP()) return false;
232 return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
236 function SQL_CLOSE ($F, $L) {
237 if (!SQL_IS_LINK_UP()) {
242 // Close database link and forget the link
243 $close = mysql_close(SQL_GET_LINK())
244 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
250 unset($GLOBALS['sql_link_res']);
257 function SQL_FREERESULT ($result) {
258 if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) {
263 $res = mysql_free_result($result);
267 // SQL string escaping
268 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure=true) {
270 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
273 $dataSecured['__sql_string'] = $qstring;
274 foreach ($data as $key => $value) {
275 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
279 $query = call_user_func_array('sprintf', $dataSecured);
283 //* DEBUG: */ $fp = fopen(getConfig('CACHE_PATH') . 'escape_debug.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write debug.log!");
284 //* DEBUG: */ fwrite($fp, $F.'('.$L."): ".str_replace("\r", '', str_replace("\n", " ", $eval))."\n");
285 //* DEBUG: */ fclose($fp);
288 // Run SQL query (default)
289 return SQL_QUERY($query, $F, $L);
291 // Return secured string
296 // Get id from last INSERT command
297 function SQL_INSERTID () {
298 if (!SQL_IS_LINK_UP()) return false;
299 return mysql_insert_id();
302 // Escape a string for the database
303 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
305 if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
306 // Secure string first? (which is the default behaviour!)
307 if ($secureString === true) {
309 $str = secureString($str, $strip);
312 if (!SQL_IS_LINK_UP()) {
313 // Fall-back to escapeQuotes() when there is no link
314 $ret = escapeQuotes($str);
315 } elseif (function_exists('mysql_real_escape_string')) {
316 // The new and improved version
317 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
318 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
319 } elseif (function_exists('mysql_escape_string')) {
320 // The obsolete function
321 $ret = mysql_escape_string($str, SQL_GET_LINK());
323 // If nothing else works, fall back to escapeQuotes() again
324 $ret = escapeQuotes($str);
328 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
332 return $GLOBALS['sql_escapes'][''.$str.''];
335 // SELECT query string from table, columns and so on... ;-)
336 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
337 // Is columns an array?
338 if (!is_array($columns)) {
340 debug_report_bug(sprintf("columns is not an array. %s != array, file=%s, line=%s",
346 // Abort here with 'false'
350 // Prepare the SQL statement
351 $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
354 return SQL_QUERY_ESC($sql,
363 // ALTER TABLE wrapper function
364 function SQL_ALTER_TABLE ($sql, $F, $L) {
365 // Abort if link is down
366 if (!SQL_IS_LINK_UP()) return false;
368 // This is the default result...
371 // Determine index/fulltext/unique word
374 strpos($sql, 'INDEX') === false
376 strpos($sql, 'KEY') === false
378 strpos($sql, 'FULLTEXT') === false
380 strpos($sql, 'UNIQUE') === false
384 // Extract table name
385 $tableArray = explode(' ', $sql);
386 $tableName = str_replace('`', '', $tableArray[2]);
388 // Shall we add/drop?
389 if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
390 // Try two columns, one should fix
391 foreach (array(4,5) as $idx) {
392 // And column name as well
393 $columnName = str_replace('`', '', $tableArray[$idx]);
395 // Get column information
396 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
397 array($tableName, $columnName), __FILE__, __LINE__);
399 // Do we have no entry on ADD or an entry on DROP?
400 // 123 4 4 3 3 4 4 32 23 4 4 3 3 4 4 321
401 if (((SQL_NUMROWS($result) == '0') && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
403 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
404 $result = SQL_QUERY($sql, $F, $L, false);
406 // Skip further attempt(s)
408 } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == '0') && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
409 // Abort here because it is alreay there
410 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
412 } elseif ($columnName != 'KEY') {
413 // Something didn't fit
414 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
417 } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
418 // Skip this query silently
419 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
420 } elseif ($noIndex === false) {
421 // And column name as well
422 //* DEBUG: */ print __LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>';
423 $keyName = str_replace('`', '', $tableArray[5]);
425 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
426 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
428 $begin = 1; $keyName = ',';
429 while (strpos($keyName, ',') !== false) {
431 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
432 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
435 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
436 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
444 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FILE__, __LINE__);
446 // Non-skipping is default for ADD
449 // But should we DROP?
450 if ($tableArray[3] == 'DROP') {
451 // Then skip if nothing found!
453 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
457 while ($content = SQL_FETCHARRAY($result)) {
459 //* DEBUG: */ print(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
460 if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
462 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
465 } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
474 SQL_FREERESULT($result);
477 if ($skip === false) {
478 // Send it to the SQL_QUERY() function
479 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
480 $result = SQL_QUERY($sql, $F, $L, false);
483 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
486 // Other ALTER TABLE query
487 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
488 $result = SQL_QUERY($sql, $F, $L, false);
495 // Getter for SQL link
496 function SQL_GET_LINK () {
500 // Is it in the globals?
501 if (isset($GLOBALS['sql_link'])) {
503 $link = $GLOBALS['sql_link'];
511 function SQL_SET_LINK ($link) {
512 // Is this a resource or null?
513 if ((!is_resource($link)) && (!is_null($link))) {
514 // This should never happen!
515 debug_report_bug(sprintf("link is not resource or null. Type: %s", gettype($link)));
519 $GLOBALS['sql_link'] = $link;
522 // Checks if the link is up
523 function SQL_IS_LINK_UP () {
527 // Do we have cached this?
528 if (isset($GLOBALS['sql_link_res'])) {
530 $linkUp = $GLOBALS['sql_link_res'];
533 $linkUp = is_resource(SQL_GET_LINK());
536 $GLOBALS['sql_link_res'] = $linkUp;