Some more rewrites to better functions
[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/4/5 server            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Datenbankschicht fuer MySQL 3/4/5 Server         *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // SQL queries
44 function SQL_QUERY ($sqlString, $F, $L, $enableCodes = TRUE) {
45         // Is there cache?
46         if (!isset($GLOBALS[__FUNCTION__][$sqlString])) {
47                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called: ' . $sqlString);
48
49                 // Trim SQL string
50                 $sqlStringModified = trim($sqlString);
51
52                 // Empty query string or link is not up?
53                 if (empty($sqlStringModified)) {
54                         // Empty SQL string!
55                         reportBug(__FUNCTION__, __LINE__, sprintf("SQL string is empty, please fix this: file=%s, line=%s",
56                                 basename($F),
57                                 $L
58                         ));
59                 } elseif (!SQL_IS_LINK_UP()) {
60                         // We should not quietly ignore this
61                         reportBug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
62                                 $sqlStringModified,
63                                 basename($F),
64                                 $L
65                         ));
66                 }
67
68                 // Remove \t, \n and \r from queries they may confuse some MySQL versions
69                 $sqlStringModified = str_replace(array(chr(9), PHP_EOL, chr(13)), array(' ', ' ', ' '), $sqlStringModified);
70
71                 // Compile config entries out
72                 $sqlStringModified = SQL_PREPARE_SQL_STRING($sqlStringModified, $enableCodes);
73
74                 // Cache it and remember as last SQL query
75                 $GLOBALS[__FUNCTION__][$sqlString] = $sqlStringModified;
76                 $GLOBALS['last_sql']               = $sqlStringModified;
77                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Stored cache: ' . $sqlStringModified);
78         }  else {
79                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
80
81                 // Use cache (to save a lot function calls
82                 $GLOBALS['last_sql'] = $GLOBALS[__FUNCTION__][$sqlString];
83
84                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache is: ' . $sqlString);
85         }
86
87         // Starting time
88         $querytimeBefore = microtime(TRUE);
89
90         // Run SQL command
91         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
92         $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
93                 or SQL_ERROR($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . ',last_query=' . $GLOBALS['last_sql']);
94         //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
95
96         // Calculate query time
97         $queryTime = microtime(TRUE) - $querytimeBefore;
98
99         // Add this query to array including timing
100         addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
101
102         // Save last successfull query
103         setConfigEntry('db_last_query', $GLOBALS['last_sql']);
104
105         // Count all query times
106         incrementConfigEntry('sql_time', $queryTime);
107
108         // Count this query
109         incrementConfigEntry('sql_count');
110
111         // Debug output
112         if (SQL_DEBUG_ENABLED()) {
113                 // Is this the first call?
114                 if (!isset($GLOBALS['sql_first_entry'])) {
115                         // Write first entry
116                         appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
117                         $GLOBALS['sql_first_entry'] = TRUE;
118                 } // END - if
119
120                 // Append debug line
121                 appendLineToFile(getCachePath() . 'mysql.log', basename($F) . '|LINE=' . $L . '|NUM=' . (is_resource($result) ? SQL_NUMROWS($result) : 'false') . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . ($queryTime * 1000) . 'ms): ' . str_replace(array(chr(13), PHP_EOL), array('', ' '), $GLOBALS['last_sql']));
122         } // END - if
123
124         // Increment stats entry
125         incrementStatsEntry('db_hits');
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 (isset($GLOBALS['sql_numrows'][intval($resource)])) {
141                 // Use cache
142                 $lines = $GLOBALS['sql_numrows'][intval($resource)];
143         } elseif (is_resource($resource)) {
144                 // Get the count of rows from database
145                 $lines = mysql_num_rows($resource);
146
147                 // Remember it in cache
148                 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
149         } else {
150                 // No resource given, please fix this
151                 reportBug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' .  $GLOBALS['last_sql']);
152         }
153
154         // Return lines
155         return $lines;
156 }
157
158 // SQL affected rows
159 function SQL_AFFECTEDROWS() {
160         // Valid link resource?
161         if (!SQL_IS_LINK_UP()) return FALSE;
162
163         // Get affected rows
164         $lines = mysql_affected_rows(SQL_GET_LINK());
165
166         // Return it
167         return $lines;
168 }
169
170 // SQL fetch row
171 function SQL_FETCHROW ($resource) {
172         // Is a result resource set?
173         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
174
175         // Fetch the data and return it
176         return mysql_fetch_row($resource);
177 }
178
179 // SQL fetch array
180 function SQL_FETCHARRAY ($resource) {
181         // Is a result resource set?
182         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
183
184         // Load row from database
185         $row = mysql_fetch_assoc($resource);
186
187         // Return only arrays here
188         if (is_array($row)) {
189                 // Return row
190                 return $row;
191         } else {
192                 // Return a false, else some loops would go endless...
193                 return FALSE;
194         }
195 }
196
197 // SQL result
198 function SQL_RESULT ($resource, $row, $field = '0') {
199         // Is $resource valid?
200         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
201
202         // Run the result command
203         $result = mysql_result($resource, $row, $field);
204
205         // ... and return the result
206         return $result;
207 }
208
209 // SQL connect
210 function SQL_CONNECT ($host, $login, $password, $F, $L) {
211         // Try to connect
212         $linkResource = mysql_connect($host, $login, $password) or SQL_ERROR($F, $L,  mysql_error());
213
214         // Set the link resource
215         if (is_resource($linkResource)) {
216                 /*
217                  * A non-resource (boolean) may happen on installation phase which
218                  * shall not be set here. Only valid link resources shall be set so
219                  * SQL_IS_LINK_UP() will only return 'true' if there is really a
220                  * working database link.
221                  */
222                 SQL_SET_LINK($linkResource);
223         } // END - if
224
225         // Return the resource
226         return $linkResource;
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 SQL_ERROR($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()) or SQL_ERROR($F, $L, mysql_error());
247
248         // Close link
249         SQL_SET_LINK(NULL);
250
251         // Return the result
252         return $close;
253 }
254
255 // SQL free result
256 function SQL_FREERESULT ($resource) {
257         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
258                 // Abort here
259                 return FALSE;
260         } // END - if
261
262         // Free result
263         $res = mysql_free_result($resource);
264
265         // And return that result of freeing it...
266         return $res;
267 }
268
269 // SQL string escaping
270 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = TRUE, $strip = TRUE, $secure = TRUE) {
271         // Link is there?
272         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) {
273                 // Link is down or data is not an array
274                 /* DEBUG: */ logDebugMessage($F, $L, 'SQL_IS_LINK_UP()=' . intval(SQL_IS_LINK_UP()) . ',data[]=' . gettype($data) . ',sqlString=' . $sqlString . ': ABORTING!');
275                 return FALSE;
276         } // END - if
277
278         // Init array for escape'd data with SQL string
279         $dataSecured = array(
280                 '__sql_string' => $sqlString
281         );
282
283         // Escape all data
284         foreach ($data as $key => $value) {
285                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
286         } // END - foreach
287
288         // Generate query
289         $query = call_user_func_array('sprintf', $dataSecured);
290
291         if ($run === TRUE) {
292                 // Run SQL query (default)
293                 return SQL_QUERY($query, $F, $L);
294         } else {
295                 // Return secured string
296                 return $query;
297         }
298 }
299
300 // Get id from last INSERT command
301 function SQL_INSERTID () {
302         if (!SQL_IS_LINK_UP()) return FALSE;
303         return mysql_insert_id();
304 }
305
306 // Escape a string for the database
307 function SQL_ESCAPE ($str, $secureString = TRUE, $strip = TRUE) {
308         // Is there cache?
309         if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
310                 // Debug message
311                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
312
313                 // Prepare the string here
314                 $str = SQL_PREPARE_SQL_STRING($str);
315
316                 // Debug message
317                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
318
319                 // Secure string first? (which is the default behaviour!)
320                 if ($secureString === TRUE) {
321                         // Debug message
322                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - BEFORE!');
323
324                         // Then do it here
325                         $str = secureString($str, $strip);
326
327                         // Debug message
328                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - AFTER!');
329                 } // END - if
330
331                 // Init (invalid) value
332                 $ret = '!INVALID!';
333
334                 if (!SQL_IS_LINK_UP()) {
335                         // Fall-back to escapeQuotes() when there is no link
336                         $ret = escapeQuotes($str);
337                 } elseif (function_exists('mysql_real_escape_string')) {
338                         // Debug message
339                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
340
341                         // The new and improved version
342                         $ret = mysql_real_escape_string($str, SQL_GET_LINK());
343
344                         // Debug message
345                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
346                 } elseif (function_exists('mysql_escape_string')) {
347                         // The obsolete function
348                         $ret = mysql_escape_string($str, SQL_GET_LINK());
349                 } else {
350                         // If nothing else works, fall back to escapeQuotes() again
351                         $ret = escapeQuotes($str);
352                 }
353
354                 // Log message
355                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
356
357                 // Cache result
358                 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
359         } // END - if
360
361         // Log message
362         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',sql_escapes=' . $GLOBALS['sql_escapes']['' . $str . '']);
363
364         // Return it
365         return $GLOBALS['sql_escapes']['' . $str . ''];
366 }
367
368 // SELECT query string from table, columns and so on... ;-)
369 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
370         // Is columns an array?
371         if (!is_array($columns)) {
372                 // No array
373                 reportBug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
374                         gettype($columns),
375                         basename($F),
376                         $L
377                 ));
378
379                 // Abort here with 'false'
380                 return FALSE;
381         } // END  - if
382
383         // Is this is a simple array?
384         if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
385                 // Begin with SQL query
386                 $sql = 'SELECT ';
387
388                 // No, it comes from XML, so get it back from it
389                 $sql .= getSqlPartFromXmlArray($columns);
390
391                 // Finalize it
392                 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
393         } else {
394                 // Yes, prepare the SQL statement
395                 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
396         }
397
398         // Return the result
399         return SQL_QUERY_ESC($sql,
400                 array(
401                         $table,
402                         $idRow,
403                         bigintval($id),
404                 ), $F, $L
405         );
406 }
407
408 // ALTER TABLE wrapper function
409 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = TRUE) {
410         // Abort if link is down
411         if (!SQL_IS_LINK_UP()) return FALSE;
412
413         // This is the default result...
414         $result = FALSE;
415
416         // Determine index/fulltext/unique word
417         $isAlterIndex = (
418                 (
419                         isInString('INDEX', $sql)
420                 ) || (
421                         isInString('KEY', $sql)
422                 ) || (
423                         isInString('FULLTEXT', $sql)
424                 ) || (
425                         isInString('UNIQUE', $sql)
426                 )
427         );
428
429         // Extract table name
430         $tableArray = explode(' ', $sql);
431         $tableName = str_replace('`', '', $tableArray[2]);
432
433         // Debug log
434         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
435
436         // Shall we add/drop?
437         if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
438                 // Try two columns, one should fix
439                 foreach (array(4,5) as $idx) {
440                         // If an entry is not set, abort here
441                         if (!isset($tableArray[$idx])) {
442                                 // Debug log this
443                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
444                                 break;
445                         } // END - if
446
447                         // And column name as well
448                         $columnName = $tableArray[$idx];
449
450                         // Debug log
451                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlColumnExists($tableName, $columnName)));
452
453                         // Is there no entry on ADD or an entry on DROP/CHANGE?
454                         if (((!ifSqlColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((ifSqlColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql)) || ((isInString('CHANGE', $sql)) && ($idx == 4) && ((!ifSqlColumnExists($tableName, $tableArray[5])) || ($columnName == $tableArray[5])))))) {
455                                 // Do the query
456                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
457                                 $result = SQL_QUERY($sql, $F, $L, FALSE);
458
459                                 // Skip further attempt(s)
460                                 break;
461                         } elseif ((((ifSqlColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
462                                 // Abort here because it is alreay there
463                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
464                                 break;
465                         } elseif ((!ifSqlColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
466                                 // Abort here because we tried to drop a column which is not there (never created maybe)
467                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
468                                 break;
469                         } elseif ($columnName != 'KEY') {
470                                 // Something didn't fit, we better log it
471                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlColumnExists($tableName, $columnName)) . '');
472                         }
473                 } // END - foreach
474         } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
475                 // Skip this query silently because InnoDB does not understand fulltext indexes
476                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s", $sql, $tableName, intval((is_bool($result)) ? 0 : ifSqlColumnExists($columnName)), $F, $L));
477         } elseif ($isAlterIndex === TRUE) {
478                 // And column name as well without backticks
479                 $keyName = str_replace('`', '', $tableArray[5]);
480                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
481
482                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
483                 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
484                         // Init loop
485                         $begin = 1;
486                         $keyName = ',';
487                         while (isInString(',', $keyName)) {
488                                 // Use last
489                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
490                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
491                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
492
493                                 // Remove brackes
494                                 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
495                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
496
497                                 // Continue
498                                 $begin++;
499                         } // END while
500                 } // END - if
501
502                 // Shall we run it?
503                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
504                 if (($tableArray[3] == 'ADD') && (!ifSqlTableIndexExist($tableName, $keyName))) {
505                         // Send it to the SQL_QUERY() function to add it
506                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
507                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
508                 } elseif (($tableArray[3] == 'DROP') && (ifSqlTableIndexExist($tableName, $keyName))) {
509                         // Send it to the SQL_QUERY() function to drop it
510                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
511                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
512                 } else {
513                         // Not executed
514                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
515                 }
516         } else {
517                 // Other ALTER TABLE query
518                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
519                 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
520         }
521
522         // Return result
523         return $result;
524 }
525
526 // Getter for SQL link
527 function SQL_GET_LINK () {
528         // Init link
529         $link = NULL;
530
531         // Is it in the globals?
532         if (isset($GLOBALS['sql_link'])) {
533                 // Then take it
534                 $link = $GLOBALS['sql_link'];
535         } // END - if
536
537         // Return it
538         return $link;
539 }
540
541 // Setter for link
542 function SQL_SET_LINK ($link) {
543         // Is this a resource or null?
544         if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
545                 // This may happen in installation phase
546                 return;
547         } elseif ((!is_resource($link)) && (!is_null($link))) {
548                 // This should never happen!
549                 reportBug(__FUNCTION__, __LINE__, sprintf("Type of link is not resource or null, type=%s", gettype($link)));
550         } // END - if
551
552         // Set it
553         $GLOBALS['sql_link'] = $link;
554
555         // Re-init cache
556         $GLOBALS['is_sql_link_up'] = is_resource($link);
557 }
558
559 // Checks if the link is up
560 function SQL_IS_LINK_UP () {
561         // Is there cached this?
562         if (!isset($GLOBALS['is_sql_link_up'])) {
563                 // Determine it
564                 $GLOBALS['is_sql_link_up'] = is_resource(SQL_GET_LINK());
565         } // END - if
566
567         // Return the result
568         return $GLOBALS['is_sql_link_up'];
569 }
570
571 // Wrapper function to make code more readable
572 function SQL_HASZERONUMS ($result) {
573         // Just pass it through
574         return (SQL_NUMROWS($result) === 0);
575 }
576
577 // Wrapper function to make code more readable
578 function SQL_HASZEROAFFECTED () {
579         // Just pass it through
580         return (SQL_AFFECTEDROWS() === 0);
581 }
582
583 // Private function to prepare the SQL query string
584 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = TRUE) {
585         // Debug message
586         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ' - ENTERED!');
587
588         // Is it already cached?
589         if (!isset($GLOBALS['sql_strings']['' . $sqlString . ''])) {
590                 // Preserve escaping and compile URI codes+config+expression code
591                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
592
593                 // Debug message
594                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
595
596                 // Do final compilation and revert {ESCAPE}
597                 $GLOBALS['sql_strings']['' . $sqlString . ''] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
598         } else {
599                 // Log message
600                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ' - CACHE!');
601         }
602
603         // Debug message
604         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ',sql_strings=' . $GLOBALS['sql_strings']['' . $sqlString . ''] . ' - EXIT!');
605
606         // Return it
607         return $GLOBALS['sql_strings']['' . $sqlString . ''];
608 }
609
610 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
611 function SQL_EPOCHE_TO_TIMESTAMP ($timestamp) {
612         return generateDateTime($timestamp, 7);
613 }
614
615 // Log SQL errors to debug.log in installation phase or call reportBug()
616 function SQL_ERROR ($file, $line, $message) {
617         // Remember plain error in last_sql_error
618         $GLOBALS['last_sql_error'] = mysql_error();
619
620         // Is there installation phase?
621         if (isInstallationPhase()) {
622                 /*
623                  * In installation phase, we don't want SQL errors abort e.g. connection
624                  * tests, so just log it away.
625                  */
626                 logDebugMessage($file, $line, $message);
627         } else {
628                 // Regular mode, then call reportBug()
629                 reportBug($file, $line, $message);
630         }
631 }
632
633 // Check if there is a SQL table created
634 function ifSqlTableExists ($tableName) {
635         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
636         // Is there cache?
637         if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
638                 // Check if the table is there
639                 $result = SQL_QUERY_ESC("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
640                         array($tableName), __FILE__, __LINE__);
641
642                 // Is a link there?
643                 if (!is_resource($result)) {
644                         // Is installation phase?
645                         if (isInstallationPhase()) {
646                                 // Then silently abort here
647                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ' - Returning FALSE ...');
648                                 return FALSE;
649                         } else {
650                                 // Please report this
651                                 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
652                         }
653                 } // END - if
654
655                 // Is there an entry?
656                 $GLOBALS[__FUNCTION__][$tableName] = (SQL_NUMROWS($result) == 1);
657                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
658         } // END - if
659
660         // Return cache
661         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
662         return $GLOBALS[__FUNCTION__][$tableName];
663 }
664
665 // Is a table column there?
666 function ifSqlColumnExists ($tableName, $columnName) {
667         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
668         // Is there cache?
669         if (!isset($GLOBALS[__FUNCTION__][$tableName][$columnName])) {
670                 // And column name as well
671                 $columnName = str_replace('`', '', $columnName);
672
673                 // If the table is not there, it is okay
674                 if (!ifSqlTableExists($tableName)) {
675                         // Then abort here
676                         return FALSE;
677                 } // END - if
678
679                 // Get column information
680                 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
681                         array(
682                                 $tableName,
683                                 $columnName
684                         ), __FUNCTION__, __LINE__);
685
686                 // Is a link there?
687                 if (!is_resource($result)) {
688                         // Is installation phase?
689                         if (isInstallationPhase()) {
690                                 // Then silently abort here
691                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ',columnName=' . $columnName . ' - Returning FALSE ...');
692                                 return FALSE;
693                         } else {
694                                 // Please report this
695                                 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
696                         }
697                 } // END - if
698
699                 // Determine it
700                 $GLOBALS[__FUNCTION__][$tableName][$columnName] = (!SQL_HASZERONUMS($result));
701                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)) . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]));
702
703                 // Free result
704                 SQL_FREERESULT($result);
705         } // END - if
706
707         // Return cache
708         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]) . ' - EXIT!');
709         return $GLOBALS[__FUNCTION__][$tableName][$columnName];
710 }
711
712 // Checks depending on the mode if the index is there
713 function ifSqlTableIndexExist ($tableName, $keyName) {
714         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ' - ENTERED!');
715         // Is there cache?
716         if (!isset($GLOBALS[__FUNCTION__][$tableName][$keyName])) {
717                 // If the table is not there, it is okay
718                 if (!ifSqlTableExists($tableName)) {
719                         // Then abort here
720                         return FALSE;
721                 } // END - if
722
723                 // Show indexes
724                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
725
726                 // Is a link there?
727                 if (!is_resource($result)) {
728                         // Is installation phase?
729                         if (isInstallationPhase()) {
730                                 // Then silently abort here
731                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ',keyName=' . $keyName . ' - Returning FALSE ...');
732                                 return FALSE;
733                         } else {
734                                 // Please report this
735                                 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
736                         }
737                 } // END - if
738
739                 // The column is not found by default
740                 $GLOBALS[__FUNCTION__][$tableName][$keyName] = FALSE;
741
742                 // Walk through all
743                 while ($content = SQL_FETCHARRAY($result)) {
744                         // Add all entries for better caching behavior
745                         $GLOBALS[__FUNCTION__][$tableName][$content['Key_name']] = TRUE;
746                 } // END - while
747
748                 // Free result
749                 SQL_FREERESULT($result);
750         } else {
751                 // Cache used
752                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$keyName]) . ' - CACHE!');
753         } // END - if
754
755         // Return cache
756         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$keyName]) . ' - EXIT!');
757         return $GLOBALS[__FUNCTION__][$tableName][$keyName];
758 }
759
760 // Init database layer
761 function initDatabaseLayer () {
762         // Set all required variables:
763         $GLOBALS['last_sql_error'] = '';
764 }
765
766 // Get last SQL error
767 function getLastSqlError () {
768         return $GLOBALS['last_sql_error'];
769 }
770
771 // Gets an array (or false if none is found) from all supported engines
772 function getArrayFromSupportedSqlEngines ($requestedEngine = 'ALL') {
773         // Init array
774         $engines = array();
775
776         // This also worked, now we need to check if the selected database type is supported
777         $result = SQL_QUERY('SHOW ENGINES', __FUNCTION__, __LINE__);
778
779         // Are there entries? (Bad if not)
780         if (!SQL_HASZERONUMS($result)) {
781                 // Load all and check for active entries
782                 while ($content = SQL_FETCHARRAY($result)) {
783                         // Debug message
784                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'support=' . $requestedEngine . ',Engine=' . $content['Engine'] . ',Support=' . $content['Support']);
785
786                         // Is this supported?
787                         if ((($requestedEngine == 'ALL') || ($content['Engine'] == $requestedEngine)) && (in_array($content['Support'], array('YES', 'DEFAULT')))) {
788                                 // Add it
789                                 array_push($engines, $content);
790                         } elseif (isDebugModeEnabled()) {
791                                 // Log it away in debug mode
792                                 logDebugMessage(__FUNCTION__, __LINE__, 'Engine ' . $content['Engine'] . ' is not supported (' . $content['Supported'] . ' - ' . $requestedEngine . ')');
793                         }
794                 } // END - if
795         } else {
796                 // No engines! :(
797                 $engines = FALSE;
798         }
799
800         // Free result
801         SQL_FREERESULT($result);
802
803         // Return result
804         return $engines;
805 }
806
807 // [EOF]
808 ?>