13d333d1b2e16f99c1cb5206e88ff7a0470ba18b
[mailer.git] / inc / db / lib-mysql3.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/29/2004 *
4  * ===================                          Last change: 08/29/2004 *
5  *                                                                      *
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  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
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                  *
22  *                                                                      *
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.                                  *
27  *                                                                      *
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.                         *
32  *                                                                      *
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,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 } // END - if
43
44 // SQL queries
45 function SQL_QUERY ($sqlString, $F, $L) {
46         // Trim SQL string
47         $sqlString = trim($sqlString);
48
49         // Link is up?
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",
53                         $sqlString,
54                         basename($F),
55                         $L
56                 ));
57
58                 // Return 'false' because it has failed
59                 return false;
60         } elseif (empty($sqlString)) {
61                 // Empty SQL string!
62                 debug_report_bug(sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
63                         basename($F),
64                         $L
65                 ));
66
67                 // This is invalid, of course
68                 return false;
69         }
70
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)));
73
74         // Compile config out
75         $sqlString = FILTER_COMPILE_CONFIG($sqlString, true);
76
77         // Starting time
78         $querytimeBefore = microtime(true);
79
80         // Run SQL command
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 />
84 Query string:<br />
85 ' . $sqlString);
86         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sqlString . ',numRows=' . SQL_NUMROWS($result) . ',affected=' . SQL_AFFECTEDROWS());
87
88         // Calculate query time
89         $queryTime = microtime(true) - $querytimeBefore;
90
91         // Add this query to array including timing
92         addSqlToDebug($result, $sqlString, $queryTime, $F, $L);
93
94         // Save last successfull query
95         setConfigEntry('db_last_query', $sqlString);
96
97         // Count all query times
98         incrementConfigEntry('sql_time', $queryTime);
99
100         // Count this query
101         incrementConfigEntry('sql_count');
102
103         // Debug output
104         if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y')) {
105                 //
106                 // Debugging stuff...
107                 //
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'])) {
110                         // Write first entry
111                         fwrite($fp, 'Module=' . getModule() . "\n");
112                         $GLOBALS['sql_first_entry'] = true;
113                 } // END - if
114                 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $sqlString)) . "\n");
115                 fclose($fp);
116         } // END - if
117
118         // Count DB hits
119         if (!isStatsEntrySet('db_hits')) {
120                 // Count in dummy variable
121                 setStatsEntry('db_hits', 1);
122         } else {
123                 // Count to config array
124                 incrementStatsEntry('db_hits');
125         }
126
127         // Return the result
128         return $result;
129 }
130
131 // SQL num rows
132 function SQL_NUMROWS ($result) {
133         // Link is not up, no rows by default
134         $lines = false;
135
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);
140
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!
145                 $lines = '0';
146         }
147
148         // Return lines
149         return $lines;
150 }
151
152 // SQL affected rows
153 function SQL_AFFECTEDROWS() {
154         // Valid link resource?
155         if (!SQL_IS_LINK_UP()) return false;
156
157         // Get affected rows
158         $lines = mysql_affected_rows(SQL_GET_LINK());
159
160         // Return it
161         return $lines;
162 }
163
164 // SQL fetch row
165 function SQL_FETCHROW ($result) {
166         // Is a result resource set?
167         if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) return false;
168
169         // Fetch the data and return it
170         return mysql_fetch_row($result);
171 }
172
173 // SQL fetch array
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;
177
178         // Initialize array
179         $row = array();
180
181         // Load row from database
182         $row = mysql_fetch_array($res);
183
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!
189                         $max = count($row);
190                         for ($idx = '0'; $idx < ($max / 2); $idx++) {
191                                 // Remove entry
192                                 unset($row[$idx]);
193                         } // END - for
194                 } // END - if
195
196                 // Return row
197                 return $row;
198         } else {
199                 // Return a false here...
200                 return false;
201         }
202 }
203
204 // SQL result
205 function SQL_RESULT ($res, $row, $field = '0') {
206         // Is $res valid?
207         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
208
209         // Run the result command and return the result
210         $result = mysql_result($res, $row, $field);
211         return $result;
212 }
213
214 // SQL connect
215 function SQL_CONNECT ($host, $login, $password, $F, $L) {
216         // Try to connect
217         $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
218
219         // Set the link resource
220         SQL_SET_LINK($connect);
221
222         // Destroy cache
223         unset($GLOBALS['sql_link_res']);
224 }
225
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;
230
231         // Return the result
232         return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
233 }
234
235 // SQL close link
236 function SQL_CLOSE ($F, $L) {
237         if (!SQL_IS_LINK_UP()) {
238                 // Skip double close
239                 return false;
240         } // END - if
241
242         // Close database link and forget the link
243         $close = mysql_close(SQL_GET_LINK())
244                 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
245
246         // Close link
247         SQL_SET_LINK(null);
248
249         // Destroy cache
250         unset($GLOBALS['sql_link_res']);
251
252         // Return the result
253         return $close;
254 }
255
256 // SQL free result
257 function SQL_FREERESULT ($result) {
258         if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) {
259                 // Abort here
260                 return false;
261         } // END - if
262
263         $res = mysql_free_result($result);
264         return $res;
265 }
266
267 // SQL string escaping
268 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure=true) {
269         // Link is there?
270         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
271
272         // Escape all data
273         $dataSecured['__sql_string'] = $qstring;
274         foreach ($data as $key => $value) {
275                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
276         } // END - foreach
277
278         // Generate query
279         $query = call_user_func_array('sprintf', $dataSecured);
280
281         // Debugging
282         //
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);
286
287         if ($run === true) {
288                 // Run SQL query (default)
289                 return SQL_QUERY($query, $F, $L);
290         } else {
291                 // Return secured string
292                 return $query;
293         }
294 }
295
296 // Get id from last INSERT command
297 function SQL_INSERTID () {
298         if (!SQL_IS_LINK_UP()) return false;
299         return mysql_insert_id();
300 }
301
302 // Escape a string for the database
303 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
304         // Do we have cache?
305         if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
306                 // Secure string first? (which is the default behaviour!)
307                 if ($secureString === true) {
308                         // Then do it here
309                         $str = secureString($str, $strip);
310                 } // END - if
311
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());
322                 } else {
323                         // If nothing else works, fall back to escapeQuotes() again
324                         $ret = escapeQuotes($str);
325                 }
326
327                 // Cache result
328                 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
329         } // END - if
330
331         // Return it
332         return $GLOBALS['sql_escapes'][''.$str.''];
333 }
334
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)) {
339                 // No array
340                 debug_report_bug(sprintf("columns is not an array. %s != array, file=%s, line=%s",
341                         gettype($columns),
342                         basename($F),
343                         $L
344                 ));
345
346                 // Abort here with 'false'
347                 return false;
348         } // END  - if
349
350         // Prepare the SQL statement
351         $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
352
353         // Return the result
354         return SQL_QUERY_ESC($sql,
355                 array(
356                         $table,
357                         $idRow,
358                         bigintval($id),
359                 ), $F, $L
360         );
361 }
362
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;
367
368         // This is the default result...
369         $result = false;
370
371         // Determine index/fulltext/unique word
372         $noIndex = (
373         (
374                 strpos($sql, 'INDEX') === false
375         ) && (
376                 strpos($sql, 'KEY') === false
377         ) && (
378                 strpos($sql, 'FULLTEXT') === false
379         ) && (
380                 strpos($sql, 'UNIQUE') === false
381         )
382         );
383
384         // Extract table name
385         $tableArray = explode(' ', $sql);
386         $tableName = str_replace('`', '', $tableArray[2]);
387
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]);
394
395                         // Get column information
396                         $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
397                                 array($tableName, $columnName), __FILE__, __LINE__);
398
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))) {
402                                 // Do the query
403                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
404                                 $result = SQL_QUERY($sql, $F, $L, false);
405
406                                 // Skip further attempt(s)
407                                 break;
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);
411                                 break;
412                         } elseif ($columnName != 'KEY') {
413                                 // Something didn't fit
414                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
415                         }
416                 } // END - foreach
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]);
424
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'))) {
427                         // Init loop
428                         $begin = 1; $keyName = ',';
429                         while (strpos($keyName, ',') !== false) {
430                                 // Use last
431                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
432                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
433
434                                 // Remove brackes
435                                 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
436                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
437
438                                 // Continue
439                                 $begin++;
440                         } // END while
441                 } // END - if
442
443                 // Show indexes
444                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FILE__, __LINE__);
445
446                 // Non-skipping is default for ADD
447                 $skip = false;
448
449                 // But should we DROP?
450                 if ($tableArray[3] == 'DROP') {
451                         // Then skip if nothing found!
452                         $skip = true;
453                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
454                 } // END - if
455
456                 // Walk through all
457                 while ($content = SQL_FETCHARRAY($result)) {
458                         // Is it found?
459                         //* DEBUG: */ print(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
460                         if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
461                                 // Skip this query!
462                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
463                                 $skip = true;
464                                 break;
465                         } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
466                                 // Don't skip this!
467                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
468                                 $skip = false;
469                                 break;
470                         }
471                 } // END - while
472
473                 // Free result
474                 SQL_FREERESULT($result);
475
476                 // Shall we run it?
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);
481                 } else {
482                         // Not executed
483                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
484                 }
485         } else {
486                 // Other ALTER TABLE query
487                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
488                 $result = SQL_QUERY($sql, $F, $L, false);
489         }
490
491         // Return result
492         return $result;
493 }
494
495 // Getter for SQL link
496 function SQL_GET_LINK () {
497         // Init link
498         $link = null;
499
500         // Is it in the globals?
501         if (isset($GLOBALS['sql_link'])) {
502                 // Then take it
503                 $link = $GLOBALS['sql_link'];
504         } // END - if
505
506         // Return it
507         return $link;
508 }
509
510 // Setter for 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)));
516         } // END - if
517
518         // Set it
519         $GLOBALS['sql_link'] = $link;
520 }
521
522 // Checks if the link is up
523 function SQL_IS_LINK_UP () {
524         // Default is not up
525         $linkUp = false;
526
527         // Do we have cached this?
528         if (isset($GLOBALS['sql_link_res'])) {
529                 // Then use this
530                 $linkUp = $GLOBALS['sql_link_res'];
531         } else {
532                 // Get it
533                 $linkUp = is_resource(SQL_GET_LINK());
534
535                 // And cache it
536                 $GLOBALS['sql_link_res'] = $linkUp;
537         }
538
539         // Return the result
540         return $linkUp;
541 }
542
543 // [EOF]
544 ?>