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