More fixes for new installer and script in general :(
[mailer.git] / inc / sql-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/23/2009 *
4  * ===================                          Last change: 10/23/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : sql-functions.php                                *
8  * -------------------------------------------------------------------- *
9  * Short description : SQL functions to handle queries                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : SQL-Funktionen fuer Queries                      *
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 // Init SQLs array
44 function initSqls () {
45         // Init generic array
46         setSqlsArray(array('generic' => array()));
47 }
48
49 // Checks whether the sqls array is initialized
50 function isSqlsInitialized () {
51         return ((isset($GLOBALS['sqls'])) && (is_array($GLOBALS['sqls'])));
52 }
53
54 // Setter for SQLs array
55 function setSqlsArray ($SQLs) {
56         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count()='.count($SQLs));
57         $GLOBALS['sqls'] = (array) $SQLs;
58 }
59
60 // Remover for SQLs array
61 function unsetSqls () {
62         unset($GLOBALS['sqls']);
63 }
64
65 // Getter for SQLs array
66 function getSqls () {
67         return $GLOBALS['sqls'];
68 }
69
70 // Add an SQL to the list
71 function addSql ($sql) {
72         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("sql=%s, count=%d", $sql, countSqls()));
73         array_push($GLOBALS['sqls']['generic'], $sql);
74 }
75
76 // Merge SQLs together
77 function mergeSqls ($SQLs, $type = '') {
78         // Should we merge full array or partial?
79         if (empty($type)) {
80                 // Merge full array (may kill entries)
81                 setSqlsArray(merge_array(getSqls(), $SQLs));
82         } else {
83                 // Merge sub array, so get it
84                 $array = getSqls();
85
86                 // Is the sub array there?
87                 if (isset($array[$type])) {
88                         // Then get it and merge it with the new one
89                         $array[$type] = merge_array($array[$type], $SQLs);
90                 } else {
91                         // Use new array
92                         $array[$type] = $SQLs;
93                 }
94
95                 // Call again..
96                 mergeSqls($array);
97         }
98 }
99
100 // Counter for SQLs array
101 function countSqls () {
102         // Default is false
103         $count = '0';
104
105         // Is the array there?
106         if (isSqlsInitialized()) {
107                 // Then count it
108                 $count = count($GLOBALS['sqls']);
109                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("count=%d", $count));
110         } // END - if
111
112         // Return it
113         return $count;
114 }
115
116 // Checks whether the SQLs array is filled
117 function isSqlsValid () {
118         //* DEBUG: */ debugOutput(__FUNCTION__ . ':' . intval(isSqlsInitialized()) . '/' . countSqls() . '/' . getCurrentExtensionName());
119         return (
120                 (
121                         isSqlsInitialized()
122                 ) && (
123                         countSqls() > 0
124                 )
125         );
126 }
127
128 // Generates an updating SQL query from given array
129 function getUpdateSqlFromArray ($array, $tableName, $whereColumn, $whereData, $excludedFields, $multiDimId = NULL) {
130         // Begin SQL query
131         $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_' . $tableName . '` SET ';
132
133         // Insert all data
134         foreach ($array as $entry => $value) {
135                 // Skip login/id entry
136                 if (in_array($entry, $excludedFields)) {
137                         continue;
138                 } // END - if
139
140                 // Is there a non-string (e.g. number, NULL, SQL function or back-tick at the beginning?
141                 if (is_null($multiDimId)) {
142                         // Handle one-dimensional data
143                         if (is_null($value)) {
144                                 // NULL detected
145                                 $SQL .= '`' . $entry . '`=NULL,';
146                         } elseif ((substr($value, -2, 2) == '()') || (substr($value, 0, 1) == '`')) {
147                                 // SQL function needs no ticks (')
148                                 $SQL .= '`' . $entry . '`=' . SQL_ESCAPE($value) . ',';
149                         } elseif ('' . bigintval($value, TRUE, FALSE) . '' == '' . $value . '')  {
150                                 // No need for ticks (')
151                                 $SQL .= '`' . $entry . '`=' . $value . ',';
152                         } else {
153                                 // Strings need ticks (') around them
154                                 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value) . "',";
155                         }
156                 } else {
157                         // Handle multi-dimensional data
158                         if (is_null($value[$multiDimId])) {
159                                 // NULL detected
160                                 $SQL .= '`' . $entry . '`=NULL,';
161                         } elseif ((substr($value[$multiDimId], -2, 2) == '()') || (substr($value[$multiDimId], 0, 1) == '`')) {
162                                 // SQL function needs no ticks (')
163                                 $SQL .= '`' . $entry . '`=' . SQL_ESCAPE($value[$multiDimId]) . ',';
164                         } elseif (('' . bigintval($value[$multiDimId], TRUE, FALSE) . '' == '' . $value[$multiDimId] . ''))  {
165                                 // No need for ticks (')
166                                 $SQL .= '`' . $entry . '`=' . $value[$multiDimId] . ',';
167                         } else {
168                                 // Strings need ticks (') around them
169                                 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$multiDimId]) . "',";
170                         }
171                 }
172         } // END - foreach
173
174         // Remove last 2 chars and finish query
175         $SQL = substr($SQL, 0, -1) . ' WHERE `' . $whereColumn . '`=' . $whereData . ' LIMIT 1';
176
177         // Return SQL query
178         return $SQL;
179 }
180
181 // "Getter" for an "INSERT INTO" SQL query
182 function getInsertSqlFromArray ($array, $tableName) {
183         // Init SQL
184         $SQL = 'INSERT INTO
185 `{?_MYSQL_PREFIX?}_' . $tableName . '`
186 (
187 `' . implode('`, `', array_keys(postRequestArray())) . '`
188 ) VALUES (';
189
190         // Walk through all entries
191         foreach (postRequestArray() as $key => $value) {
192                 // Log debug message
193                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',key=' . $key . ',value=' . $value);
194
195                 // Add all entries
196                 if (is_null($value)) {
197                         // Add NULL
198                         $SQL .= 'NULL,';
199                 } elseif (substr($value, -2, 2) == '()') {
200                         // SQL function needs no ticks (')
201                         $SQL .= SQL_ESCAPE($value) . ',';
202                 } elseif ('' . bigintval($value, TRUE, FALSE) . '' == '' . $value . '') {
203                         // Number detected, no need for ticks (')
204                         $SQL .= bigintval($value) . ',';
205                 } elseif ('' . (float) $value . '' == '' . $value . '') {
206                         // Float number detected
207                         $SQL .= sprintf('%01.5f', $value);
208                 } else {
209                         // Everything else might be a string, so add ticks around it
210                         $SQL .= chr(39) . SQL_ESCAPE($value) . chr(39) . ',';
211                 }
212         } // END - foreach
213
214         // Finish SQL query
215         $SQL = substr($SQL, 0, -1) . ')';
216
217         // Return SQL query
218         return $SQL;
219 }
220
221 // Function to unset __is_sql_link_up
222 function unsetSqlLinkUp ($F, $L) {
223         // Unset it
224         //* DEBUG: */ logDebugMessage($F, $L, __FUNCTION__ . ': Called!');
225         SQL_SET_LINK($F, $L, NULL);
226 }
227
228 // Initializes the SQL link by bringing it up if set
229 function initSqlLink () {
230         // "Unset" the link
231         unsetSqlLinkUp(__FUNCTION__, __LINE__);
232
233         // Do this only if link is down
234         assert(!SQL_IS_LINK_UP());
235
236         // Is the configuration data set?
237         if ((!empty($GLOBALS['mysql']['host'])) && (!empty($GLOBALS['mysql']['login'])) && (!empty($GLOBALS['mysql']['dbase']))) {
238                 // Remove cache
239                 unsetSqlLinkUp(__FUNCTION__, __LINE__);
240
241                 // Connect to DB
242                 SQL_CONNECT($GLOBALS['mysql']['host'], $GLOBALS['mysql']['login'], $GLOBALS['mysql']['password'], __FUNCTION__, __LINE__);
243
244                 // Is the link valid?
245                 if (SQL_IS_LINK_UP()) {
246                         // Enable exit on error
247                         enableExitOnError();
248
249                         // Is it a valid resource?
250                         if (SQL_SELECT_DB($GLOBALS['mysql']['dbase'], __FUNCTION__, __LINE__) === TRUE) {
251                                 // Set database name (required for ext-optimize and ifSqlTableExists())
252                                 setConfigEntry('__DB_NAME', $GLOBALS['mysql']['dbase']);
253
254                                 // Remove MySQL array from namespace
255                                 unset($GLOBALS['mysql']);
256
257                                 // Load cache
258                                 loadIncludeOnce('inc/load_cache.php');
259                         } else {
260                                 // Wrong database?
261                                 reportBug(__FUNCTION__, __LINE__, 'Wrong database selected.');
262                         }
263                 } else {
264                         // No link to database!
265                         reportBug(__FUNCTION__, __LINE__, 'Database link is not yet up.');
266                 }
267         } else {
268                 // Maybe you forgot to enter your database login?
269                 reportBug(__FUNCTION__, __LINE__, 'Database login is missing.');
270         }
271 }
272
273 // Imports given SQL dump from given (relative) path and adds them to $sqlPool
274 function importSqlDump ($path, $dumpName, $sqlPool) {
275         // Construct FQFN
276         $FQFN = getPath() . $path . '/' . $dumpName . '.sql';
277
278         // Is the file readable?
279         if (!isFileReadable($FQFN)) {
280                 // Not found, which is bad
281                 reportBug(__FUNCTION__, __LINE__, sprintf("SQL dump %s/%s.sql is not readable.", $path, $dumpName));
282         } // END - if
283
284         // Then read it
285         $fileContent = readSqlDump($FQFN);
286
287         // Merge it with existing SQL statements
288         mergeSqls(explode(";\n", $fileContent), $sqlPool);
289 }
290
291 // SQL string escaping
292 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = TRUE, $strip = TRUE, $secure = TRUE) {
293         // Link is there?
294         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) {
295                 // Link is down or data is not an array
296                 //* DEBUG: */ logDebugMessage($F, $L, 'SQL_IS_LINK_UP()=' . intval(SQL_IS_LINK_UP()) . ',data[]=' . gettype($data) . ',sqlString=' . $sqlString . ': ABORTING!');
297                 return FALSE;
298         } // END - if
299
300         // Init array for escape'd data with SQL string
301         $dataSecured = array(
302                 '__sql_string' => $sqlString
303         );
304
305         // Escape all data
306         foreach ($data as $key => $value) {
307                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
308         } // END - foreach
309
310         // Generate query
311         $query = call_user_func_array('sprintf', $dataSecured);
312
313         if ($run === TRUE) {
314                 // Run SQL query (default)
315                 return SQL_QUERY($query, $F, $L);
316         } else {
317                 // Return secured string
318                 return $query;
319         }
320 }
321
322 // SELECT query string from table, columns and so on... ;-)
323 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
324         // Is columns an array?
325         if (!is_array($columns)) {
326                 // No array
327                 reportBug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
328                         gettype($columns),
329                         basename($F),
330                         $L
331                 ));
332
333                 // Abort here with 'false'
334                 return FALSE;
335         } // END  - if
336
337         // Is this is a simple array?
338         if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
339                 // Begin with SQL query
340                 $sql = 'SELECT ';
341
342                 // No, it comes from XML, so get it back from it
343                 $sql .= getSqlPartFromXmlArray($columns);
344
345                 // Finalize it
346                 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
347         } else {
348                 // Yes, prepare the SQL statement
349                 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
350         }
351
352         // Return the result
353         return SQL_QUERY_ESC($sql,
354                 array(
355                         $table,
356                         $idRow,
357                         bigintval($id),
358                 ), $F, $L
359         );
360 }
361
362 // ALTER TABLE wrapper function
363 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = TRUE) {
364         // Abort if link is down
365         if (!SQL_IS_LINK_UP()) return FALSE;
366
367         // This is the default result...
368         $result = FALSE;
369
370         // Determine index/fulltext/unique word
371         $isAlterIndex = (
372                 (
373                         isInString('INDEX', $sql)
374                 ) || (
375                         isInString('KEY', $sql)
376                 ) || (
377                         isInString('FULLTEXT', $sql)
378                 ) || (
379                         isInString('UNIQUE', $sql)
380                 )
381         );
382
383         // Extract table name
384         $tableArray = explode(' ', $sql);
385         $tableName = str_replace('`', '', $tableArray[2]);
386
387         // Debug log
388         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
389
390         // Shall we add/drop?
391         if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
392                 // Try two columns, one should fix
393                 foreach (array(4,5) as $idx) {
394                         // If an entry is not set, abort here
395                         if (!isset($tableArray[$idx])) {
396                                 // Debug log this
397                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
398                                 break;
399                         } // END - if
400
401                         // And column name as well
402                         $columnName = $tableArray[$idx];
403
404                         // Debug log
405                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)));
406
407                         // Is there no entry on ADD or an entry on DROP/CHANGE?
408                         if (((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql)) || ((isInString('CHANGE', $sql)) && ($idx == 4) && ((!ifSqlTableColumnExists($tableName, $tableArray[5])) || ($columnName == $tableArray[5])))))) {
409                                 // Do the query
410                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
411                                 $result = SQL_QUERY($sql, $F, $L, FALSE);
412
413                                 // Skip further attempt(s)
414                                 break;
415                         } elseif ((((ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
416                                 // Abort here because it is alreay there
417                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
418                                 break;
419                         } elseif ((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
420                                 // Abort here because we tried to drop a column which is not there (never created maybe)
421                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
422                                 break;
423                         } elseif ($columnName != 'KEY') {
424                                 // Something didn't fit, we better log it
425                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)) . '');
426                         }
427                 } // END - foreach
428         } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
429                 // Skip this query silently because InnoDB does not understand fulltext indexes
430                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s", $sql, $tableName, intval((is_bool($result)) ? 0 : ifSqlTableColumnExists($columnName)), $F, $L));
431         } elseif ($isAlterIndex === TRUE) {
432                 // And column name as well without backticks
433                 $keyName = str_replace('`', '', $tableArray[5]);
434                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
435
436                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
437                 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
438                         // Init loop
439                         $begin = 1;
440                         $keyName = ',';
441                         while (isInString(',', $keyName)) {
442                                 // Use last
443                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
444                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
445                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
446
447                                 // Remove brackes
448                                 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
449                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
450
451                                 // Continue
452                                 $begin++;
453                         } // END while
454                 } // END - if
455
456                 // Shall we run it?
457                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
458                 if (($tableArray[3] == 'ADD') && (!ifSqlTableIndexExist($tableName, $keyName))) {
459                         // Send it to the SQL_QUERY() function to add it
460                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
461                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
462                 } elseif (($tableArray[3] == 'DROP') && (ifSqlTableIndexExist($tableName, $keyName))) {
463                         // Send it to the SQL_QUERY() function to drop it
464                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
465                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
466                 } else {
467                         // Not executed
468                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
469                 }
470         } else {
471                 // Other ALTER TABLE query
472                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
473                 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
474         }
475
476         // Return result
477         return $result;
478 }
479
480 // Getter for SQL link
481 function SQL_GET_LINK () {
482         // Init link
483         $link = NULL;
484
485         // Is it in the globals?
486         if (isset($GLOBALS['__sql_link'])) {
487                 // Then take it
488                 $link = $GLOBALS['__sql_link'];
489                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - FROM GLOBALS!');
490         } // END - if
491
492         // Return it
493         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - EXIT!');
494         return $link;
495 }
496
497 // Setter for link
498 function SQL_SET_LINK ($F, $L, $link) {
499         //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'link[]=' . gettype($link) . ' - ENTERED!');
500         // Is this a resource or null?
501         if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
502                 // This may happen in installation phase
503                 //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'Some fatal errors detected in installation phase.');
504                 return;
505         } elseif ((!is_resource($link)) && (!is_null($link))) {
506                 // This should never happen!
507                 reportBug($F . ':' . __FUNCTION__, $L . ':' . __LINE__, sprintf("Type of link is not resource or null, type=%s", gettype($link)));
508         } // END - if
509
510         // Set it
511         $GLOBALS['__sql_link'] = $link;
512
513         // Re-init cache
514         $GLOBALS['__is_sql_link_up'] = is_resource($link);
515         //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, '__is_sql_link_up=' . intval($GLOBALS['__is_sql_link_up']) . ' - EXIT!');
516 }
517
518 // Checks if the link is up
519 function SQL_IS_LINK_UP () {
520         // Is there cached this?
521         if (!isset($GLOBALS['__is_sql_link_up'])) {
522                 // Something bad went wrong
523                 reportBug(__FUNCTION__, __LINE__, 'Called before SQL_SET_LINK() was called!');
524         } // END - if
525
526         // Return the result
527         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__is_sql_link_up=' . intval($GLOBALS['__is_sql_link_up']) . ' - EXIT!');
528         return $GLOBALS['__is_sql_link_up'];
529 }
530
531 // Wrapper function to make code more readable
532 function SQL_HASZERONUMS ($result) {
533         // Just pass it through
534         return (SQL_NUMROWS($result) === 0);
535 }
536
537 // Wrapper function to make code more readable
538 function SQL_HASZEROAFFECTED () {
539         // Just pass it through
540         return (SQL_AFFECTEDROWS() === 0);
541 }
542
543 // Private function to prepare the SQL query string
544 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = TRUE) {
545         // Debug message
546         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ' - ENTERED!');
547
548         // Is it already cached?
549         if (!isset($GLOBALS['sql_strings']['' . $sqlString . ''])) {
550                 // Preserve escaping and compile URI codes+config+expression code
551                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
552
553                 // Debug message
554                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
555
556                 // Do final compilation and revert {ESCAPE}
557                 $GLOBALS['sql_strings']['' . $sqlString . ''] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
558         } else {
559                 // Log message
560                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ' - CACHE!');
561         }
562
563         // Debug message
564         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ',sql_strings=' . $GLOBALS['sql_strings']['' . $sqlString . ''] . ' - EXIT!');
565
566         // Return it
567         return $GLOBALS['sql_strings']['' . $sqlString . ''];
568 }
569
570 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
571 function SQL_EPOCHE_TO_TIMESTAMP ($timestamp) {
572         return generateDateTime($timestamp, 7);
573 }
574
575 // Check if there is a SQL table created
576 function ifSqlTableExists ($tableName) {
577         // Make sure double-prefixes are being removed
578         $tableName = str_replace('{?_MYSQL_PREFIX?}_', '', $tableName);
579
580         // Log message
581         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
582
583         // Is there cache?
584         if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
585                 // Check if the table is there
586                 $result = SQL_QUERY_ESC("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
587                         array($tableName), __FUNCTION__, __LINE__);
588
589                 // Is a link there?
590                 if (!is_resource($result)) {
591                         // Is installation phase?
592                         if (isInstallationPhase()) {
593                                 // Then silently abort here
594                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ' - Returning FALSE ...');
595                                 return FALSE;
596                         } else {
597                                 // Please report this
598                                 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
599                         }
600                 } // END - if
601
602                 // Is there an entry?
603                 $GLOBALS[__FUNCTION__][$tableName] = (SQL_NUMROWS($result) == 1);
604                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
605         } // END - if
606
607         // Return cache
608         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
609         return $GLOBALS[__FUNCTION__][$tableName];
610 }
611
612 // Is a table column there?
613 function ifSqlTableColumnExists ($tableName, $columnName, $forceFound = FALSE) {
614         // Remove back-ticks
615         $columnName = str_replace('`', '', $columnName);
616
617         // Debug message
618         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
619
620         // If the table is not there, it is okay
621         if (!ifSqlTableExists($tableName)) {
622                 // Then abort here
623                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, columnName=' . $columnName . ',forceFound=' . intval($forceFound));
624                 return (($forceFound === FALSE) && (isInstallationPhase()));
625         } // END - if
626
627         // Get column information
628         $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
629                 array(
630                         $tableName,
631                         $columnName
632                 ), __FUNCTION__, __LINE__);
633
634         // Is a link there?
635         if (!is_resource($result)) {
636                 // Is installation phase?
637                 if (isInstallationPhase()) {
638                         // Then silently abort here
639                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ',columnName=' . $columnName . ' - Returning FALSE ...');
640                         return $forceFound;
641                 } else {
642                         // Please report this
643                         reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
644                 }
645         } // END - if
646
647         // Determine it
648         $doesExist = (!SQL_HASZERONUMS($result));
649
650         // Free result
651         SQL_FREERESULT($result);
652
653         // Return cache
654         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
655         return $doesExist;
656 }
657
658 // Checks depending on the mode if the index is there
659 function ifSqlTableIndexExist ($tableName, $keyName, $forceFound = FALSE) {
660         // Remove back-ticks
661         $keyName = str_replace('`', '', $keyName);
662
663         // Debug message
664         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ' - ENTERED!');
665
666         // If the table is not there, it is okay
667         if (!ifSqlTableExists($tableName)) {
668                 // Then abort here
669                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, keyName=' . $keyName . ',forceFound=' . intval($forceFound));
670                 return (($forceFound === FALSE) && (isInstallationPhase()));
671         } // END - if
672
673         // Show indexes
674         $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
675
676         // Is a link there?
677         if (!is_resource($result)) {
678                 // Is installation phase?
679                 if (isInstallationPhase()) {
680                         // Then silently abort here
681                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ',keyName=' . $keyName . ' - Returning FALSE ...');
682                         return $forceFound;
683                 } else {
684                         // Please report this
685                         reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
686                 }
687         } // END - if
688
689         // The key is not found by default
690         $doesExist = FALSE;
691
692         // Walk through all
693         while ($content = SQL_FETCHARRAY($result)) {
694                 // Is it the requested one?
695                 if ($content['Key_name'] == $keyName) {
696                         // Then it is found and exit
697                         $doesExist = TRUE;
698                         break;
699                 } // END - if
700         } // END - while
701
702         // Free result
703         SQL_FREERESULT($result);
704
705         // Return cache
706         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
707         return $doesExist;
708 }
709
710 // Init database layer
711 function initDatabaseLayer () {
712         // Set all required variables:
713         $GLOBALS['last_sql_error'] = '';
714 }
715
716 // Get last SQL error
717 function getLastSqlError () {
718         return $GLOBALS['last_sql_error'];
719 }
720
721 // Gets an array (or false if none is found) from all supported engines
722 function getArrayFromSupportedSqlEngines ($requestedEngine = 'ALL') {
723         // Init array
724         $engines = array();
725
726         // This also worked, now we need to check if the selected database type is supported
727         $result = SQL_QUERY('SHOW ENGINES', __FUNCTION__, __LINE__);
728
729         // Are there entries? (Bad if not)
730         if (!SQL_HASZERONUMS($result)) {
731                 // Load all and check for active entries
732                 while ($content = SQL_FETCHARRAY($result)) {
733                         // Debug message
734                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'support=' . $requestedEngine . ',Engine=' . $content['Engine'] . ',Support=' . $content['Support']);
735
736                         // Is this supported?
737                         if ((($requestedEngine == 'ALL') || ($content['Engine'] == $requestedEngine)) && (in_array($content['Support'], array('YES', 'DEFAULT')))) {
738                                 // Add it
739                                 array_push($engines, $content);
740                         } elseif (isDebugModeEnabled()) {
741                                 // Log it away in debug mode
742                                 logDebugMessage(__FUNCTION__, __LINE__, 'Engine ' . $content['Engine'] . ' is not supported (' . $content['Supported'] . ' - ' . $requestedEngine . ')');
743                         }
744                 } // END - if
745         } else {
746                 // No engines! :(
747                 $engines = FALSE;
748         }
749
750         // Free result
751         SQL_FREERESULT($result);
752
753         // Return result
754         return $engines;
755 }
756
757 // [EOF]
758 ?>