also prevent it in .htacces. You may want to add this to one of your files in /etc...
[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  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
14  * Copyright (c) 2009 - 2016 by Mailer Developer Team                   *
15  * For more information visit: http://mxchange.org                      *
16  *                                                                      *
17  * This program is free software; you can redistribute it and/or modify *
18  * it under the terms of the GNU General Public License as published by *
19  * the Free Software Foundation; either version 2 of the License, or    *
20  * (at your option) any later version.                                  *
21  *                                                                      *
22  * This program is distributed in the hope that it will be useful,      *
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
25  * GNU General Public License for more details.                         *
26  *                                                                      *
27  * You should have received a copy of the GNU General Public License    *
28  * along with this program; if not, write to the Free Software          *
29  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
30  * MA  02110-1301  USA                                                  *
31  ************************************************************************/
32
33 // Some security stuff...
34 if (!defined('__SECURITY')) {
35         die();
36 } // END - if
37
38 // Init SQLs array
39 function initSqls () {
40         // Init generic array
41         setSqlsArray(array('generic' => array()));
42 }
43
44 // Checks whether the sqls array is initialized
45 function isSqlsInitialized () {
46         return ((isset($GLOBALS['sqls'])) && (is_array($GLOBALS['sqls'])));
47 }
48
49 // Setter for SQLs array
50 function setSqlsArray ($SQLs) {
51         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count()='.count($SQLs));
52         $GLOBALS['sqls'] = (array) $SQLs;
53 }
54
55 // Remover for SQLs array
56 function unsetSqls () {
57         unset($GLOBALS['sqls']);
58 }
59
60 // Getter for SQLs array
61 function getSqls () {
62         return $GLOBALS['sqls'];
63 }
64
65 // Add an SQL to the list
66 function addSql ($sql) {
67         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf('sql=%s, count=%d', $sql, countSqls()));
68         array_push($GLOBALS['sqls']['generic'], $sql);
69 }
70
71 // Merge SQLs together
72 function mergeSqls ($SQLs, $type = '') {
73         // Should we merge full array or partial?
74         if (empty($type)) {
75                 // Merge full array (may kill entries)
76                 setSqlsArray(merge_array(getSqls(), $SQLs));
77         } else {
78                 // Merge sub array, so get it
79                 $array = getSqls();
80
81                 // Is the sub array there?
82                 if (isset($array[$type])) {
83                         // Then get it and merge it with the new one
84                         $array[$type] = merge_array($array[$type], $SQLs);
85                 } else {
86                         // Use new array
87                         $array[$type] = $SQLs;
88                 }
89
90                 // Call again..
91                 mergeSqls($array);
92         }
93 }
94
95 // Counter for SQLs array
96 function countSqls () {
97         // Default is false
98         $count = '0';
99
100         // Is the array there?
101         if (isSqlsInitialized()) {
102                 // Then count it
103                 $count = count($GLOBALS['sqls']);
104                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf('count=%d', $count));
105         } // END - if
106
107         // Return it
108         return $count;
109 }
110
111 // Checks whether the SQLs array is filled
112 function ifSqlsRegistered () {
113         //* DEBUG: */ debugOutput(__FUNCTION__ . ':' . intval(isSqlsInitialized()) . '/' . countSqls() . '/' . getCurrentExtensionName());
114         return (
115                 (
116                         isSqlsInitialized()
117                 ) && (
118                         countSqls() > 0
119                 )
120         );
121 }
122
123 // Generates an updating SQL query from given array
124 function getUpdateSqlFromArray ($array, $tableName, $whereColumn, $whereData, $excludedFields, $multiDimId = NULL) {
125         // Begin SQL query
126         $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_' . $tableName . '` SET ';
127
128         // Insert all data
129         foreach ($array as $entry => $value) {
130                 // Skip login/id entry
131                 if (in_array($entry, $excludedFields)) {
132                         continue;
133                 } // END - if
134
135                 // Is there a non-string (e.g. number, NULL, SQL function or back-tick at the beginning?
136                 if (is_null($multiDimId)) {
137                         // Handle one-dimensional data
138                         if (is_null($value)) {
139                                 // NULL detected
140                                 $SQL .= '`' . $entry . '`=NULL,';
141                         } elseif ((substr($value, -2, 2) == '()') || (substr($value, 0, 1) == '`')) {
142                                 // SQL function needs no ticks (')
143                                 $SQL .= '`' . $entry . '`=' . sqlEscapeString($value) . ',';
144                         } elseif ('' . bigintval($value, TRUE, FALSE) . '' == '' . $value . '')  {
145                                 // No need for ticks (')
146                                 $SQL .= '`' . $entry . '`=' . $value . ',';
147                         } elseif ('' . (float) $value . '' == '' . $value . '') {
148                                 // Float number detected
149                                 $SQL .= '`' . $entry . '`=' . sprintf(getConfig('FLOAT_MASK'), $value) . ',';
150                         } else {
151                                 // Strings need ticks (') around them
152                                 $SQL .= '`' . $entry . "`='" . sqlEscapeString($value) . "',";
153                         }
154                 } else {
155                         // Handle multi-dimensional data
156                         if (is_null($value[$multiDimId])) {
157                                 // NULL detected
158                                 $SQL .= '`' . $entry . '`=NULL,';
159                         } elseif ((substr($value[$multiDimId], -2, 2) == '()') || (substr($value[$multiDimId], 0, 1) == '`')) {
160                                 // SQL function needs no ticks (')
161                                 $SQL .= '`' . $entry . '`=' . sqlEscapeString($value[$multiDimId]) . ',';
162                         } elseif (('' . bigintval($value[$multiDimId], TRUE, FALSE) . '' == '' . $value[$multiDimId] . ''))  {
163                                 // No need for ticks (')
164                                 $SQL .= '`' . $entry . '`=' . $value[$multiDimId] . ',';
165                         } elseif ('' . (float) $value[$multiDimId] . '' == '' . $value[$multiDimId] . '') {
166                                 // Float number detected
167                                 $SQL .= '`' . $entry . '`=' . sprintf(getConfig('FLOAT_MASK'), $value[$multiDimId]) . ',';
168                         } else {
169                                 // Strings need ticks (') around them
170                                 $SQL .= '`' . $entry . "`='" . sqlEscapeString($value[$multiDimId]) . "',";
171                         }
172                 }
173         } // END - foreach
174
175         // Remove last 2 chars and finish query
176         $SQL = substr($SQL, 0, -1) . ' WHERE `' . $whereColumn . '`=' . $whereData . ' LIMIT 1';
177
178         // Return SQL query
179         return $SQL;
180 }
181
182 // "Getter" for an "INSERT INTO" SQL query
183 function getInsertSqlFromArray ($array, $tableName) {
184         // Init SQL
185         $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName . '` (`' . implode('`, `', array_keys($array)) . '`) VALUES (';
186
187         // Walk through all entries
188         foreach ($array as $key => $value) {
189                 // Log debug message
190                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',key=' . $key . ',value=' . $value);
191
192                 // Add all entries
193                 if (is_null($value)) {
194                         // Add NULL
195                         $SQL .= 'NULL,';
196                 } elseif (substr($value, -2, 2) == '()') {
197                         // SQL function needs no ticks (')
198                         $SQL .= sqlEscapeString($value) . ',';
199                 } elseif ('' . bigintval($value, TRUE, FALSE) . '' == '' . $value . '') {
200                         // Number detected, no need for ticks (')
201                         $SQL .= bigintval($value) . ',';
202                 } elseif ('' . (float) $value . '' == '' . $value . '') {
203                         // Float number detected
204                         $SQL .= sprintf(getConfig('FLOAT_MASK'), $value) . ',';
205                 } else {
206                         // Everything else might be a string, so add ticks around it
207                         $SQL .= chr(39) . sqlEscapeString($value) . chr(39) . ',';
208                 }
209         } // END - foreach
210
211         // Finish SQL query
212         $SQL = substr($SQL, 0, -1) . ')';
213
214         // Return SQL query
215         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',sql=' . $SQL);
216         return $SQL;
217 }
218
219 // Function to unset __is_sql_link_up
220 function unsetSqlLinkUp ($file, $line) {
221         // Unset it
222         //* DEBUG: */ logDebugMessage($file, $line, __FUNCTION__ . ': Called!');
223         setSqlLink($file, $line, NULL);
224 }
225
226 // Initializes the SQL link by bringing it up if set
227 function initSqlLink () {
228         // "Unset" the link
229         unsetSqlLinkUp(__FUNCTION__, __LINE__);
230
231         // Is the configuration data set?
232         if ((!empty($GLOBALS['mysql']['host'])) && (!empty($GLOBALS['mysql']['login'])) && (!empty($GLOBALS['mysql']['dbase']))) {
233                 // Remove cache
234                 unsetSqlLinkUp(__FUNCTION__, __LINE__);
235
236                 // Connect to DB
237                 sqlConnectToDatabase($GLOBALS['mysql']['host'], $GLOBALS['mysql']['login'], $GLOBALS['mysql']['password'], __FUNCTION__, __LINE__);
238
239                 // Is the link valid?
240                 if (isSqlLinkUp()) {
241                         // Enable exit on error
242                         enableExitOnError();
243
244                         // Is it a valid resource?
245                         if (sqlSelectDatabase($GLOBALS['mysql']['dbase'], __FUNCTION__, __LINE__) === TRUE) {
246                                 // Set database name (required for ext-optimize and ifSqlTableExists())
247                                 setConfigEntry('__DB_NAME', $GLOBALS['mysql']['dbase']);
248
249                                 // Remove MySQL array from namespace
250                                 unset($GLOBALS['mysql']);
251
252                                 // Load cache
253                                 loadIncludeOnce('inc/load_cache.php');
254                         } else {
255                                 // Wrong database?
256                                 reportBug(__FUNCTION__, __LINE__, 'Wrong database selected.');
257                         }
258                 } else {
259                         // No link to database!
260                         reportBug(__FUNCTION__, __LINE__, 'Database link is not yet up.');
261                 }
262         } else {
263                 // Maybe you forgot to enter your database login?
264                 reportBug(__FUNCTION__, __LINE__, 'Database login is missing.');
265         }
266 }
267
268 // Imports given SQL dump from given (relative) path and adds them to $sqlPool
269 function importSqlDump ($path, $dumpName, $sqlPool) {
270         // Construct FQFN
271         $FQFN = getPath() . $path . '/' . $dumpName . '.sql';
272
273         // Is the file readable?
274         if (!isFileReadable($FQFN)) {
275                 // Not found, which is bad
276                 reportBug(__FUNCTION__, __LINE__, sprintf('SQL dump %s/%s.sql is not readable.', $path, $dumpName));
277         } // END - if
278
279         // Then read it
280         $fileContent = readSqlDump($FQFN);
281
282         // Merge it with existing SQL statements
283         mergeSqls(explode(";\n", $fileContent), $sqlPool);
284 }
285
286 // SQL string escaping
287 function sqlQueryEscaped ($sqlString, $data, $file, $line, $run = TRUE, $strip = TRUE, $secure = TRUE) {
288         // Link is there?
289         if ((!isSqlLinkUp()) || (!is_array($data))) {
290                 // Link is down or data is not an array
291                 //* DEBUG: */ logDebugMessage($file, $line, 'isSqlLinkUp()=' . intval(isSqlLinkUp()) . ',data[]=' . gettype($data) . ',sqlString=' . $sqlString . ': ABORTING!');
292                 return FALSE;
293         } // END - if
294
295         // Init array for escape'd data with SQL string
296         $dataSecured = array(
297                 '__sql_string' => $sqlString
298         );
299
300         // Escape all data
301         foreach ($data as $key => $value) {
302                 //* DEBUG: */ logDebugMessage(basename($file) . '/' . __FUNCTION__, $line . '/' . __LINE__, 'key=' . $key . ',value=' . $value . ',run=' . intval($run) . ',strip=' . intval($strip) . ',secure=' . intval($secure));
303                 $dataSecured[$key] = sqlEscapeString($value, $secure, $strip);
304                 //* DEBUG: */ logDebugMessage(basename($file) . '/' . __FUNCTION__, $line . '/' . __LINE__, 'dataSecured[key]=' . $dataSecured[$key]);
305         } // END - foreach
306
307         // Generate query
308         $query = call_user_func_array('sprintf', $dataSecured);
309
310         if ($run === TRUE) {
311                 // Run SQL query (default)
312                 return sqlQuery($query, $file, $line);
313         } else {
314                 // Return secured string
315                 return $query;
316         }
317 }
318
319 // SELECT query string from table, columns and so on... ;-)
320 function getSqlResultFromArray ($table, $columns, $idRow, $id, $file, $line) {
321         // Is columns an array?
322         if (!is_array($columns)) {
323                 // No array
324                 reportBug(__FUNCTION__, __LINE__, sprintf('columns is not an array. %s != array, file=%s, line=%s',
325                         gettype($columns),
326                         basename($file),
327                         $line
328                 ));
329
330                 // Abort here with 'false'
331                 return FALSE;
332         } // END  - if
333
334         // Is this is a simple array?
335         if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
336                 // Begin with SQL query
337                 $sql = 'SELECT ';
338
339                 // No, it comes from XML, so get it back from it
340                 $sql .= getSqlPartFromXmlArray($columns);
341
342                 // Finalize it
343                 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
344         } else {
345                 // Yes, prepare the SQL statement
346                 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
347         }
348
349         // Return the result
350         return sqlQueryEscaped($sql,
351                 array(
352                         $table,
353                         $idRow,
354                         bigintval($id),
355                 ), $file, $line
356         );
357 }
358
359 // ALTER TABLE wrapper function
360 function sqlQueryAlterTable ($sql, $file, $line, $enableCodes = TRUE) {
361         // Abort if link is down
362         if (!isSqlLinkUp()) return FALSE;
363
364         // This is the default result...
365         $result = FALSE;
366
367         // Determine index/fulltext/unique word
368         $isAlterIndex = (
369                 (
370                         isInString('INDEX', $sql)
371                 ) || (
372                         isInString('KEY', $sql)
373                 ) || (
374                         isInString('FULLTEXT', $sql)
375                 ) || (
376                         isInString('UNIQUE', $sql)
377                 )
378         );
379
380         // Extract table name
381         $tableArray = explode(' ', $sql);
382         $tableName = str_replace('`', '', $tableArray[2]);
383
384         // Debug log
385         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
386
387         // Shall we add/drop?
388         if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
389                 // Try two columns, one should fix
390                 foreach (array(4,5) as $idx) {
391                         // If an entry is not set, abort here
392                         if (!isset($tableArray[$idx])) {
393                                 // Debug log this
394                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
395                                 break;
396                         } // END - if
397
398                         // And column name as well
399                         $columnName = $tableArray[$idx];
400
401                         // Debug log
402                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)));
403
404                         // Is there no entry on ADD or an entry on DROP/CHANGE?
405                         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])))))) {
406                                 // Do the query
407                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
408                                 $result = sqlQuery($sql, $file, $line, FALSE);
409
410                                 // Skip further attempt(s)
411                                 break;
412                         } elseif ((((ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
413                                 // Abort here because it is alreay there
414                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
415                                 break;
416                         } elseif ((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
417                                 // Abort here because we tried to drop a column which is not there (never created maybe)
418                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
419                                 break;
420                         } elseif ($columnName != 'KEY') {
421                                 // Something didn't fit, we better log it
422                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)) . '');
423                         }
424                 } // END - foreach
425         } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
426                 // Skip this query silently because InnoDB does not understand fulltext indexes
427                 //* 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));
428         } elseif ($isAlterIndex === TRUE) {
429                 // And column name as well without backticks
430                 $keyName = str_replace('`', '', $tableArray[5]);
431                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
432
433                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
434                 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
435                         // Init loop
436                         $begin = 1;
437                         $keyName = ',';
438                         while (isInString(',', $keyName)) {
439                                 // Use last
440                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
441                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
442                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
443
444                                 // Remove brackes
445                                 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
446                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
447
448                                 // Continue
449                                 $begin++;
450                         } // END while
451                 } // END - if
452
453                 // Shall we run it?
454                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
455                 if (($tableArray[3] == 'ADD') && (!ifSqlTableIndexExist($tableName, $keyName))) {
456                         // Send it to the sqlQuery() function to add it
457                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
458                         $result = sqlQuery($sql, $file, $line, $enableCodes);
459                 } elseif (($tableArray[3] == 'DROP') && (ifSqlTableIndexExist($tableName, $keyName))) {
460                         // Send it to the sqlQuery() function to drop it
461                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
462                         $result = sqlQuery($sql, $file, $line, $enableCodes);
463                 } else {
464                         // Not executed
465                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
466                 }
467         } else {
468                 // Other ALTER TABLE query
469                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
470                 $result = sqlQuery($sql, $file, $line, $enableCodes);
471         }
472
473         // Return result
474         return $result;
475 }
476
477 // Getter for SQL link
478 function getSqlLink () {
479         // Init link
480         $link = NULL;
481
482         // Is it in the globals?
483         if (isset($GLOBALS['__sql_link'])) {
484                 // Then take it
485                 $link = $GLOBALS['__sql_link'];
486                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - FROM GLOBALS!');
487         } // END - if
488
489         // Return it
490         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - EXIT!');
491         return $link;
492 }
493
494 // Setter for link
495 // Do *not* add debug lines here. This will cause and endless loop
496 function setSqlLink ($file, $line, $link) {
497         // Is this a resource or null?
498         if ((ifFatalErrorsDetected()) && (isInstaller())) {
499                 // This may happen in installation phase
500                 return;
501         } elseif ((!is_resource($link)) && (!is_null($link)) && (!$link instanceof mysqli)) {
502                 // This should never happen!
503                 reportBug($file . ':' . __FUNCTION__, $line . ':' . __LINE__, sprintf('Type of link is not resource, null or mysqli class, type=%s', gettype($link)));
504         } // END - if
505
506         // Set it
507         $GLOBALS['__sql_link'] = $link;
508
509         // Re-init cache
510         $GLOBALS['__is_sql_link_up'] = ((function_exists('isValidSqlLink')) && (isValidSqlLink($link)));
511 }
512
513 // Checks if the link is up
514 function isSqlLinkUp () {
515         // Is there cached this?
516         if (!isset($GLOBALS['__is_sql_link_up'])) {
517                 // Something bad went wrong
518                 reportBug(__FUNCTION__, __LINE__, 'Called before setSqlLink() was called!');
519         } // END - if
520
521         // Return the result
522         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__is_sql_link_up=' . intval($GLOBALS['__is_sql_link_up']) . ' - EXIT!');
523         return $GLOBALS['__is_sql_link_up'];
524 }
525
526 // Wrapper function to make code more readable
527 function ifSqlHasZeroNumRows ($result) {
528         // Just pass it through
529         return (sqlNumRows($result) === 0);
530 }
531
532 // Wrapper function to make code more readable
533 function ifSqlHasZeroAffectedRows () {
534         // Just pass it through
535         return (sqlAffectedRows() === 0);
536 }
537
538 // Private function to prepare the SQL query string
539 function sqlPrepareQueryString ($sqlString, $enableCodes = TRUE) {
540         // Debug message
541         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ' - ENTERED!');
542
543         // Is it already cached?
544         if (!isset($GLOBALS['sql_strings']['' . $sqlString . ''])) {
545                 // Preserve escaping and compile URI codes+config+expression code
546                 $sqlString2 = str_replace(chr(92), '{BACKLASH}', $sqlString);
547                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
548                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString2));
549
550                 // Debug message
551                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
552
553                 // Do final compilation and revert {BACKSLASH}
554                 $GLOBALS['sql_strings']['' . $sqlString . ''] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
555                 $GLOBALS['sql_strings']['' . $sqlString . ''] = str_replace('{BACKLASH}', chr(92), $GLOBALS['sql_strings']['' . $sqlString . '']);
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) . ',returned sql_string=' . $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 (!isValidSqlResult($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 (!isValidSqlResult($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 = (!ifSqlHasZeroNumRows($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 (!isValidSqlResult($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 (!ifSqlHasZeroNumRows($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 // Log SQL errors to debug.log in installation phase or call reportBug()
781 function logSqlError ($file, $line, $message) {
782         // Remember plain error in last_sql_error
783         setSqlError($file, $line, $message);
784
785         // Is login set?
786         if (!empty($GLOBALS['mysql']['login'])) {
787                 // Secure login name in message
788                 $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
789         } // END - if
790
791         // Is database password set?
792         if (!empty($GLOBALS['mysql']['password'])) {
793                 // Secure password in message
794                 $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
795         } // END - if
796
797         // Is database name set?
798         if (!empty($GLOBALS['mysql']['dbase'])) {
799                 // Secure database name in message
800                 $message = str_replace($GLOBALS['mysql']['dbase'], '***', $message);
801         } // END - if
802
803         // Is there installation phase?
804         if (isInstaller()) {
805                 /*
806                  * In installation phase, we don't want SQL errors abort e.g. connection
807                  * tests, so just log it away.
808                  */
809                 logDebugMessage($file, $line, $message);
810         } else {
811                 // Regular mode, then call reportBug()
812                 reportBug($file, $line, $message);
813         }
814 }
815
816 // [EOF]
817 ?>