Code style changed, ext-user continued:
[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), chr(10), 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), chr(10)), 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 escaped 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                 // Prepare the string here
311                 $str = SQL_PREPARE_SQL_STRING($str);
312
313                 // Secure string first? (which is the default behaviour!)
314                 if ($secureString === TRUE) {
315                         // Then do it here
316                         $str = secureString($str, $strip);
317                 } // END - if
318
319                 if (!SQL_IS_LINK_UP()) {
320                         // Fall-back to escapeQuotes() when there is no link
321                         $ret = escapeQuotes($str);
322                 } elseif (function_exists('mysql_real_escape_string')) {
323                         // The new and improved version
324                         $ret = mysql_real_escape_string($str, SQL_GET_LINK());
325                 } elseif (function_exists('mysql_escape_string')) {
326                         // The obsolete function
327                         $ret = mysql_escape_string($str, SQL_GET_LINK());
328                 } else {
329                         // If nothing else works, fall back to escapeQuotes() again
330                         $ret = escapeQuotes($str);
331                 }
332
333                 // Cache result
334                 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
335         } // END - if
336
337         // Return it
338         return $GLOBALS['sql_escapes']['' . $str . ''];
339 }
340
341 // SELECT query string from table, columns and so on... ;-)
342 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
343         // Is columns an array?
344         if (!is_array($columns)) {
345                 // No array
346                 reportBug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
347                         gettype($columns),
348                         basename($F),
349                         $L
350                 ));
351
352                 // Abort here with 'false'
353                 return FALSE;
354         } // END  - if
355
356         // Is this is a simple array?
357         if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
358                 // Begin with SQL query
359                 $sql = 'SELECT ';
360
361                 // No, it comes from XML, so get it back from it
362                 $sql .= getSqlPartFromXmlArray($columns);
363
364                 // Finalize it
365                 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
366         } else {
367                 // Yes, prepare the SQL statement
368                 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
369         }
370
371         // Return the result
372         return SQL_QUERY_ESC($sql,
373                 array(
374                         $table,
375                         $idRow,
376                         bigintval($id),
377                 ), $F, $L
378         );
379 }
380
381 // ALTER TABLE wrapper function
382 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = TRUE) {
383         // Abort if link is down
384         if (!SQL_IS_LINK_UP()) return FALSE;
385
386         // This is the default result...
387         $result = FALSE;
388
389         // Determine index/fulltext/unique word
390         $isAlterIndex = (
391                 (
392                         isInString('INDEX', $sql)
393                 ) || (
394                         isInString('KEY', $sql)
395                 ) || (
396                         isInString('FULLTEXT', $sql)
397                 ) || (
398                         isInString('UNIQUE', $sql)
399                 )
400         );
401
402         // Extract table name
403         $tableArray = explode(' ', $sql);
404         $tableName = str_replace('`', '', $tableArray[2]);
405
406         // Debug log
407         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
408
409         // Shall we add/drop?
410         if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
411                 // Try two columns, one should fix
412                 foreach (array(4,5) as $idx) {
413                         // If an entry is not set, abort here
414                         if (!isset($tableArray[$idx])) {
415                                 // Debug log this
416                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
417                                 break;
418                         } // END - if
419
420                         // And column name as well
421                         $columnName = $tableArray[$idx];
422
423                         // Debug log
424                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlColumnExists($tableName, $columnName)));
425
426                         // Is there no entry on ADD or an entry on DROP/CHANGE?
427                         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])))))) {
428                                 // Do the query
429                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
430                                 $result = SQL_QUERY($sql, $F, $L, FALSE);
431
432                                 // Skip further attempt(s)
433                                 break;
434                         } elseif ((((ifSqlColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
435                                 // Abort here because it is alreay there
436                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
437                                 break;
438                         } elseif ((!ifSqlColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
439                                 // Abort here because we tried to drop a column which is not there (never created maybe)
440                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
441                                 break;
442                         } elseif ($columnName != 'KEY') {
443                                 // Something didn't fit, we better log it
444                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlColumnExists($tableName, $columnName)) . '');
445                         }
446                 } // END - foreach
447         } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
448                 // Skip this query silently because InnoDB does not understand fulltext indexes
449                 //* 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));
450         } elseif ($isAlterIndex === TRUE) {
451                 // And column name as well without backticks
452                 $keyName = str_replace('`', '', $tableArray[5]);
453                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
454
455                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
456                 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
457                         // Init loop
458                         $begin = 1;
459                         $keyName = ',';
460                         while (isInString(',', $keyName)) {
461                                 // Use last
462                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
463                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
464                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
465
466                                 // Remove brackes
467                                 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
468                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
469
470                                 // Continue
471                                 $begin++;
472                         } // END while
473                 } // END - if
474
475                 // Shall we run it?
476                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
477                 if (($tableArray[3] == 'ADD') && (!isSqlTableIndexFound($tableName, $keyName))) {
478                         // Send it to the SQL_QUERY() function to add it
479                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
480                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
481                 } elseif (($tableArray[3] == 'DROP') && (isSqlTableIndexFound($tableName, $keyName))) {
482                         // Send it to the SQL_QUERY() function to drop it
483                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
484                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
485                 } else {
486                         // Not executed
487                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
488                 }
489         } else {
490                 // Other ALTER TABLE query
491                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
492                 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
493         }
494
495         // Return result
496         return $result;
497 }
498
499 // Getter for SQL link
500 function SQL_GET_LINK () {
501         // Init link
502         $link = NULL;
503
504         // Is it in the globals?
505         if (isset($GLOBALS['sql_link'])) {
506                 // Then take it
507                 $link = $GLOBALS['sql_link'];
508         } // END - if
509
510         // Return it
511         return $link;
512 }
513
514 // Setter for link
515 function SQL_SET_LINK ($link) {
516         // Is this a resource or null?
517         if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
518                 // This may happen in installation phase
519                 return;
520         } elseif ((!is_resource($link)) && (!is_null($link))) {
521                 // This should never happen!
522                 reportBug(__FUNCTION__, __LINE__, sprintf("Type of link is not resource or null, type=%s", gettype($link)));
523         } // END - if
524
525         // Set it
526         $GLOBALS['sql_link'] = $link;
527
528         // Re-init cache
529         $GLOBALS['is_sql_link_up'] = is_resource($link);
530 }
531
532 // Checks if the link is up
533 function SQL_IS_LINK_UP () {
534         // Is there cached this?
535         if (!isset($GLOBALS['is_sql_link_up'])) {
536                 // Determine it
537                 $GLOBALS['is_sql_link_up'] = is_resource(SQL_GET_LINK());
538         } // END - if
539
540         // Return the result
541         return $GLOBALS['is_sql_link_up'];
542 }
543
544 // Wrapper function to make code more readable
545 function SQL_HASZERONUMS ($result) {
546         // Just pass it through
547         return (SQL_NUMROWS($result) === 0);
548 }
549
550 // Wrapper function to make code more readable
551 function SQL_HASZEROAFFECTED () {
552         // Just pass it through
553         return (SQL_AFFECTEDROWS() === 0);
554 }
555
556 // Private function to prepare the SQL query string
557 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = TRUE) {
558         // Is it already cached?
559         if (!isset($GLOBALS['sql_strings'][$sqlString])) {
560                 // Compile URI codes+config+expression code
561                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG(compileUriCode($sqlString)));
562
563                 // Do final compilation
564                 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
565         } // END - if
566
567         // Return it
568         return $GLOBALS['sql_strings'][$sqlString];
569 }
570
571 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
572 function SQL_EPOCHE_TO_TIMESTAMP ($timestamp) {
573         return generateDateTime($timestamp, 7);
574 }
575
576 // Log SQL errors to debug.log in installation phase or call reportBug()
577 function SQL_ERROR ($file, $line, $message) {
578         // Remember plain error in last_sql_error
579         $GLOBALS['last_sql_error'] = mysql_error();
580
581         // Is there installation phase?
582         if (isInstallationPhase()) {
583                 /*
584                  * In installation phase, we don't want SQL errors abort e.g. connection
585                  * tests, so just log it away.
586                  */
587                 logDebugMessage($file, $line, $message);
588         } else {
589                 // Regular mode, then call reportBug()
590                 reportBug($file, $line, $message);
591         }
592 }
593
594 // Check if there is a SQL table created
595 function ifSqlTableExists ($tableName) {
596         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
597         // Is there cache?
598         if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
599                 // Check if the table is there
600                 $result = SQL_QUERY_ESC("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
601                         array($tableName), __FILE__, __LINE__);
602
603                 // Is there an entry?
604                 $GLOBALS[__FUNCTION__][$tableName] = (SQL_NUMROWS($result) == 1);
605                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
606         } // END - if
607
608         // Return cache
609         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
610         return $GLOBALS[__FUNCTION__][$tableName];
611 }
612
613 // Is a table column there?
614 function ifSqlColumnExists ($tableName, $columnName) {
615         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
616         // Is there cache?
617         if (!isset($GLOBALS[__FUNCTION__][$tableName][$columnName])) {
618                 // And column name as well
619                 $columnName = str_replace('`', '', $columnName);
620
621                 // Get column information
622                 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
623                         array(
624                                 $tableName,
625                                 $columnName
626                         ), __FUNCTION__, __LINE__);
627
628                 // Determine it
629                 $GLOBALS[__FUNCTION__][$tableName][$columnName] = (!SQL_HASZERONUMS($result));
630                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)) . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]));
631
632                 // Free result
633                 SQL_FREERESULT($result);
634         } // END - if
635
636         // Return cache
637         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]) . ' - EXIT!');
638         return $GLOBALS[__FUNCTION__][$tableName][$columnName];
639 }
640
641 // Checks depending on the mode if the index is there
642 function isSqlTableIndexFound ($tableName, $keyName) {
643         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ' - ENTERED!');
644         // Is there cache?
645         if (!isset($GLOBALS[__FUNCTION__][$tableName][$keyName])) {
646                 // Show indexes
647                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
648
649                 // The column is not found by default
650                 $GLOBALS[__FUNCTION__][$tableName][$keyName] = FALSE;
651
652                 // Walk through all
653                 while ($content = SQL_FETCHARRAY($result)) {
654                         // Add all entries for better caching behavior
655                         $GLOBALS[__FUNCTION__][$tableName][$content['Key_name']] = TRUE;
656                 } // END - while
657
658                 // Free result
659                 SQL_FREERESULT($result);
660         } else {
661                 // Cache used
662                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$keyName]) . ' - CACHE!');
663         } // END - if
664
665         // Return cache
666         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$keyName]) . ' - EXIT!');
667         return $GLOBALS[__FUNCTION__][$tableName][$keyName];
668 }
669
670 // Init database layer
671 function initDatabaseLayer () {
672         // Set all required variables:
673         $GLOBALS['last_sql_error'] = '';
674 }
675
676 // Get last SQL error
677 function getLastSqlError () {
678         return $GLOBALS['last_sql_error'];
679 }
680
681 // Gets an array (or false if none is found) from all supported engines
682 function getArrayFromSupportedSqlEngines ($support = 'YES') {
683         // Init array
684         $engines = array();
685
686         // This also worked, now we need to check if the selected database type is supported
687         $result = SQL_QUERY('SHOW ENGINES', __FUNCTION__, __LINE__);
688
689         // Are there entries? (Bad if not)
690         if (SQL_NUMROWS($result) > 0) {
691                 // Load all and check for active entries
692                 while ($content = SQL_FETCHARRAY($result)) {
693                         // Is this supported?
694                         if (($support == 'ALL') || ($content['Support'] == $support)) {
695                                 // Add it
696                                 array_push($engines, $content);
697                         } elseif (isDebugModeEnabled()) {
698                                 // Log it away in debug mode
699                                 logDebugMessage(__FUNCTION__, __LINE__, 'Engine ' . $content['Engine'] . ' is not supported (' . $content['Supported'] . ')');
700                         }
701                 } // END - if
702         } else {
703                 // No engines! :(
704                 $engines = FALSE;
705         }
706
707         // Free result
708         SQL_FREERESULT($result);
709
710         // Return result
711         return $engines;
712 }
713
714 // [EOF]
715 ?>