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 * -------------------------------------------------------------------- *
13 * Copyright (c) 2003 - 2009 by Roland Haeder *
14 * Copyright (c) 2009 - 2013 by Mailer Developer Team *
15 * For more information visit: http://mxchange.org *
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. *
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. *
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, *
31 ************************************************************************/
33 // Some security stuff...
34 if (!defined('__SECURITY')) {
39 function initSqls () {
41 setSqlsArray(array('generic' => array()));
44 // Checks whether the sqls array is initialized
45 function isSqlsInitialized () {
46 return ((isset($GLOBALS['sqls'])) && (is_array($GLOBALS['sqls'])));
49 // Setter for SQLs array
50 function setSqlsArray ($SQLs) {
51 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count()='.count($SQLs));
52 $GLOBALS['sqls'] = (array) $SQLs;
55 // Remover for SQLs array
56 function unsetSqls () {
57 unset($GLOBALS['sqls']);
60 // Getter for SQLs array
62 return $GLOBALS['sqls'];
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);
71 // Merge SQLs together
72 function mergeSqls ($SQLs, $type = '') {
73 // Should we merge full array or partial?
75 // Merge full array (may kill entries)
76 setSqlsArray(merge_array(getSqls(), $SQLs));
78 // Merge sub array, so get it
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);
87 $array[$type] = $SQLs;
95 // Counter for SQLs array
96 function countSqls () {
100 // Is the array there?
101 if (isSqlsInitialized()) {
103 $count = count($GLOBALS['sqls']);
104 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf('count=%d', $count));
111 // Checks whether the SQLs array is filled
112 function ifSqlsRegistered () {
113 //* DEBUG: */ debugOutput(__FUNCTION__ . ':' . intval(isSqlsInitialized()) . '/' . countSqls() . '/' . getCurrentExtensionName());
123 // Generates an updating SQL query from given array
124 function getUpdateSqlFromArray ($array, $tableName, $whereColumn, $whereData, $excludedFields, $multiDimId = NULL) {
126 $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_' . $tableName . '` SET ';
129 foreach ($array as $entry => $value) {
130 // Skip login/id entry
131 if (in_array($entry, $excludedFields)) {
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)) {
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) . ',';
151 // Strings need ticks (') around them
152 $SQL .= '`' . $entry . "`='" . sqlEscapeString($value) . "',";
155 // Handle multi-dimensional data
156 if (is_null($value[$multiDimId])) {
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]) . ',';
169 // Strings need ticks (') around them
170 $SQL .= '`' . $entry . "`='" . sqlEscapeString($value[$multiDimId]) . "',";
175 // Remove last 2 chars and finish query
176 $SQL = substr($SQL, 0, -1) . ' WHERE `' . $whereColumn . '`=' . $whereData . ' LIMIT 1';
182 // "Getter" for an "INSERT INTO" SQL query
183 function getInsertSqlFromArray ($array, $tableName) {
185 $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName . '` (`' . implode('`, `', array_keys($array)) . '`) VALUES (';
187 // Walk through all entries
188 foreach ($array as $key => $value) {
190 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',key=' . $key . ',value=' . $value);
193 if (is_null($value)) {
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) . ',';
206 // Everything else might be a string, so add ticks around it
207 $SQL .= chr(39) . sqlEscapeString($value) . chr(39) . ',';
212 $SQL = substr($SQL, 0, -1) . ')';
215 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',sql=' . $SQL);
219 // Function to unset __is_sql_link_up
220 function unsetSqlLinkUp ($file, $line) {
222 //* DEBUG: */ logDebugMessage($file, $line, __FUNCTION__ . ': Called!');
223 setSqlLink($file, $line, NULL);
226 // Initializes the SQL link by bringing it up if set
227 function initSqlLink () {
229 unsetSqlLinkUp(__FUNCTION__, __LINE__);
231 // Is the configuration data set?
232 if ((!empty($GLOBALS['mysql']['host'])) && (!empty($GLOBALS['mysql']['login'])) && (!empty($GLOBALS['mysql']['dbase']))) {
234 unsetSqlLinkUp(__FUNCTION__, __LINE__);
237 sqlConnectToDatabase($GLOBALS['mysql']['host'], $GLOBALS['mysql']['login'], $GLOBALS['mysql']['password'], __FUNCTION__, __LINE__);
239 // Is the link valid?
241 // Enable exit on error
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']);
249 // Remove MySQL array from namespace
250 unset($GLOBALS['mysql']);
253 loadIncludeOnce('inc/load_cache.php');
256 reportBug(__FUNCTION__, __LINE__, 'Wrong database selected.');
259 // No link to database!
260 reportBug(__FUNCTION__, __LINE__, 'Database link is not yet up.');
263 // Maybe you forgot to enter your database login?
264 reportBug(__FUNCTION__, __LINE__, 'Database login is missing.');
268 // Imports given SQL dump from given (relative) path and adds them to $sqlPool
269 function importSqlDump ($path, $dumpName, $sqlPool) {
271 $FQFN = getPath() . $path . '/' . $dumpName . '.sql';
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));
280 $fileContent = readSqlDump($FQFN);
282 // Merge it with existing SQL statements
283 mergeSqls(explode(";\n", $fileContent), $sqlPool);
286 // SQL string escaping
287 function sqlQueryEscaped ($sqlString, $data, $file, $line, $run = TRUE, $strip = TRUE, $secure = TRUE) {
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!');
295 // Init array for escape'd data with SQL string
296 $dataSecured = array(
297 '__sql_string' => $sqlString
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]);
308 $query = call_user_func_array('sprintf', $dataSecured);
311 // Run SQL query (default)
312 return sqlQuery($query, $file, $line);
314 // Return secured string
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)) {
324 reportBug(__FUNCTION__, __LINE__, sprintf('columns is not an array. %s != array, file=%s, line=%s',
330 // Abort here with 'false'
334 // Is this is a simple array?
335 if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
336 // Begin with SQL query
339 // No, it comes from XML, so get it back from it
340 $sql .= getSqlPartFromXmlArray($columns);
343 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
345 // Yes, prepare the SQL statement
346 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
350 return sqlQueryEscaped($sql,
359 // ALTER TABLE wrapper function
360 function sqlQueryAlterTable ($sql, $file, $line, $enableCodes = TRUE) {
361 // Abort if link is down
362 if (!isSqlLinkUp()) return FALSE;
364 // This is the default result...
367 // Determine index/fulltext/unique word
370 isInString('INDEX', $sql)
372 isInString('KEY', $sql)
374 isInString('FULLTEXT', $sql)
376 isInString('UNIQUE', $sql)
380 // Extract table name
381 $tableArray = explode(' ', $sql);
382 $tableName = str_replace('`', '', $tableArray[2]);
385 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
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])) {
394 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
398 // And column name as well
399 $columnName = $tableArray[$idx];
402 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)));
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])))))) {
407 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
408 $result = sqlQuery($sql, $file, $line, FALSE);
410 // Skip further attempt(s)
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);
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);
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)) . '');
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>');
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'))) {
438 while (isInString(',', $keyName)) {
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');
445 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
446 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
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);
465 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
468 // Other ALTER TABLE query
469 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
470 $result = sqlQuery($sql, $file, $line, $enableCodes);
477 // Getter for SQL link
478 function getSqlLink () {
482 // Is it in the globals?
483 if (isset($GLOBALS['__sql_link'])) {
485 $link = $GLOBALS['__sql_link'];
486 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - FROM GLOBALS!');
490 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - EXIT!');
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
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)));
507 $GLOBALS['__sql_link'] = $link;
510 $GLOBALS['__is_sql_link_up'] = ((function_exists('isValidSqlLink')) && (isValidSqlLink($link)));
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!');
522 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__is_sql_link_up=' . intval($GLOBALS['__is_sql_link_up']) . ' - EXIT!');
523 return $GLOBALS['__is_sql_link_up'];
526 // Wrapper function to make code more readable
527 function ifSqlHasZeroNums ($result) {
528 // Just pass it through
529 return (sqlNumRows($result) === 0);
532 // Wrapper function to make code more readable
533 function ifSqlHasZeroAffectedRows () {
534 // Just pass it through
535 return (sqlAffectedRows() === 0);
538 // Private function to prepare the SQL query string
539 function sqlPrepareQueryString ($sqlString, $enableCodes = TRUE) {
541 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ' - ENTERED!');
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));
551 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
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 . '']);
558 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ' - CACHE!');
562 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ',returned sql_string=' . $GLOBALS['sql_strings']['' . $sqlString . ''] . ' - EXIT!');
565 return $GLOBALS['sql_strings']['' . $sqlString . ''];
568 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
569 function getSqlTimestampFromUnix ($timestamp) {
570 return generateDateTime($timestamp, '7');
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);
579 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
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__);
588 if (!isValidSqlLink($result)) {
589 // Is installation phase?
591 // Then silently abort here
592 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',tableName=' . $tableName . ' - Returning FALSE ...');
595 // Please report this
596 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
600 // Is there an entry?
601 $GLOBALS[__FUNCTION__][$tableName] = (sqlNumRows($result) == 1);
602 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
606 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
607 return $GLOBALS[__FUNCTION__][$tableName];
610 // Is a table column there?
611 function ifSqlTableColumnExists ($tableName, $columnName, $forceFound = FALSE) {
613 $columnName = str_replace('`', '', $columnName);
616 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
618 // If the table is not there, it is okay
619 if (!ifSqlTableExists($tableName)) {
621 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, columnName=' . $columnName . ',forceFound=' . intval($forceFound));
622 return (($forceFound === FALSE) && (isInstaller()));
625 // Get column information
626 $result = sqlQueryEscaped("SHOW COLUMNS FROM `%s` LIKE '%s'",
630 ), __FUNCTION__, __LINE__);
633 if (!isValidSqlLink($result)) {
634 // Is installation phase?
636 // Then silently abort here
637 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',tableName=' . $tableName . ',columnName=' . $columnName . ' - Returning FALSE ...');
640 // Please report this
641 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
646 $doesExist = (!ifSqlHasZeroNums($result));
649 sqlFreeResult($result);
652 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
656 // Checks depending on the mode if the index is there
657 function ifSqlTableIndexExist ($tableName, $keyName, $forceFound = FALSE) {
659 $keyName = str_replace('`', '', $keyName);
662 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ' - ENTERED!');
664 // If the table is not there, it is okay
665 if (!ifSqlTableExists($tableName)) {
667 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Table ' . $tableName . ' does not exist, keyName=' . $keyName . ',forceFound=' . intval($forceFound));
668 return (($forceFound === FALSE) && (isInstaller()));
672 $result = sqlQueryEscaped("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
675 if (!isValidSqlLink($result)) {
676 // Is installation phase?
678 // Then silently abort here
679 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',tableName=' . $tableName . ',keyName=' . $keyName . ' - Returning FALSE ...');
682 // Please report this
683 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
687 // The key is not found by default
691 while ($content = sqlFetchArray($result)) {
692 // Is it the requested one?
693 if ($content['Key_name'] == $keyName) {
694 // Then it is found and exit
701 sqlFreeResult($result);
704 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',keyName=' . $keyName . ',doesExist=' . intval($doesExist) . ' - EXIT!');
708 // Init database layer
709 function initDatabaseLayer () {
710 // Set all required variables:
711 $GLOBALS['last_sql_error'] = '';
714 // Get last SQL error
715 function getLastSqlError () {
716 return $GLOBALS['last_sql_error'];
719 // Gets an array (or false if none is found) from all supported engines
720 function getArrayFromSupportedSqlEngines ($requestedEngine = 'ALL') {
724 // This also worked, now we need to check if the selected database type is supported
725 $result = sqlQuery('SHOW ENGINES', __FUNCTION__, __LINE__);
727 // Are there entries? (Bad if not)
728 if (!ifSqlHasZeroNums($result)) {
729 // Load all and check for active entries
730 while ($content = sqlFetchArray($result)) {
732 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'support=' . $requestedEngine . ',Engine=' . $content['Engine'] . ',Support=' . $content['Support']);
734 // Is this supported?
735 if ((($requestedEngine == 'ALL') || ($content['Engine'] == $requestedEngine)) && (in_array($content['Support'], array('YES', 'DEFAULT')))) {
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 . ')');
749 sqlFreeResult($result);
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));
760 // Default no field set
762 if (!empty($field)) {
764 $fieldSql = "`Field` LIKE '" . $field . "' AND";
768 return sqlQueryEscaped("SHOW COLUMNS FROM
769 `{?_MYSQL_PREFIX?}_%s`
776 ), __FUNCTION__, __LINE__
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);
786 if (!empty($GLOBALS['mysql']['login'])) {
787 // Secure login name in message
788 $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
791 // Is database password set?
792 if (!empty($GLOBALS['mysql']['password'])) {
793 // Secure password in message
794 $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
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);
803 // Is there installation phase?
806 * In installation phase, we don't want SQL errors abort e.g. connection
807 * tests, so just log it away.
809 logDebugMessage($file, $line, $message);
811 // Regular mode, then call reportBug()
812 reportBug($file, $line, $message);