2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 10/23/2009 *
4 * =================== Last change: 10/23/2009 *
6 * -------------------------------------------------------------------- *
7 * File : sql-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : SQL functions to handle queries *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : SQL-Funktionen fuer Queries *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2012 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
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. *
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. *
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, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
44 function initSqls () {
46 setSqlsArray(array('generic' => array()));
49 // Checks whether the sqls array is initialized
50 function isSqlsInitialized () {
51 return ((isset($GLOBALS['sqls'])) && (is_array($GLOBALS['sqls'])));
54 // Setter for SQLs array
55 function setSqlsArray ($SQLs) {
56 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count()='.count($SQLs));
57 $GLOBALS['sqls'] = (array) $SQLs;
60 // Remover for SQLs array
61 function unsetSqls () {
62 unset($GLOBALS['sqls']);
65 // Getter for SQLs array
67 return $GLOBALS['sqls'];
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);
76 // Merge SQLs together
77 function mergeSqls ($SQLs, $type = '') {
78 // Should we merge full array or partial?
80 // Merge full array (may kill entries)
81 setSqlsArray(merge_array(getSqls(), $SQLs));
83 // Merge sub array, so get it
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);
92 $array[$type] = $SQLs;
100 // Counter for SQLs array
101 function countSqls () {
105 // Is the array there?
106 if (isSqlsInitialized()) {
108 $count = count($GLOBALS['sqls']);
109 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("count=%d", $count));
116 // Checks whether the SQLs array is filled
117 function isSqlsValid () {
118 //* DEBUG: */ debugOutput(__FUNCTION__ . ':' . intval(isSqlsInitialized()) . '/' . countSqls() . '/' . getCurrentExtensionName());
128 // Generates an updating SQL query from given array
129 function getUpdateSqlFromArray ($array, $tableName, $whereColumn, $whereData, $excludedFields, $multiDimId = NULL) {
131 $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_' . $tableName . '` SET ';
134 foreach ($array as $entry => $value) {
135 // Skip login/id entry
136 if (in_array($entry, $excludedFields)) {
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)) {
145 $SQL .= '`' . $entry . '`=NULL,';
146 } elseif ((substr($value, -2, 2) == '()') || (substr($value, 0, 1) == '`')) {
147 // SQL function needs no ticks (')
148 $SQL .= '`' . $entry . '`=' . SQL_ESCAPE($value) . ',';
149 } elseif ('' . bigintval($value, TRUE, FALSE) . '' == '' . $value . '') {
150 // No need for ticks (')
151 $SQL .= '`' . $entry . '`=' . $value . ',';
152 } elseif ('' . (float) $value . '' == '' . $value . '') {
153 // Float number detected
154 $SQL .= '`' . $entry . '`=' . sprintf(getConfig('FLOAT_MASK'), $value) . ',';
156 // Strings need ticks (') around them
157 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value) . "',";
160 // Handle multi-dimensional data
161 if (is_null($value[$multiDimId])) {
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 . '`=' . SQL_ESCAPE($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]) . ',';
174 // Strings need ticks (') around them
175 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$multiDimId]) . "',";
180 // Remove last 2 chars and finish query
181 $SQL = substr($SQL, 0, -1) . ' WHERE `' . $whereColumn . '`=' . $whereData . ' LIMIT 1';
187 // "Getter" for an "INSERT INTO" SQL query
188 function getInsertSqlFromArray ($array, $tableName) {
190 $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName . '` (`' . implode('`, `', array_keys($array)) . '`) VALUES (';
192 // Walk through all entries
193 foreach ($array as $key => $value) {
195 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',key=' . $key . ',value=' . $value);
198 if (is_null($value)) {
201 } elseif (substr($value, -2, 2) == '()') {
202 // SQL function needs no ticks (')
203 $SQL .= SQL_ESCAPE($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) . ',';
211 // Everything else might be a string, so add ticks around it
212 $SQL .= chr(39) . SQL_ESCAPE($value) . chr(39) . ',';
217 $SQL = substr($SQL, 0, -1) . ')';
220 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',sql=' . $SQL);
224 // Function to unset __is_sql_link_up
225 function unsetSqlLinkUp ($F, $L) {
227 //* DEBUG: */ logDebugMessage($F, $L, __FUNCTION__ . ': Called!');
228 SQL_SET_LINK($F, $L, NULL);
231 // Initializes the SQL link by bringing it up if set
232 function initSqlLink () {
234 unsetSqlLinkUp(__FUNCTION__, __LINE__);
236 // Do this only if link is down
237 assert(!SQL_IS_LINK_UP());
239 // Is the configuration data set?
240 if ((!empty($GLOBALS['mysql']['host'])) && (!empty($GLOBALS['mysql']['login'])) && (!empty($GLOBALS['mysql']['dbase']))) {
242 unsetSqlLinkUp(__FUNCTION__, __LINE__);
245 SQL_CONNECT($GLOBALS['mysql']['host'], $GLOBALS['mysql']['login'], $GLOBALS['mysql']['password'], __FUNCTION__, __LINE__);
247 // Is the link valid?
248 if (SQL_IS_LINK_UP()) {
249 // Enable exit on error
252 // Is it a valid resource?
253 if (SQL_SELECT_DB($GLOBALS['mysql']['dbase'], __FUNCTION__, __LINE__) === TRUE) {
254 // Set database name (required for ext-optimize and ifSqlTableExists())
255 setConfigEntry('__DB_NAME', $GLOBALS['mysql']['dbase']);
257 // Remove MySQL array from namespace
258 unset($GLOBALS['mysql']);
261 loadIncludeOnce('inc/load_cache.php');
264 reportBug(__FUNCTION__, __LINE__, 'Wrong database selected.');
267 // No link to database!
268 reportBug(__FUNCTION__, __LINE__, 'Database link is not yet up.');
271 // Maybe you forgot to enter your database login?
272 reportBug(__FUNCTION__, __LINE__, 'Database login is missing.');
276 // Imports given SQL dump from given (relative) path and adds them to $sqlPool
277 function importSqlDump ($path, $dumpName, $sqlPool) {
279 $FQFN = getPath() . $path . '/' . $dumpName . '.sql';
281 // Is the file readable?
282 if (!isFileReadable($FQFN)) {
283 // Not found, which is bad
284 reportBug(__FUNCTION__, __LINE__, sprintf("SQL dump %s/%s.sql is not readable.", $path, $dumpName));
288 $fileContent = readSqlDump($FQFN);
290 // Merge it with existing SQL statements
291 mergeSqls(explode(";\n", $fileContent), $sqlPool);
294 // SQL string escaping
295 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = TRUE, $strip = TRUE, $secure = TRUE) {
297 if ((!SQL_IS_LINK_UP()) || (!is_array($data))) {
298 // Link is down or data is not an array
299 //* DEBUG: */ logDebugMessage($F, $L, 'SQL_IS_LINK_UP()=' . intval(SQL_IS_LINK_UP()) . ',data[]=' . gettype($data) . ',sqlString=' . $sqlString . ': ABORTING!');
303 // Init array for escape'd data with SQL string
304 $dataSecured = array(
305 '__sql_string' => $sqlString
309 foreach ($data as $key => $value) {
310 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
314 $query = call_user_func_array('sprintf', $dataSecured);
317 // Run SQL query (default)
318 return SQL_QUERY($query, $F, $L);
320 // Return secured string
325 // SELECT query string from table, columns and so on... ;-)
326 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
327 // Is columns an array?
328 if (!is_array($columns)) {
330 reportBug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
336 // Abort here with 'false'
340 // Is this is a simple array?
341 if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
342 // Begin with SQL query
345 // No, it comes from XML, so get it back from it
346 $sql .= getSqlPartFromXmlArray($columns);
349 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
351 // Yes, prepare the SQL statement
352 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
356 return SQL_QUERY_ESC($sql,
365 // ALTER TABLE wrapper function
366 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = TRUE) {
367 // Abort if link is down
368 if (!SQL_IS_LINK_UP()) return FALSE;
370 // This is the default result...
373 // Determine index/fulltext/unique word
376 isInString('INDEX', $sql)
378 isInString('KEY', $sql)
380 isInString('FULLTEXT', $sql)
382 isInString('UNIQUE', $sql)
386 // Extract table name
387 $tableArray = explode(' ', $sql);
388 $tableName = str_replace('`', '', $tableArray[2]);
391 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
393 // Shall we add/drop?
394 if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
395 // Try two columns, one should fix
396 foreach (array(4,5) as $idx) {
397 // If an entry is not set, abort here
398 if (!isset($tableArray[$idx])) {
400 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
404 // And column name as well
405 $columnName = $tableArray[$idx];
408 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)));
410 // Is there no entry on ADD or an entry on DROP/CHANGE?
411 if (((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql)) || ((isInString('CHANGE', $sql)) && ($idx == 4) && ((!ifSqlTableColumnExists($tableName, $tableArray[5])) || ($columnName == $tableArray[5])))))) {
413 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
414 $result = SQL_QUERY($sql, $F, $L, FALSE);
416 // Skip further attempt(s)
418 } elseif ((((ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
419 // Abort here because it is alreay there
420 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
422 } elseif ((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
423 // Abort here because we tried to drop a column which is not there (never created maybe)
424 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
426 } elseif ($columnName != 'KEY') {
427 // Something didn't fit, we better log it
428 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)) . '');
431 } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
432 // Skip this query silently because InnoDB does not understand fulltext indexes
433 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s", $sql, $tableName, intval((is_bool($result)) ? 0 : ifSqlTableColumnExists($columnName)), $F, $L));
434 } elseif ($isAlterIndex === TRUE) {
435 // And column name as well without backticks
436 $keyName = str_replace('`', '', $tableArray[5]);
437 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
439 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
440 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
444 while (isInString(',', $keyName)) {
446 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
447 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
448 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
451 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
452 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
460 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
461 if (($tableArray[3] == 'ADD') && (!ifSqlTableIndexExist($tableName, $keyName))) {
462 // Send it to the SQL_QUERY() function to add it
463 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
464 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
465 } elseif (($tableArray[3] == 'DROP') && (ifSqlTableIndexExist($tableName, $keyName))) {
466 // Send it to the SQL_QUERY() function to drop it
467 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
468 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
471 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
474 // Other ALTER TABLE query
475 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
476 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
483 // Getter for SQL link
484 function SQL_GET_LINK () {
488 // Is it in the globals?
489 if (isset($GLOBALS['__sql_link'])) {
491 $link = $GLOBALS['__sql_link'];
492 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - FROM GLOBALS!');
496 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - EXIT!');
501 function SQL_SET_LINK ($F, $L, $link) {
502 //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'link[]=' . gettype($link) . ' - ENTERED!');
503 // Is this a resource or null?
504 if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
505 // This may happen in installation phase
506 //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'Some fatal errors detected in installation phase.');
508 } elseif ((!is_resource($link)) && (!is_null($link))) {
509 // This should never happen!
510 reportBug($F . ':' . __FUNCTION__, $L . ':' . __LINE__, sprintf("Type of link is not resource or null, type=%s", gettype($link)));
514 $GLOBALS['__sql_link'] = $link;
517 $GLOBALS['__is_sql_link_up'] = is_resource($link);
518 //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, '__is_sql_link_up=' . intval($GLOBALS['__is_sql_link_up']) . ' - EXIT!');
521 // Checks if the link is up
522 function SQL_IS_LINK_UP () {
523 // Is there cached this?
524 if (!isset($GLOBALS['__is_sql_link_up'])) {
525 // Something bad went wrong
526 reportBug(__FUNCTION__, __LINE__, 'Called before SQL_SET_LINK() was called!');
530 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__is_sql_link_up=' . intval($GLOBALS['__is_sql_link_up']) . ' - EXIT!');
531 return $GLOBALS['__is_sql_link_up'];
534 // Wrapper function to make code more readable
535 function SQL_HASZERONUMS ($result) {
536 // Just pass it through
537 return (SQL_NUMROWS($result) === 0);
540 // Wrapper function to make code more readable
541 function SQL_HASZEROAFFECTED () {
542 // Just pass it through
543 return (SQL_AFFECTEDROWS() === 0);
546 // Private function to prepare the SQL query string
547 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = TRUE) {
549 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ' - ENTERED!');
551 // Is it already cached?
552 if (!isset($GLOBALS['sql_strings']['' . $sqlString . ''])) {
553 // Preserve escaping and compile URI codes+config+expression code
554 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
557 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
559 // Do final compilation and revert {ESCAPE}
560 $GLOBALS['sql_strings']['' . $sqlString . ''] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
563 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ' - CACHE!');
567 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ',sql_strings=' . $GLOBALS['sql_strings']['' . $sqlString . ''] . ' - EXIT!');
570 return $GLOBALS['sql_strings']['' . $sqlString . ''];
573 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
574 function SQL_EPOCHE_TO_TIMESTAMP ($timestamp) {
575 return generateDateTime($timestamp, 7);
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);
584 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
587 if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
588 // Check if the table is there
589 $result = SQL_QUERY_ESC("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
590 array($tableName), __FUNCTION__, __LINE__);
593 if (!is_resource($result)) {
594 // Is installation phase?
595 if (isInstallationPhase()) {
596 // Then silently abort here
597 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ' - Returning FALSE ...');
600 // Please report this
601 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
605 // Is there an entry?
606 $GLOBALS[__FUNCTION__][$tableName] = (SQL_NUMROWS($result) == 1);
607 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
611 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
612 return $GLOBALS[__FUNCTION__][$tableName];
615 // Is a table column there?
616 function ifSqlTableColumnExists ($tableName, $columnName, $forceFound = FALSE) {
618 $columnName = str_replace('`', '', $columnName);
621 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
623 // If the table is not there, it is okay
624 if (!ifSqlTableExists($tableName)) {
626 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, columnName=' . $columnName . ',forceFound=' . intval($forceFound));
627 return (($forceFound === FALSE) && (isInstallationPhase()));
630 // Get column information
631 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
635 ), __FUNCTION__, __LINE__);
638 if (!is_resource($result)) {
639 // Is installation phase?
640 if (isInstallationPhase()) {
641 // Then silently abort here
642 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ',columnName=' . $columnName . ' - Returning FALSE ...');
645 // Please report this
646 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
651 $doesExist = (!SQL_HASZERONUMS($result));
654 SQL_FREERESULT($result);
657 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
661 // Checks depending on the mode if the index is there
662 function ifSqlTableIndexExist ($tableName, $keyName, $forceFound = FALSE) {
664 $keyName = str_replace('`', '', $keyName);
667 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ' - ENTERED!');
669 // If the table is not there, it is okay
670 if (!ifSqlTableExists($tableName)) {
672 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, keyName=' . $keyName . ',forceFound=' . intval($forceFound));
673 return (($forceFound === FALSE) && (isInstallationPhase()));
677 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
680 if (!is_resource($result)) {
681 // Is installation phase?
682 if (isInstallationPhase()) {
683 // Then silently abort here
684 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(SQL_IS_LINK_UP()) . ',tableName=' . $tableName . ',keyName=' . $keyName . ' - Returning FALSE ...');
687 // Please report this
688 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
692 // The key is not found by default
696 while ($content = SQL_FETCHARRAY($result)) {
697 // Is it the requested one?
698 if ($content['Key_name'] == $keyName) {
699 // Then it is found and exit
706 SQL_FREERESULT($result);
709 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
713 // Init database layer
714 function initDatabaseLayer () {
715 // Set all required variables:
716 $GLOBALS['last_sql_error'] = '';
719 // Get last SQL error
720 function getLastSqlError () {
721 return $GLOBALS['last_sql_error'];
724 // Gets an array (or false if none is found) from all supported engines
725 function getArrayFromSupportedSqlEngines ($requestedEngine = 'ALL') {
729 // This also worked, now we need to check if the selected database type is supported
730 $result = SQL_QUERY('SHOW ENGINES', __FUNCTION__, __LINE__);
732 // Are there entries? (Bad if not)
733 if (!SQL_HASZERONUMS($result)) {
734 // Load all and check for active entries
735 while ($content = SQL_FETCHARRAY($result)) {
737 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'support=' . $requestedEngine . ',Engine=' . $content['Engine'] . ',Support=' . $content['Support']);
739 // Is this supported?
740 if ((($requestedEngine == 'ALL') || ($content['Engine'] == $requestedEngine)) && (in_array($content['Support'], array('YES', 'DEFAULT')))) {
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 . ')');
754 SQL_FREERESULT($result);