Merge branch 'contrib' into 0.2.1-FINAL
[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 ifSqlsRegistered () {
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         // 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                 sqlConnectToDatabase($GLOBALS['mysql']['host'], $GLOBALS['mysql']['login'], $GLOBALS['mysql']['password'], __FUNCTION__, __LINE__);
243
244                 // Is the link valid?
245                 if (isSqlLinkUp()) {
246                         // Enable exit on error
247                         enableExitOnError();
248
249                         // Is it a valid resource?
250                         if (sqlSelectDatabase($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 sqlQueryEscaped ($sqlString, $data, $file, $line, $run = TRUE, $strip = TRUE, $secure = TRUE) {
293         // Link is there?
294         if ((!isSqlLinkUp()) || (!is_array($data))) {
295                 // Link is down or data is not an array
296                 //* DEBUG: */ logDebugMessage($file, $line, 'isSqlLinkUp()=' . intval(isSqlLinkUp()) . ',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                 //* DEBUG: */ logDebugMessage(basename($file) . '/' . __FUNCTION__, $line . '/' . __LINE__, 'key=' . $key . ',value=' . $value . ',run=' . intval($run) . ',strip=' . intval($strip) . ',secure=' . intval($secure));
308                 $dataSecured[$key] = sqlEscapeString($value, $secure, $strip);
309                 //* DEBUG: */ logDebugMessage(basename($file) . '/' . __FUNCTION__, $line . '/' . __LINE__, 'dataSecured[key]=' . $dataSecured[$key]);
310         } // END - foreach
311
312         // Generate query
313         $query = call_user_func_array('sprintf', $dataSecured);
314
315         if ($run === TRUE) {
316                 // Run SQL query (default)
317                 return sqlQuery($query, $file, $line);
318         } else {
319                 // Return secured string
320                 return $query;
321         }
322 }
323
324 // SELECT query string from table, columns and so on... ;-)
325 function getSqlResultFromArray ($table, $columns, $idRow, $id, $file, $line) {
326         // Is columns an array?
327         if (!is_array($columns)) {
328                 // No array
329                 reportBug(__FUNCTION__, __LINE__, sprintf('columns is not an array. %s != array, file=%s, line=%s',
330                         gettype($columns),
331                         basename($file),
332                         $line
333                 ));
334
335                 // Abort here with 'false'
336                 return FALSE;
337         } // END  - if
338
339         // Is this is a simple array?
340         if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
341                 // Begin with SQL query
342                 $sql = 'SELECT ';
343
344                 // No, it comes from XML, so get it back from it
345                 $sql .= getSqlPartFromXmlArray($columns);
346
347                 // Finalize it
348                 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
349         } else {
350                 // Yes, prepare the SQL statement
351                 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
352         }
353
354         // Return the result
355         return sqlQueryEscaped($sql,
356                 array(
357                         $table,
358                         $idRow,
359                         bigintval($id),
360                 ), $file, $line
361         );
362 }
363
364 // ALTER TABLE wrapper function
365 function sqlQueryAlterTable ($sql, $file, $line, $enableCodes = TRUE) {
366         // Abort if link is down
367         if (!isSqlLinkUp()) return FALSE;
368
369         // This is the default result...
370         $result = FALSE;
371
372         // Determine index/fulltext/unique word
373         $isAlterIndex = (
374                 (
375                         isInString('INDEX', $sql)
376                 ) || (
377                         isInString('KEY', $sql)
378                 ) || (
379                         isInString('FULLTEXT', $sql)
380                 ) || (
381                         isInString('UNIQUE', $sql)
382                 )
383         );
384
385         // Extract table name
386         $tableArray = explode(' ', $sql);
387         $tableName = str_replace('`', '', $tableArray[2]);
388
389         // Debug log
390         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
391
392         // Shall we add/drop?
393         if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
394                 // Try two columns, one should fix
395                 foreach (array(4,5) as $idx) {
396                         // If an entry is not set, abort here
397                         if (!isset($tableArray[$idx])) {
398                                 // Debug log this
399                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
400                                 break;
401                         } // END - if
402
403                         // And column name as well
404                         $columnName = $tableArray[$idx];
405
406                         // Debug log
407                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)));
408
409                         // Is there no entry on ADD or an entry on DROP/CHANGE?
410                         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])))))) {
411                                 // Do the query
412                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
413                                 $result = sqlQuery($sql, $file, $line, FALSE);
414
415                                 // Skip further attempt(s)
416                                 break;
417                         } elseif ((((ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
418                                 // Abort here because it is alreay there
419                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
420                                 break;
421                         } elseif ((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
422                                 // Abort here because we tried to drop a column which is not there (never created maybe)
423                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
424                                 break;
425                         } elseif ($columnName != 'KEY') {
426                                 // Something didn't fit, we better log it
427                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)) . '');
428                         }
429                 } // END - foreach
430         } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
431                 // Skip this query silently because InnoDB does not understand fulltext indexes
432                 //* 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));
433         } elseif ($isAlterIndex === TRUE) {
434                 // And column name as well without backticks
435                 $keyName = str_replace('`', '', $tableArray[5]);
436                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
437
438                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
439                 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
440                         // Init loop
441                         $begin = 1;
442                         $keyName = ',';
443                         while (isInString(',', $keyName)) {
444                                 // Use last
445                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
446                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
447                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
448
449                                 // Remove brackes
450                                 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
451                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
452
453                                 // Continue
454                                 $begin++;
455                         } // END while
456                 } // END - if
457
458                 // Shall we run it?
459                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
460                 if (($tableArray[3] == 'ADD') && (!ifSqlTableIndexExist($tableName, $keyName))) {
461                         // Send it to the sqlQuery() function to add it
462                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
463                         $result = sqlQuery($sql, $file, $line, $enableCodes);
464                 } elseif (($tableArray[3] == 'DROP') && (ifSqlTableIndexExist($tableName, $keyName))) {
465                         // Send it to the sqlQuery() function to drop it
466                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
467                         $result = sqlQuery($sql, $file, $line, $enableCodes);
468                 } else {
469                         // Not executed
470                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
471                 }
472         } else {
473                 // Other ALTER TABLE query
474                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
475                 $result = sqlQuery($sql, $file, $line, $enableCodes);
476         }
477
478         // Return result
479         return $result;
480 }
481
482 // Getter for SQL link
483 function getSqlLink () {
484         // Init link
485         $link = NULL;
486
487         // Is it in the globals?
488         if (isset($GLOBALS['__sql_link'])) {
489                 // Then take it
490                 $link = $GLOBALS['__sql_link'];
491                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - FROM GLOBALS!');
492         } // END - if
493
494         // Return it
495         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - EXIT!');
496         return $link;
497 }
498
499 // Setter for link
500 // Do *not* add debug lines here. This will cause and endless loop
501 function setSqlLink ($file, $line, $link) {
502         // Is this a resource or null?
503         if ((ifFatalErrorsDetected()) && (isInstaller())) {
504                 // This may happen in installation phase
505                 return;
506         } elseif ((!is_resource($link)) && (!is_null($link)) && (!$link instanceof mysqli)) {
507                 // This should never happen!
508                 reportBug($file . ':' . __FUNCTION__, $line . ':' . __LINE__, sprintf('Type of link is not resource, null or mysqli class, type=%s', gettype($link)));
509         } // END - if
510
511         // Set it
512         $GLOBALS['__sql_link'] = $link;
513
514         // Re-init cache
515         $GLOBALS['__is_sql_link_up'] = ((function_exists('isValidSqlLink')) && (isValidSqlLink($link)));
516 }
517
518 // Checks if the link is up
519 function isSqlLinkUp () {
520         // Is there cached this?
521         if (!isset($GLOBALS['__is_sql_link_up'])) {
522                 // Something bad went wrong
523                 reportBug(__FUNCTION__, __LINE__, 'Called before setSqlLink() 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 ifSqlHasZeroNums ($result) {
533         // Just pass it through
534         return (sqlNumRows($result) === 0);
535 }
536
537 // Wrapper function to make code more readable
538 function ifSqlHasZeroAffectedRows () {
539         // Just pass it through
540         return (sqlAffectedRows() === 0);
541 }
542
543 // Private function to prepare the SQL query string
544 function sqlPrepareQueryString ($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 = str_replace(chr(92), '{BACKLASH}', $sqlString);
552                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
553                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString2));
554
555                 // Debug message
556                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
557
558                 // Do final compilation and revert {BACKSLASH}
559                 $GLOBALS['sql_strings']['' . $sqlString . ''] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
560                 $GLOBALS['sql_strings']['' . $sqlString . ''] = str_replace('{BACKLASH}', chr(92), $GLOBALS['sql_strings']['' . $sqlString . '']);
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) . ',returned sql_string=' . $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 (!isValidSqlLink($result)) {
594                         // Is installation phase?
595                         if (isInstaller()) {
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) && (isInstaller()));
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 (!isValidSqlLink($result)) {
639                 // Is installation phase?
640                 if (isInstaller()) {
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) && (isInstaller()));
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 (!isValidSqlLink($result)) {
681                 // Is installation phase?
682                 if (isInstaller()) {
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 // "Getter" for result from given table and field/type LIKEs
761 function sqlGetResultFromLikeColumnsType ($tableName, $field, $type) {
762         // The table should be there
763         assert(ifSqlTableExists($tableName));
764
765         // Default no field set
766         $fieldSql = '';
767         if (!empty($field)) {
768                 // Then use it
769                 $fieldSql = "`Field` LIKE '" . $field . "' AND";
770         } // END - if
771
772         // Show them
773         return sqlQueryEscaped("SHOW COLUMNS FROM
774         `{?_MYSQL_PREFIX?}_%s`
775 WHERE
776         " . $fieldSql . "
777         `Type` LIKE '%s%%'",
778                 array(
779                         $tableName,
780                         $type
781                 ), __FUNCTION__, __LINE__
782         );
783 }
784
785 // [EOF]
786 ?>