Cache path changed and compileRawCode() introduced
[mailer.git] / inc / db / lib-mysql3.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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 = array_sum(explode(' ', microtime()));
79
80         // Run SQL command
81         //* DEBUG: */ print('F=' . basename($F) . ',L=' . $L . 'sql=' . $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         // Ending time
89         $querytimeAfter = array_sum(explode(' ', microtime()));
90
91         // Calculate query time
92         $queryTime = $querytimeAfter - $querytimeBefore;
93
94         // Add this query to array including timing
95         addSqlToDebug($result, $sqlString, $queryTime, $F, $L);
96
97         // Save last successfull query
98         setConfigEntry('db_last_query', $sqlString);
99
100         // Count all query times
101         incrementConfigEntry('sql_time', $queryTime);
102
103         // Count this query
104         incrementConfigEntry('sql_count');
105
106         // Debug output
107         if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y')) {
108                 //
109                 // Debugging stuff...
110                 //
111                 $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write mysql.log!");
112                 if (!isset($GLOBALS['sql_first_entry'])) {
113                         // Write first entry
114                         fwrite($fp, 'Module=' . getModule() . "\n");
115                         $GLOBALS['sql_first_entry'] = true;
116                 } // END - if
117                 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $sqlString)) . "\n");
118                 fclose($fp);
119         } // END - if
120
121         // Count DB hits
122         if (!isStatsEntrySet('db_hits')) {
123                 // Count in dummy variable
124                 setStatsEntry('db_hits', 1);
125         } else {
126                 // Count to config array
127                 incrementStatsEntry('db_hits');
128         }
129
130         // Return the result
131         return $result;
132 }
133
134 // SQL num rows
135 function SQL_NUMROWS ($result) {
136         // Link is not up, no rows by default
137         $lines = false;
138
139         // Is the result a valid resource?
140         if (is_resource($result)) {
141                 // Get the count of rows from database
142                 $lines = mysql_num_rows($result);
143
144                 // Is the result empty? Then we have an error!
145                 if (empty($lines)) $lines = 0;
146         } elseif (SQL_IS_LINK_UP()) {
147                 // No resource given, no lines found!
148                 $lines = 0;
149         }
150
151         // Return lines
152         return $lines;
153 }
154
155 // SQL affected rows
156 function SQL_AFFECTEDROWS() {
157         // Valid link resource?
158         if (!SQL_IS_LINK_UP()) return false;
159
160         // Get affected rows
161         $lines = mysql_affected_rows(SQL_GET_LINK());
162
163         // Return it
164         return $lines;
165 }
166
167 // SQL fetch row
168 function SQL_FETCHROW ($result) {
169         // Is a result resource set?
170         if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) return false;
171
172         // Fetch the data and return it
173         return mysql_fetch_row($result);
174 }
175
176 // SQL fetch array
177 function SQL_FETCHARRAY ($res, $nr=0, $remove_numerical=true) {
178         // Is a result resource set?
179         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
180
181         // Initialize array
182         $row = array();
183
184         // Load row from database
185         $row = mysql_fetch_array($res);
186
187         // Return only arrays here
188         if (is_array($row)) {
189                 // Shall we remove numerical data here automatically?
190                 if ($remove_numerical) {
191                         // So let's remove all numerical elements to save memory!
192                         $max = count($row);
193                         for ($idx = 0; $idx < ($max / 2); $idx++) {
194                                 // Remove entry
195                                 unset($row[$idx]);
196                         } // END - for
197                 } // END - if
198
199                 // Return row
200                 return $row;
201         } else {
202                 // Return a false here...
203                 return false;
204         }
205 }
206
207 // SQL result
208 function SQL_RESULT ($res, $row, $field = 0) {
209         // Is $res valid?
210         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
211
212         // Run the result command and return the result
213         $result = mysql_result($res, $row, $field);
214         return $result;
215 }
216
217 // SQL connect
218 function SQL_CONNECT ($host, $login, $password, $F, $L) {
219         // Try to connect
220         $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
221
222         // Set the link resource
223         SQL_SET_LINK($connect);
224
225         // Destroy cache
226         unset($GLOBALS['sql_link_res']);
227 }
228
229 // SQL select database
230 function SQL_SELECT_DB ($dbName, $F, $L) {
231         // Is there still a valid link? If not, skip it.
232         if (!SQL_IS_LINK_UP()) return false;
233
234         // Return the result
235         return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
236 }
237
238 // SQL close link
239 function SQL_CLOSE ($F, $L) {
240         if (!SQL_IS_LINK_UP()) {
241                 // Skip double close
242                 return false;
243         } // END - if
244
245         // Close database link and forget the link
246         $close = mysql_close(SQL_GET_LINK())
247                 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
248
249         // Close link
250         SQL_SET_LINK(null);
251
252         // Destroy cache
253         unset($GLOBALS['sql_link_res']);
254
255         // Return the result
256         return $close;
257 }
258
259 // SQL free result
260 function SQL_FREERESULT ($result) {
261         if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) {
262                 // Abort here
263                 return false;
264         } // END - if
265
266         $res = mysql_free_result($result);
267         return $res;
268 }
269
270 // SQL string escaping
271 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure=true) {
272         // Link is there?
273         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
274
275         // Escape all data
276         $dataSecured['__sql_string'] = $qstring;
277         foreach ($data as $key => $value) {
278                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
279         } // END - foreach
280
281         // Generate query
282         $query = call_user_func_array('sprintf', $dataSecured);
283
284         // Debugging
285         //
286         //* DEBUG: */ $fp = fopen(getConfig('CACHE_PATH') . 'escape_debug.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write debug.log!");
287         //* DEBUG: */ fwrite($fp, $F.'('.$L."): ".str_replace("\r", '', str_replace("\n", " ", $eval))."\n");
288         //* DEBUG: */ fclose($fp);
289
290         if ($run === true) {
291                 // Run SQL query (default)
292                 return SQL_QUERY($query, $F, $L);
293         } else {
294                 // Return secured string
295                 return $query;
296         }
297 }
298
299 // Get id from last INSERT command
300 function SQL_INSERTID () {
301         if (!SQL_IS_LINK_UP()) return false;
302         return mysql_insert_id();
303 }
304
305 // Escape a string for the database
306 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
307         // Do we have cache?
308         if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
309                 // Secure string first? (which is the default behaviour!)
310                 if ($secureString === true) {
311                         // Then do it here
312                         $str = secureString($str, $strip);
313                 } // END - if
314
315                 if (!SQL_IS_LINK_UP()) {
316                         // Fall-back to smartAddSlashes() when there is no link
317                         $ret = smartAddSlashes($str);
318                 } elseif (function_exists('mysql_real_escape_string')) {
319                         // The new and improved version
320                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
321                         $ret = mysql_real_escape_string($str, SQL_GET_LINK());
322                 } elseif (function_exists('mysql_escape_string')) {
323                         // The obsolete function
324                         $ret = mysql_escape_string($str, SQL_GET_LINK());
325                 } else {
326                         // If nothing else works, fall back to smartAddSlashes() again
327                         $ret = smartAddSlashes($str);
328                 }
329
330                 // Cache result
331                 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
332         } // END - if
333
334         // Return it
335         return $GLOBALS['sql_escapes'][''.$str.''];
336 }
337
338 // SELECT query string from table, columns and so on... ;-)
339 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
340         // Is columns an array?
341         if (!is_array($columns)) {
342                 // No array
343                 debug_report_bug(sprintf("columns is not an array. %s != array, file=%s, line=%s",
344                         gettype($columns),
345                         basename($F),
346                         $L
347                 ));
348
349                 // Abort here with 'false'
350                 return false;
351         } // END  - if
352
353         // Prepare the SQL statement
354         $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
355
356         // Return the result
357         return SQL_QUERY_ESC($sql,
358                 array(
359                         $table,
360                         $idRow,
361                         bigintval($id),
362                 ), $F, $L
363         );
364 }
365
366 // ALTER TABLE wrapper function
367 function SQL_ALTER_TABLE ($sql, $F, $L) {
368         // Abort if link is down
369         if (!SQL_IS_LINK_UP()) return false;
370
371         // This is the default result...
372         $result = false;
373
374         // Determine index/fulltext/unique word
375         $noIndex = (
376         (
377                 strpos($sql, 'INDEX') === false
378         ) && (
379                 strpos($sql, 'KEY') === false
380         ) && (
381                 strpos($sql, 'FULLTEXT') === false
382         ) && (
383                 strpos($sql, 'UNIQUE') === false
384         )
385         );
386
387         // Extract table name
388         $tableArray = explode(' ', $sql);
389         $tableName = str_replace('`', '', $tableArray[2]);
390
391         // Shall we add/drop?
392         if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
393                 // Try two columns, one should fix
394                 foreach (array(4,5) as $idx) {
395                         // And column name as well
396                         $columnName = str_replace('`', '', $tableArray[$idx]);
397
398                         // Get column information
399                         $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
400                                 array($tableName, $columnName), __FILE__, __LINE__);
401
402                         // Do we have no entry on ADD or an entry on DROP?
403                         // 123           4       4     3    3      4           4          32    23           4       4     3    3      4            4          321
404                         if (((SQL_NUMROWS($result) == 0) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
405                                 // Do the query
406                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
407                                 $result = SQL_QUERY($sql, $F, $L, false);
408
409                                 // Skip further attempt(s)
410                                 break;
411                         } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 0) && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
412                                 // Abort here because it is alreay there
413                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
414                                 break;
415                         } elseif ($columnName != 'KEY') {
416                                 // Something didn't fit
417                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
418                         }
419                 } // END - foreach
420         } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
421                 // Skip this query silently
422                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
423         } elseif ($noIndex === false) {
424                 // And column name as well
425                 //* DEBUG: */ print __LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>';
426                 $keyName = str_replace('`', '', $tableArray[5]);
427
428                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
429                 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
430                         // Init loop
431                         $begin = 1; $keyName = ',';
432                         while (strpos($keyName, ',') !== false) {
433                                 // Use last
434                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
435                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
436
437                                 // Remove brackes
438                                 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
439                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
440
441                                 // Continue
442                                 $begin++;
443                         } // END while
444                 } // END - if
445
446                 // Show indexes
447                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FILE__, __LINE__);
448
449                 // Non-skipping is default for ADD
450                 $skip = false;
451
452                 // But should we DROP?
453                 if ($tableArray[3] == 'DROP') {
454                         // Then skip if nothing found!
455                         $skip = true;
456                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
457                 } // END - if
458
459                 // Walk through all
460                 while ($content = SQL_FETCHARRAY($result)) {
461                         // Is it found?
462                         //* DEBUG: */ print(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
463                         if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
464                                 // Skip this query!
465                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
466                                 $skip = true;
467                                 break;
468                         } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
469                                 // Don't skip this!
470                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
471                                 $skip = false;
472                                 break;
473                         }
474                 } // END - while
475
476                 // Free result
477                 SQL_FREERESULT($result);
478
479                 // Shall we run it?
480                 if ($skip === false) {
481                         // Send it to the SQL_QUERY() function
482                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
483                         $result = SQL_QUERY($sql, $F, $L, false);
484                 } else {
485                         // Not executed
486                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
487                 }
488         } else {
489                 // Other ALTER TABLE query
490                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
491                 $result = SQL_QUERY($sql, $F, $L, false);
492         }
493
494         // Return result
495         return $result;
496 }
497
498 // Getter for SQL link
499 function SQL_GET_LINK () {
500         // Init link
501         $link = null;
502
503         // Is it in the globals?
504         if (isset($GLOBALS['sql_link'])) {
505                 // Then take it
506                 $link = $GLOBALS['sql_link'];
507         } // END - if
508
509         // Return it
510         return $link;
511 }
512
513 // Setter for link
514 function SQL_SET_LINK ($link) {
515         // Is this a resource or null?
516         if ((!is_resource($link)) && (!is_null($link))) {
517                 // This should never happen!
518                 debug_report_bug(sprintf("link is not resource or null. Type: %s", gettype($link)));
519         } // END - if
520
521         // Set it
522         $GLOBALS['sql_link'] = $link;
523 }
524
525 // Checks if the link is up
526 function SQL_IS_LINK_UP () {
527         // Default is not up
528         $linkUp = false;
529
530         // Do we have cached this?
531         if (isset($GLOBALS['sql_link_res'])) {
532                 // Then use this
533                 $linkUp = $GLOBALS['sql_link_res'];
534         } else {
535                 // Get it
536                 $linkUp = is_resource(SQL_GET_LINK());
537
538                 // And cache it
539                 $GLOBALS['sql_link_res'] = $linkUp;
540         }
541
542         // Return the result
543         return $linkUp;
544 }
545
546 // [EOF]
547 ?>