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