New wrapper functions introduced
[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  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
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.                                  *
28  *                                                                      *
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.                         *
33  *                                                                      *
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,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // SQL queries
46 function SQL_QUERY ($sqlString, $F, $L, $enableCodes = true) {
47         // Trim SQL string
48         $sqlString = trim($sqlString);
49
50         // Link is up?
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",
54                         $sqlString,
55                         basename($F),
56                         $L
57                 ));
58
59                 // Return 'false' because it has failed
60                 return false;
61         } elseif (empty($sqlString)) {
62                 // Empty SQL string!
63                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
64                         basename($F),
65                         $L
66                 ));
67
68                 // This is invalid, of course
69                 return false;
70         }
71
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)));
74
75         // Compile config entries out
76         $GLOBALS['last_sql'] = SQL_PREPARE_SQL_STRING($sqlString, $enableCodes);
77
78         // Starting time
79         $querytimeBefore = microtime(true);
80
81         // Run SQL command
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());
87
88         // Calculate query time
89         $queryTime = microtime(true) - $querytimeBefore;
90
91         // Add this query to array including timing
92         addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
93
94         // Save last successfull query
95         setConfigEntry('db_last_query', $GLOBALS['last_sql']);
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 ((!isCssOutputMode()) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
105                 //
106                 // Debugging stuff...
107                 //
108                 $fp = fopen(getCachePath() . 'mysql.log', 'a') or debug_report_bug(__FUNCTION__, __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", ' ', $GLOBALS['last_sql'])) . "\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 ($resource) {
133         // Valid link resource?
134         if (!SQL_IS_LINK_UP()) return false;
135
136         // Link is not up, no rows by default
137         $lines = false;
138
139         // Is the result a valid resource?
140         if (is_resource($resource)) {
141                 // Get the count of rows from database
142                 $lines = mysql_num_rows($resource);
143         } else {
144                 // No resource given, please fix this
145                 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' .  $GLOBALS['last_sql']);
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 ($resource) {
166         // Is a result resource set?
167         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
168
169         // Fetch the data and return it
170         return mysql_fetch_row($resource);
171 }
172
173 // SQL fetch array
174 function SQL_FETCHARRAY ($res, $nr=0) {
175         // Is a result resource set?
176         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
177
178         // Load row from database
179         $row = mysql_fetch_assoc($res);
180
181         // Return only arrays here
182         if (is_array($row)) {
183                 // Return row
184                 return $row;
185         } else {
186                 // Return a false, else some loops would go endless...
187                 return false;
188         }
189 }
190
191 // SQL result
192 function SQL_RESULT ($resource, $row, $field = '0') {
193         // Is $resource valid?
194         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
195
196         // Run the result command
197         $result = mysql_result($resource, $row, $field);
198
199         // ... and return the result
200         return $result;
201 }
202
203 // SQL connect
204 function SQL_CONNECT ($host, $login, $password, $F, $L) {
205         // Try to connect
206         $linkResource = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
207
208         // Set the link resource
209         SQL_SET_LINK($linkResource);
210
211         // Destroy cache
212         unset($GLOBALS['is_sql_link_up']);
213 }
214
215 // SQL select database
216 function SQL_SELECT_DB ($dbName, $F, $L) {
217         // Is there still a valid link? If not, skip it.
218         if (!SQL_IS_LINK_UP()) return false;
219
220         // Return the result
221         return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
222 }
223
224 // SQL close link
225 function SQL_CLOSE ($F, $L) {
226         if (!SQL_IS_LINK_UP()) {
227                 // Skip double close
228                 return false;
229         } // END - if
230
231         // Close database link and forget the link
232         $close = mysql_close(SQL_GET_LINK())
233                 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
234
235         // Close link
236         SQL_SET_LINK(null);
237
238         // Destroy cache
239         unset($GLOBALS['is_sql_link_up']);
240
241         // Return the result
242         return $close;
243 }
244
245 // SQL free result
246 function SQL_FREERESULT ($resource) {
247         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
248                 // Abort here
249                 return false;
250         } // END - if
251
252         // Free result
253         $res = mysql_free_result($resource);
254
255         // And return that result of freeing it...
256         return $res;
257 }
258
259 // SQL string escaping
260 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
261         // Link is there?
262         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
263
264         // Escape all data
265         $dataSecured['__sql_string'] = $sqlString;
266         foreach ($data as $key => $value) {
267                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
268         } // END - foreach
269
270         // Generate query
271         $query = call_user_func_array('sprintf', $dataSecured);
272
273         // Debugging
274         //
275         //* DEBUG: */ $fp = fopen(getCachePath() . 'escape_debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write debug.log!');
276         //* DEBUG: */ fwrite($fp, $F . '(' . $L . '): ' . str_replace("\r", '', str_replace("\n", ' ', $eval)) . "\n");
277         //* DEBUG: */ fclose($fp);
278
279         if ($run === true) {
280                 // Run SQL query (default)
281                 return SQL_QUERY($query, $F, $L);
282         } else {
283                 // Return secured string
284                 return $query;
285         }
286 }
287
288 // Get id from last INSERT command
289 function SQL_INSERTID () {
290         if (!SQL_IS_LINK_UP()) return false;
291         return mysql_insert_id();
292 }
293
294 // Escape a string for the database
295 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
296         // Do we have cache?
297         if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
298                 // Secure string first? (which is the default behaviour!)
299                 if ($secureString === true) {
300                         // Then do it here
301                         $str = secureString($str, $strip);
302                 } // END - if
303
304                 if (!SQL_IS_LINK_UP()) {
305                         // Fall-back to escapeQuotes() when there is no link
306                         $ret = escapeQuotes($str);
307                 } elseif (function_exists('mysql_real_escape_string')) {
308                         // The new and improved version
309                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
310                         $ret = mysql_real_escape_string($str, SQL_GET_LINK());
311                 } elseif (function_exists('mysql_escape_string')) {
312                         // The obsolete function
313                         $ret = mysql_escape_string($str, SQL_GET_LINK());
314                 } else {
315                         // If nothing else works, fall back to escapeQuotes() again
316                         $ret = escapeQuotes($str);
317                 }
318
319                 // Cache result
320                 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
321         } // END - if
322
323         // Return it
324         return $GLOBALS['sql_escapes'][''.$str.''];
325 }
326
327 // SELECT query string from table, columns and so on... ;-)
328 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
329         // Is columns an array?
330         if (!is_array($columns)) {
331                 // No array
332                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
333                         gettype($columns),
334                         basename($F),
335                         $L
336                 ));
337
338                 // Abort here with 'false'
339                 return false;
340         } // END  - if
341
342         // Prepare the SQL statement
343         $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
344
345         // Return the result
346         return SQL_QUERY_ESC($sql,
347                 array(
348                         $table,
349                         $idRow,
350                         bigintval($id),
351                 ), $F, $L
352         );
353 }
354
355 // ALTER TABLE wrapper function
356 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = true) {
357         // Abort if link is down
358         if (!SQL_IS_LINK_UP()) return false;
359
360         // This is the default result...
361         $result = false;
362
363         // Determine index/fulltext/unique word
364         $noIndex = (
365         (
366                 strpos($sql, 'INDEX') === false
367         ) && (
368                 strpos($sql, 'KEY') === false
369         ) && (
370                 strpos($sql, 'FULLTEXT') === false
371         ) && (
372                 strpos($sql, 'UNIQUE') === false
373         )
374         );
375
376         // Extract table name
377         $tableArray = explode(' ', $sql);
378         $tableName = str_replace('`', '', $tableArray[2]);
379
380         // Shall we add/drop?
381         if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
382                 // Try two columns, one should fix
383                 foreach (array(4,5) as $idx) {
384                         // And column name as well
385                         $columnName = str_replace('`', '', $tableArray[$idx]);
386
387                         // Get column information
388                         $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
389                                 array($tableName, $columnName), __FUNCTION__, __LINE__);
390
391                         // Do we have no entry on ADD or an entry on DROP?
392                         // 123           4       4     3    3      4           4          32    23           4       4     3    3      4            4          321
393                         if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
394                                 // Do the query
395                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
396                                 $result = SQL_QUERY($sql, $F, $L, false);
397
398                                 // Skip further attempt(s)
399                                 break;
400                         } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
401                                 // Abort here because it is alreay there
402                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
403                                 break;
404                         } elseif ($columnName != 'KEY') {
405                                 // Something didn't fit
406                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
407                         }
408                 } // END - foreach
409         } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
410                 // Skip this query silently
411                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
412         } elseif ($noIndex === false) {
413                 // And column name as well
414                 //* DEBUG: */ debugOutput(__LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
415                 $keyName = str_replace('`', '', $tableArray[5]);
416
417                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
418                 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
419                         // Init loop
420                         $begin = 1; $keyName = ',';
421                         while (strpos($keyName, ',') !== false) {
422                                 // Use last
423                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
424                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
425
426                                 // Remove brackes
427                                 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
428                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
429
430                                 // Continue
431                                 $begin++;
432                         } // END while
433                 } // END - if
434
435                 // Show indexes
436                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
437
438                 // Non-skipping is default for ADD
439                 $skip = false;
440
441                 // But should we DROP?
442                 if ($tableArray[3] == 'DROP') {
443                         // Then skip if nothing found!
444                         $skip = true;
445                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
446                 } // END - if
447
448                 // Walk through all
449                 while ($content = SQL_FETCHARRAY($result)) {
450                         // Is it found?
451                         //* DEBUG: */ debugOutput(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
452                         if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
453                                 // Skip this query!
454                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
455                                 $skip = true;
456                                 break;
457                         } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
458                                 // Don't skip this!
459                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
460                                 $skip = false;
461                                 break;
462                         }
463                 } // END - while
464
465                 // Free result
466                 SQL_FREERESULT($result);
467
468                 // Shall we run it?
469                 if ($skip === false) {
470                         // Send it to the SQL_QUERY() function
471                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
472                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
473                 } else {
474                         // Not executed
475                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
476                 }
477         } else {
478                 // Other ALTER TABLE query
479                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
480                 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
481         }
482
483         // Return result
484         return $result;
485 }
486
487 // Getter for SQL link
488 function SQL_GET_LINK () {
489         // Init link
490         $link = null;
491
492         // Is it in the globals?
493         if (isset($GLOBALS['sql_link'])) {
494                 // Then take it
495                 $link = $GLOBALS['sql_link'];
496         } // END - if
497
498         // Return it
499         return $link;
500 }
501
502 // Setter for link
503 function SQL_SET_LINK ($link) {
504         // Is this a resource or null?
505         if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
506                 // This may happen in installation phase
507                 return;
508         } elseif ((!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)));
511         } // END - if
512
513         // Set it
514         $GLOBALS['sql_link'] = $link;
515 }
516
517 // Checks if the link is up
518 function SQL_IS_LINK_UP () {
519         // Default is not up
520         $linkUp = false;
521
522         // Do we have cached this?
523         if (isset($GLOBALS['is_sql_link_up'])) {
524                 // Then use this
525                 $linkUp = $GLOBALS['is_sql_link_up'];
526         } else {
527                 // Get it
528                 $linkUp = is_resource(SQL_GET_LINK());
529
530                 // And cache it
531                 $GLOBALS['is_sql_link_up'] = $linkUp;
532         }
533
534         // Return the result
535         return $linkUp;
536 }
537
538 // Wrapper function to make code more readable
539 function SQL_HASZERONUMS ($result) {
540         // Just pass it through
541         return (SQL_NUMROWS($result) === 0);
542 }
543
544 // Private function to prepare the SQL query string
545 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
546         // Is it already cached?
547         if (!isset($GLOBALS['sql_strings'][$sqlString])) {
548                 // Compile config+expression code
549                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
550
551                 // Do final compilation
552                 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
553                 //die($sqlString.'<br />'.$sqlString2.'<br />'.$GLOBALS['sql_strings'][$sqlString]);
554         } // END - if
555
556         // Return it
557         return $GLOBALS['sql_strings'][$sqlString];
558 }
559
560 // [EOF]
561 ?>