Fixed bug 'sprintf() too few arguments':
[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                 $dataSecured[$key] = sqlEscapeString($value, $secure, $strip);
308         } // END - foreach
309
310         // Generate query
311         $query = call_user_func_array('sprintf', $dataSecured);
312
313         if ($run === TRUE) {
314                 // Run SQL query (default)
315                 return sqlQuery($query, $file, $line);
316         } else {
317                 // Return secured string
318                 return $query;
319         }
320 }
321
322 // SELECT query string from table, columns and so on... ;-)
323 function getSqlResultFromArray ($table, $columns, $idRow, $id, $file, $line) {
324         // Is columns an array?
325         if (!is_array($columns)) {
326                 // No array
327                 reportBug(__FUNCTION__, __LINE__, sprintf('columns is not an array. %s != array, file=%s, line=%s',
328                         gettype($columns),
329                         basename($file),
330                         $line
331                 ));
332
333                 // Abort here with 'false'
334                 return FALSE;
335         } // END  - if
336
337         // Is this is a simple array?
338         if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
339                 // Begin with SQL query
340                 $sql = 'SELECT ';
341
342                 // No, it comes from XML, so get it back from it
343                 $sql .= getSqlPartFromXmlArray($columns);
344
345                 // Finalize it
346                 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
347         } else {
348                 // Yes, prepare the SQL statement
349                 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
350         }
351
352         // Return the result
353         return sqlQueryEscaped($sql,
354                 array(
355                         $table,
356                         $idRow,
357                         bigintval($id),
358                 ), $file, $line
359         );
360 }
361
362 // ALTER TABLE wrapper function
363 function sqlQueryAlterTable ($sql, $file, $line, $enableCodes = TRUE) {
364         // Abort if link is down
365         if (!isSqlLinkUp()) return FALSE;
366
367         // This is the default result...
368         $result = FALSE;
369
370         // Determine index/fulltext/unique word
371         $isAlterIndex = (
372                 (
373                         isInString('INDEX', $sql)
374                 ) || (
375                         isInString('KEY', $sql)
376                 ) || (
377                         isInString('FULLTEXT', $sql)
378                 ) || (
379                         isInString('UNIQUE', $sql)
380                 )
381         );
382
383         // Extract table name
384         $tableArray = explode(' ', $sql);
385         $tableName = str_replace('`', '', $tableArray[2]);
386
387         // Debug log
388         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
389
390         // Shall we add/drop?
391         if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
392                 // Try two columns, one should fix
393                 foreach (array(4,5) as $idx) {
394                         // If an entry is not set, abort here
395                         if (!isset($tableArray[$idx])) {
396                                 // Debug log this
397                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
398                                 break;
399                         } // END - if
400
401                         // And column name as well
402                         $columnName = $tableArray[$idx];
403
404                         // Debug log
405                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)));
406
407                         // Is there no entry on ADD or an entry on DROP/CHANGE?
408                         if (((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql)) || ((isInString('CHANGE', $sql)) && ($idx == 4) && ((!ifSqlTableColumnExists($tableName, $tableArray[5])) || ($columnName == $tableArray[5])))))) {
409                                 // Do the query
410                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
411                                 $result = sqlQuery($sql, $file, $line, FALSE);
412
413                                 // Skip further attempt(s)
414                                 break;
415                         } elseif ((((ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
416                                 // Abort here because it is alreay there
417                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
418                                 break;
419                         } elseif ((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
420                                 // Abort here because we tried to drop a column which is not there (never created maybe)
421                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
422                                 break;
423                         } elseif ($columnName != 'KEY') {
424                                 // Something didn't fit, we better log it
425                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)) . '');
426                         }
427                 } // END - foreach
428         } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
429                 // Skip this query silently because InnoDB does not understand fulltext indexes
430                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf('Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s', $sql, $tableName, intval((is_bool($result)) ? 0 : ifSqlTableColumnExists($columnName)), $file, $line));
431         } elseif ($isAlterIndex === TRUE) {
432                 // And column name as well without backticks
433                 $keyName = str_replace('`', '', $tableArray[5]);
434                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
435
436                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
437                 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
438                         // Init loop
439                         $begin = 1;
440                         $keyName = ',';
441                         while (isInString(',', $keyName)) {
442                                 // Use last
443                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
444                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
445                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
446
447                                 // Remove brackes
448                                 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
449                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
450
451                                 // Continue
452                                 $begin++;
453                         } // END while
454                 } // END - if
455
456                 // Shall we run it?
457                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
458                 if (($tableArray[3] == 'ADD') && (!ifSqlTableIndexExist($tableName, $keyName))) {
459                         // Send it to the sqlQuery() function to add it
460                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
461                         $result = sqlQuery($sql, $file, $line, $enableCodes);
462                 } elseif (($tableArray[3] == 'DROP') && (ifSqlTableIndexExist($tableName, $keyName))) {
463                         // Send it to the sqlQuery() function to drop it
464                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
465                         $result = sqlQuery($sql, $file, $line, $enableCodes);
466                 } else {
467                         // Not executed
468                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
469                 }
470         } else {
471                 // Other ALTER TABLE query
472                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
473                 $result = sqlQuery($sql, $file, $line, $enableCodes);
474         }
475
476         // Return result
477         return $result;
478 }
479
480 // Getter for SQL link
481 function getSqlLink () {
482         // Init link
483         $link = NULL;
484
485         // Is it in the globals?
486         if (isset($GLOBALS['__sql_link'])) {
487                 // Then take it
488                 $link = $GLOBALS['__sql_link'];
489                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - FROM GLOBALS!');
490         } // END - if
491
492         // Return it
493         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - EXIT!');
494         return $link;
495 }
496
497 // Setter for link
498 // Do *not* add debug lines here. This will cause and endless loop
499 function setSqlLink ($file, $line, $link) {
500         // Is this a resource or null?
501         if ((ifFatalErrorsDetected()) && (isInstaller())) {
502                 // This may happen in installation phase
503                 return;
504         } elseif ((!is_resource($link)) && (!is_null($link))) {
505                 // This should never happen!
506                 reportBug($file . ':' . __FUNCTION__, $line . ':' . __LINE__, sprintf('Type of link is not resource or null, type=%s', gettype($link)));
507         } // END - if
508
509         // Set it
510         $GLOBALS['__sql_link'] = $link;
511
512         // Re-init cache
513         $GLOBALS['__is_sql_link_up'] = is_resource($link);
514 }
515
516 // Checks if the link is up
517 function isSqlLinkUp () {
518         // Is there cached this?
519         if (!isset($GLOBALS['__is_sql_link_up'])) {
520                 // Something bad went wrong
521                 reportBug(__FUNCTION__, __LINE__, 'Called before setSqlLink() was called!');
522         } // END - if
523
524         // Return the result
525         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__is_sql_link_up=' . intval($GLOBALS['__is_sql_link_up']) . ' - EXIT!');
526         return $GLOBALS['__is_sql_link_up'];
527 }
528
529 // Wrapper function to make code more readable
530 function ifSqlHasZeroNums ($result) {
531         // Just pass it through
532         return (sqlNumRows($result) === 0);
533 }
534
535 // Wrapper function to make code more readable
536 function ifSqlHasZeroAffectedRows () {
537         // Just pass it through
538         return (sqlAffectedRows() === 0);
539 }
540
541 // Private function to prepare the SQL query string
542 function sqlPrepareQueryString ($sqlString, $enableCodes = TRUE) {
543         // Debug message
544         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ' - ENTERED!');
545
546         // Is it already cached?
547         if (!isset($GLOBALS['sql_strings']['' . $sqlString . ''])) {
548                 // Preserve escaping and compile URI codes+config+expression code
549                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
550
551                 // Debug message
552                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
553
554                 // Do final compilation and revert {ESCAPE}
555                 $GLOBALS['sql_strings']['' . $sqlString . ''] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
556         } else {
557                 // Log message
558                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ' - CACHE!');
559         }
560
561         // Debug message
562         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ',sql_strings=' . $GLOBALS['sql_strings']['' . $sqlString . ''] . ' - EXIT!');
563
564         // Return it
565         return $GLOBALS['sql_strings']['' . $sqlString . ''];
566 }
567
568 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
569 function getSqlTimestampFromUnix ($timestamp) {
570         return generateDateTime($timestamp, '7');
571 }
572
573 // Check if there is a SQL table created
574 function ifSqlTableExists ($tableName) {
575         // Make sure double-prefixes are being removed
576         $tableName = str_replace('{?_MYSQL_PREFIX?}_', '', $tableName);
577
578         // Log message
579         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
580
581         // Is there cache?
582         if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
583                 // Check if the table is there
584                 $result = sqlQueryEscaped("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
585                         array($tableName), __FUNCTION__, __LINE__);
586
587                 // Is a link there?
588                 if (!is_resource($result)) {
589                         // Is installation phase?
590                         if (isInstaller()) {
591                                 // Then silently abort here
592                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',tableName=' . $tableName . ' - Returning FALSE ...');
593                                 return FALSE;
594                         } else {
595                                 // Please report this
596                                 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
597                         }
598                 } // END - if
599
600                 // Is there an entry?
601                 $GLOBALS[__FUNCTION__][$tableName] = (sqlNumRows($result) == 1);
602                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
603         } // END - if
604
605         // Return cache
606         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
607         return $GLOBALS[__FUNCTION__][$tableName];
608 }
609
610 // Is a table column there?
611 function ifSqlTableColumnExists ($tableName, $columnName, $forceFound = FALSE) {
612         // Remove back-ticks
613         $columnName = str_replace('`', '', $columnName);
614
615         // Debug message
616         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
617
618         // If the table is not there, it is okay
619         if (!ifSqlTableExists($tableName)) {
620                 // Then abort here
621                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, columnName=' . $columnName . ',forceFound=' . intval($forceFound));
622                 return (($forceFound === FALSE) && (isInstaller()));
623         } // END - if
624
625         // Get column information
626         $result = sqlQueryEscaped("SHOW COLUMNS FROM `%s` LIKE '%s'",
627                 array(
628                         $tableName,
629                         $columnName
630                 ), __FUNCTION__, __LINE__);
631
632         // Is a link there?
633         if (!is_resource($result)) {
634                 // Is installation phase?
635                 if (isInstaller()) {
636                         // Then silently abort here
637                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',tableName=' . $tableName . ',columnName=' . $columnName . ' - Returning FALSE ...');
638                         return $forceFound;
639                 } else {
640                         // Please report this
641                         reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
642                 }
643         } // END - if
644
645         // Determine it
646         $doesExist = (!ifSqlHasZeroNums($result));
647
648         // Free result
649         sqlFreeResult($result);
650
651         // Return cache
652         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
653         return $doesExist;
654 }
655
656 // Checks depending on the mode if the index is there
657 function ifSqlTableIndexExist ($tableName, $keyName, $forceFound = FALSE) {
658         // Remove back-ticks
659         $keyName = str_replace('`', '', $keyName);
660
661         // Debug message
662         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ' - ENTERED!');
663
664         // If the table is not there, it is okay
665         if (!ifSqlTableExists($tableName)) {
666                 // Then abort here
667                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, keyName=' . $keyName . ',forceFound=' . intval($forceFound));
668                 return (($forceFound === FALSE) && (isInstaller()));
669         } // END - if
670
671         // Show indexes
672         $result = sqlQueryEscaped("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
673
674         // Is a link there?
675         if (!is_resource($result)) {
676                 // Is installation phase?
677                 if (isInstaller()) {
678                         // Then silently abort here
679                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',tableName=' . $tableName . ',keyName=' . $keyName . ' - Returning FALSE ...');
680                         return $forceFound;
681                 } else {
682                         // Please report this
683                         reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
684                 }
685         } // END - if
686
687         // The key is not found by default
688         $doesExist = FALSE;
689
690         // Walk through all
691         while ($content = sqlFetchArray($result)) {
692                 // Is it the requested one?
693                 if ($content['Key_name'] == $keyName) {
694                         // Then it is found and exit
695                         $doesExist = TRUE;
696                         break;
697                 } // END - if
698         } // END - while
699
700         // Free result
701         sqlFreeResult($result);
702
703         // Return cache
704         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
705         return $doesExist;
706 }
707
708 // Init database layer
709 function initDatabaseLayer () {
710         // Set all required variables:
711         $GLOBALS['last_sql_error'] = '';
712 }
713
714 // Get last SQL error
715 function getLastSqlError () {
716         return $GLOBALS['last_sql_error'];
717 }
718
719 // Gets an array (or false if none is found) from all supported engines
720 function getArrayFromSupportedSqlEngines ($requestedEngine = 'ALL') {
721         // Init array
722         $engines = array();
723
724         // This also worked, now we need to check if the selected database type is supported
725         $result = sqlQuery('SHOW ENGINES', __FUNCTION__, __LINE__);
726
727         // Are there entries? (Bad if not)
728         if (!ifSqlHasZeroNums($result)) {
729                 // Load all and check for active entries
730                 while ($content = sqlFetchArray($result)) {
731                         // Debug message
732                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'support=' . $requestedEngine . ',Engine=' . $content['Engine'] . ',Support=' . $content['Support']);
733
734                         // Is this supported?
735                         if ((($requestedEngine == 'ALL') || ($content['Engine'] == $requestedEngine)) && (in_array($content['Support'], array('YES', 'DEFAULT')))) {
736                                 // Add it
737                                 array_push($engines, $content);
738                         } elseif (isDebugModeEnabled()) {
739                                 // Log it away in debug mode
740                                 logDebugMessage(__FUNCTION__, __LINE__, 'Engine ' . $content['Engine'] . ' is not supported (' . $content['Supported'] . ' - ' . $requestedEngine . ')');
741                         }
742                 } // END - if
743         } else {
744                 // No engines! :(
745                 $engines = FALSE;
746         }
747
748         // Free result
749         sqlFreeResult($result);
750
751         // Return result
752         return $engines;
753 }
754
755 // "Getter" for result from given table and field/type LIKEs
756 function sqlGetResultFromLikeColumnsType ($tableName, $field, $type) {
757         // The table should be there
758         assert(ifSqlTableExists($tableName));
759
760         // Default no field set
761         $fieldSql = '';
762         if (!empty($field)) {
763                 // Then use it
764                 $fieldSql = "`Field` LIKE '" . $field . "' AND";
765         } // END - if
766
767         // Show them
768         return sqlQueryEscaped("SHOW COLUMNS FROM
769         `{?_MYSQL_PREFIX?}_%s`
770 WHERE
771         " . $fieldSql . "
772         `Type` LIKE '%s%%'",
773                 array(
774                         $tableName,
775                         $type
776                 ), __FUNCTION__, __LINE__
777         );
778 }
779
780 // [EOF]
781 ?>