]> git.mxchange.org Git - mailer.git/blob - inc/sql-functions.php
New function introduced, fixes for extension installation:
[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 // Initializes the SQL link by bringing it up if set
222 function initSqlLink () {
223         // Do this only if link is down
224         assert(!SQL_IS_LINK_UP());
225
226         // Is the configuration data set?
227         if ((!empty($GLOBALS['mysql']['host'])) && (!empty($GLOBALS['mysql']['login'])) && (!empty($GLOBALS['mysql']['dbase']))) {
228                 // Remove cache
229                 unset($GLOBALS['is_sql_link_up']);
230
231                 // Connect to DB
232                 SQL_CONNECT($GLOBALS['mysql']['host'], $GLOBALS['mysql']['login'], $GLOBALS['mysql']['password'], __FILE__, __LINE__);
233
234                 // Is the link valid?
235                 if (SQL_IS_LINK_UP()) {
236                         // Enable exit on error
237                         enableExitOnError();
238
239                         // Is it a valid resource?
240                         if (SQL_SELECT_DB($GLOBALS['mysql']['dbase'], __FILE__, __LINE__) === TRUE) {
241                                 // Set database name (required for ext-optimize and ifSqlTableExists())
242                                 setConfigEntry('__DB_NAME', $GLOBALS['mysql']['dbase']);
243
244                                 // Remove MySQL array from namespace
245                                 unset($GLOBALS['mysql']);
246
247                                 // Load cache
248                                 loadIncludeOnce('inc/load_cache.php');
249                         } else {
250                                 // Wrong database?
251                                 reportBug(__FILE__, __LINE__, 'Wrong database selected.');
252                         }
253                 } else {
254                         // No link to database!
255                         reportBug(__FILE__, __LINE__, 'Database link is not yet up.');
256                 }
257         } else {
258                 // Maybe you forgot to enter your database login?
259                 reportBug(__FILE__, __LINE__, 'Database login is missing.');
260         }
261 }
262
263 // Imports given SQL dump from given (relative) path and adds them to $sqlPool
264 function importSqlDump ($path, $dumpName, $sqlPool) {
265         // Construct FQFN
266         $FQFN = getPath() . $path . '/' . $dumpName . '.sql';
267
268         // Is the file readable?
269         if (!isFileReadable($FQFN)) {
270                 // Not found, which is bad
271                 reportBug(__FILE__, __LINE__, sprintf("SQL dump %s/%s.sql is not readable.", $path, $dumpName));
272         } // END - if
273
274         // Then read it
275         $fileContent = readSqlDump($FQFN);
276
277         // Merge it with existing SQL statements
278         mergeSqls(explode(";\n", $fileContent), $sqlPool);
279 }
280
281 // SQL string escaping
282 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = TRUE, $strip = TRUE, $secure = TRUE) {
283         // Link is there?
284         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) {
285                 // Link is down or data is not an array
286                 /* DEBUG: */ logDebugMessage($F, $L, 'SQL_IS_LINK_UP()=' . intval(SQL_IS_LINK_UP()) . ',data[]=' . gettype($data) . ',sqlString=' . $sqlString . ': ABORTING!');
287                 return FALSE;
288         } // END - if
289
290         // Init array for escape'd data with SQL string
291         $dataSecured = array(
292                 '__sql_string' => $sqlString
293         );
294
295         // Escape all data
296         foreach ($data as $key => $value) {
297                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
298         } // END - foreach
299
300         // Generate query
301         $query = call_user_func_array('sprintf', $dataSecured);
302
303         if ($run === TRUE) {
304                 // Run SQL query (default)
305                 return SQL_QUERY($query, $F, $L);
306         } else {
307                 // Return secured string
308                 return $query;
309         }
310 }
311
312 // SELECT query string from table, columns and so on... ;-)
313 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
314         // Is columns an array?
315         if (!is_array($columns)) {
316                 // No array
317                 reportBug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
318                         gettype($columns),
319                         basename($F),
320                         $L
321                 ));
322
323                 // Abort here with 'false'
324                 return FALSE;
325         } // END  - if
326
327         // Is this is a simple array?
328         if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
329                 // Begin with SQL query
330                 $sql = 'SELECT ';
331
332                 // No, it comes from XML, so get it back from it
333                 $sql .= getSqlPartFromXmlArray($columns);
334
335                 // Finalize it
336                 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
337         } else {
338                 // Yes, prepare the SQL statement
339                 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
340         }
341
342         // Return the result
343         return SQL_QUERY_ESC($sql,
344                 array(
345                         $table,
346                         $idRow,
347                         bigintval($id),
348                 ), $F, $L
349         );
350 }
351
352 // ALTER TABLE wrapper function
353 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = TRUE) {
354         // Abort if link is down
355         if (!SQL_IS_LINK_UP()) return FALSE;
356
357         // This is the default result...
358         $result = FALSE;
359
360         // Determine index/fulltext/unique word
361         $isAlterIndex = (
362                 (
363                         isInString('INDEX', $sql)
364                 ) || (
365                         isInString('KEY', $sql)
366                 ) || (
367                         isInString('FULLTEXT', $sql)
368                 ) || (
369                         isInString('UNIQUE', $sql)
370                 )
371         );
372
373         // Extract table name
374         $tableArray = explode(' ', $sql);
375         $tableName = str_replace('`', '', $tableArray[2]);
376
377         // Debug log
378         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
379
380         // Shall we add/drop?
381         if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
382                 // Try two columns, one should fix
383                 foreach (array(4,5) as $idx) {
384                         // If an entry is not set, abort here
385                         if (!isset($tableArray[$idx])) {
386                                 // Debug log this
387                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
388                                 break;
389                         } // END - if
390
391                         // And column name as well
392                         $columnName = $tableArray[$idx];
393
394                         // Debug log
395                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)));
396
397                         // Is there no entry on ADD or an entry on DROP/CHANGE?
398                         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])))))) {
399                                 // Do the query
400                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
401                                 $result = SQL_QUERY($sql, $F, $L, FALSE);
402
403                                 // Skip further attempt(s)
404                                 break;
405                         } elseif ((((ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
406                                 // Abort here because it is alreay there
407                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
408                                 break;
409                         } elseif ((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
410                                 // Abort here because we tried to drop a column which is not there (never created maybe)
411                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
412                                 break;
413                         } elseif ($columnName != 'KEY') {
414                                 // Something didn't fit, we better log it
415                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)) . '');
416                         }
417                 } // END - foreach
418         } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
419                 // Skip this query silently because InnoDB does not understand fulltext indexes
420                 //* 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));
421         } elseif ($isAlterIndex === TRUE) {
422                 // And column name as well without backticks
423                 $keyName = str_replace('`', '', $tableArray[5]);
424                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
425
426                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
427                 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
428                         // Init loop
429                         $begin = 1;
430                         $keyName = ',';
431                         while (isInString(',', $keyName)) {
432                                 // Use last
433                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
434                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
435                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
436
437                                 // Remove brackes
438                                 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
439                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
440
441                                 // Continue
442                                 $begin++;
443                         } // END while
444                 } // END - if
445
446                 // Shall we run it?
447                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
448                 if (($tableArray[3] == 'ADD') && (!ifSqlTableIndexExist($tableName, $keyName))) {
449                         // Send it to the SQL_QUERY() function to add it
450                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
451                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
452                 } elseif (($tableArray[3] == 'DROP') && (ifSqlTableIndexExist($tableName, $keyName))) {
453                         // Send it to the SQL_QUERY() function to drop it
454                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
455                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
456                 } else {
457                         // Not executed
458                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
459                 }
460         } else {
461                 // Other ALTER TABLE query
462                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
463                 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
464         }
465
466         // Return result
467         return $result;
468 }
469
470 // Getter for SQL link
471 function SQL_GET_LINK () {
472         // Init link
473         $link = NULL;
474
475         // Is it in the globals?
476         if (isset($GLOBALS['sql_link'])) {
477                 // Then take it
478                 $link = $GLOBALS['sql_link'];
479         } // END - if
480
481         // Return it
482         return $link;
483 }
484
485 // Setter for link
486 function SQL_SET_LINK ($link) {
487         // Is this a resource or null?
488         if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
489                 // This may happen in installation phase
490                 return;
491         } elseif ((!is_resource($link)) && (!is_null($link))) {
492                 // This should never happen!
493                 reportBug(__FUNCTION__, __LINE__, sprintf("Type of link is not resource or null, type=%s", gettype($link)));
494         } // END - if
495
496         // Set it
497         $GLOBALS['sql_link'] = $link;
498
499         // Re-init cache
500         $GLOBALS['is_sql_link_up'] = is_resource($link);
501 }
502
503 // Checks if the link is up
504 function SQL_IS_LINK_UP () {
505         // Is there cached this?
506         if (!isset($GLOBALS['is_sql_link_up'])) {
507                 // Determine it
508                 $GLOBALS['is_sql_link_up'] = is_resource(SQL_GET_LINK());
509         } // END - if
510
511         // Return the result
512         return $GLOBALS['is_sql_link_up'];
513 }
514
515 // Wrapper function to make code more readable
516 function SQL_HASZERONUMS ($result) {
517         // Just pass it through
518         return (SQL_NUMROWS($result) === 0);
519 }
520
521 // Wrapper function to make code more readable
522 function SQL_HASZEROAFFECTED () {
523         // Just pass it through
524         return (SQL_AFFECTEDROWS() === 0);
525 }
526
527 // Private function to prepare the SQL query string
528 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = TRUE) {
529         // Debug message
530         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ' - ENTERED!');
531
532         // Is it already cached?
533         if (!isset($GLOBALS['sql_strings']['' . $sqlString . ''])) {
534                 // Preserve escaping and compile URI codes+config+expression code
535                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
536
537                 // Debug message
538                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
539
540                 // Do final compilation and revert {ESCAPE}
541                 $GLOBALS['sql_strings']['' . $sqlString . ''] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
542         } else {
543                 // Log message
544                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ' - CACHE!');
545         }
546
547         // Debug message
548         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ',sql_strings=' . $GLOBALS['sql_strings']['' . $sqlString . ''] . ' - EXIT!');
549
550         // Return it
551         return $GLOBALS['sql_strings']['' . $sqlString . ''];
552 }
553
554 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
555 function SQL_EPOCHE_TO_TIMESTAMP ($timestamp) {
556         return generateDateTime($timestamp, 7);
557 }
558
559 // Check if there is a SQL table created
560 function ifSqlTableExists ($tableName) {
561         // Make sure double-prefixes are being removed
562         $tableName = str_replace('{?_MYSQL_PREFIX?}_', '', $tableName);
563
564         // Log message
565         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
566
567         // Is there cache?
568         if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
569                 // Check if the table is there
570                 $result = SQL_QUERY_ESC("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
571                         array($tableName), __FILE__, __LINE__);
572
573                 // Is a link there?
574                 if (!is_resource($result)) {
575                         // Is installation phase?
576                         if (isInstallationPhase()) {
577                                 // Then silently abort here
578                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ' - Returning FALSE ...');
579                                 return FALSE;
580                         } else {
581                                 // Please report this
582                                 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
583                         }
584                 } // END - if
585
586                 // Is there an entry?
587                 $GLOBALS[__FUNCTION__][$tableName] = (SQL_NUMROWS($result) == 1);
588                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
589         } // END - if
590
591         // Return cache
592         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
593         return $GLOBALS[__FUNCTION__][$tableName];
594 }
595
596 // Is a table column there?
597 function ifSqlTableColumnExists ($tableName, $columnName, $forceFound = FALSE) {
598         // Remove back-ticks
599         $columnName = str_replace('`', '', $columnName);
600
601         // Debug message
602         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
603
604         // If the table is not there, it is okay
605         if (!ifSqlTableExists($tableName)) {
606                 // Then abort here
607                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, columnName=' . $columnName . ',forceFound=' . intval($forceFound));
608                 return (($forceFound === FALSE) && (isInstallationPhase()));
609         } // END - if
610
611         // Get column information
612         $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
613                 array(
614                         $tableName,
615                         $columnName
616                 ), __FUNCTION__, __LINE__);
617
618         // Is a link there?
619         if (!is_resource($result)) {
620                 // Is installation phase?
621                 if (isInstallationPhase()) {
622                         // Then silently abort here
623                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ',columnName=' . $columnName . ' - Returning FALSE ...');
624                         return $forceFound;
625                 } else {
626                         // Please report this
627                         reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
628                 }
629         } // END - if
630
631         // Determine it
632         $doesExist = (!SQL_HASZERONUMS($result));
633
634         // Free result
635         SQL_FREERESULT($result);
636
637         // Return cache
638         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
639         return $doesExist;
640 }
641
642 // Checks depending on the mode if the index is there
643 function ifSqlTableIndexExist ($tableName, $keyName, $forceFound = FALSE) {
644         // Remove back-ticks
645         $keyName = str_replace('`', '', $keyName);
646
647         // Debug message
648         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ' - ENTERED!');
649
650         // If the table is not there, it is okay
651         if (!ifSqlTableExists($tableName)) {
652                 // Then abort here
653                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, keyName=' . $keyName . ',forceFound=' . intval($forceFound));
654                 return (($forceFound === FALSE) && (isInstallationPhase()));
655         } // END - if
656
657         // Show indexes
658         $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
659
660         // Is a link there?
661         if (!is_resource($result)) {
662                 // Is installation phase?
663                 if (isInstallationPhase()) {
664                         // Then silently abort here
665                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ',keyName=' . $keyName . ' - Returning FALSE ...');
666                         return $forceFound;
667                 } else {
668                         // Please report this
669                         reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
670                 }
671         } // END - if
672
673         // The key is not found by default
674         $doesExist = FALSE;
675
676         // Walk through all
677         while ($content = SQL_FETCHARRAY($result)) {
678                 // Is it the requested one?
679                 if ($content['Key_name'] == $keyName) {
680                         // Then it is found and exit
681                         $doesExist = TRUE;
682                         break;
683                 } // END - if
684         } // END - while
685
686         // Free result
687         SQL_FREERESULT($result);
688
689         // Return cache
690         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
691         return $doesExist;
692 }
693
694 // Init database layer
695 function initDatabaseLayer () {
696         // Set all required variables:
697         $GLOBALS['last_sql_error'] = '';
698 }
699
700 // Get last SQL error
701 function getLastSqlError () {
702         return $GLOBALS['last_sql_error'];
703 }
704
705 // Gets an array (or false if none is found) from all supported engines
706 function getArrayFromSupportedSqlEngines ($requestedEngine = 'ALL') {
707         // Init array
708         $engines = array();
709
710         // This also worked, now we need to check if the selected database type is supported
711         $result = SQL_QUERY('SHOW ENGINES', __FUNCTION__, __LINE__);
712
713         // Are there entries? (Bad if not)
714         if (!SQL_HASZERONUMS($result)) {
715                 // Load all and check for active entries
716                 while ($content = SQL_FETCHARRAY($result)) {
717                         // Debug message
718                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'support=' . $requestedEngine . ',Engine=' . $content['Engine'] . ',Support=' . $content['Support']);
719
720                         // Is this supported?
721                         if ((($requestedEngine == 'ALL') || ($content['Engine'] == $requestedEngine)) && (in_array($content['Support'], array('YES', 'DEFAULT')))) {
722                                 // Add it
723                                 array_push($engines, $content);
724                         } elseif (isDebugModeEnabled()) {
725                                 // Log it away in debug mode
726                                 logDebugMessage(__FUNCTION__, __LINE__, 'Engine ' . $content['Engine'] . ' is not supported (' . $content['Supported'] . ' - ' . $requestedEngine . ')');
727                         }
728                 } // END - if
729         } else {
730                 // No engines! :(
731                 $engines = FALSE;
732         }
733
734         // Free result
735         SQL_FREERESULT($result);
736
737         // Return result
738         return $engines;
739 }
740
741 // [EOF]
742 ?>