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 - 2013 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 ifSqlsRegistered () {
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 . '`=' . 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) . ',';
156 // Strings need ticks (') around them
157 $SQL .= '`' . $entry . "`='" . sqlEscapeString($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 . '`=' . 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]) . ',';
174 // Strings need ticks (') around them
175 $SQL .= '`' . $entry . "`='" . sqlEscapeString($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 .= 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) . ',';
211 // Everything else might be a string, so add ticks around it
212 $SQL .= chr(39) . sqlEscapeString($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 ($file, $line) {
227 //* DEBUG: */ logDebugMessage($file, $line, __FUNCTION__ . ': Called!');
228 setSqlLink($file, $line, NULL);
231 // Initializes the SQL link by bringing it up if set
232 function initSqlLink () {
234 unsetSqlLinkUp(__FUNCTION__, __LINE__);
236 // Is the configuration data set?
237 if ((!empty($GLOBALS['mysql']['host'])) && (!empty($GLOBALS['mysql']['login'])) && (!empty($GLOBALS['mysql']['dbase']))) {
239 unsetSqlLinkUp(__FUNCTION__, __LINE__);
242 sqlConnectToDatabase($GLOBALS['mysql']['host'], $GLOBALS['mysql']['login'], $GLOBALS['mysql']['password'], __FUNCTION__, __LINE__);
244 // Is the link valid?
246 // Enable exit on error
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']);
254 // Remove MySQL array from namespace
255 unset($GLOBALS['mysql']);
258 loadIncludeOnce('inc/load_cache.php');
261 reportBug(__FUNCTION__, __LINE__, 'Wrong database selected.');
264 // No link to database!
265 reportBug(__FUNCTION__, __LINE__, 'Database link is not yet up.');
268 // Maybe you forgot to enter your database login?
269 reportBug(__FUNCTION__, __LINE__, 'Database login is missing.');
273 // Imports given SQL dump from given (relative) path and adds them to $sqlPool
274 function importSqlDump ($path, $dumpName, $sqlPool) {
276 $FQFN = getPath() . $path . '/' . $dumpName . '.sql';
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));
285 $fileContent = readSqlDump($FQFN);
287 // Merge it with existing SQL statements
288 mergeSqls(explode(";\n", $fileContent), $sqlPool);
291 // SQL string escaping
292 function sqlQueryEscaped ($sqlString, $data, $file, $line, $run = TRUE, $strip = TRUE, $secure = TRUE) {
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!');
300 // Init array for escape'd data with SQL string
301 $dataSecured = array(
302 '__sql_string' => $sqlString
306 foreach ($data as $key => $value) {
307 //* DEBUG: */ logDebugMessage(basename($file) . '/' . __FUNCTION__, $line . '/' . __LINE__, 'key=' . $key . ',value=' . $value . ',run=' . intval($run) . ',strip=' . intval($strip) . ',secure=' . intval($secure));
308 $dataSecured[$key] = sqlEscapeString($value, $secure, $strip);
309 //* DEBUG: */ logDebugMessage(basename($file) . '/' . __FUNCTION__, $line . '/' . __LINE__, 'dataSecured[key]=' . $dataSecured[$key]);
313 $query = call_user_func_array('sprintf', $dataSecured);
316 // Run SQL query (default)
317 return sqlQuery($query, $file, $line);
319 // Return secured string
324 // SELECT query string from table, columns and so on... ;-)
325 function getSqlResultFromArray ($table, $columns, $idRow, $id, $file, $line) {
326 // Is columns an array?
327 if (!is_array($columns)) {
329 reportBug(__FUNCTION__, __LINE__, sprintf('columns is not an array. %s != array, file=%s, line=%s',
335 // Abort here with 'false'
339 // Is this is a simple array?
340 if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
341 // Begin with SQL query
344 // No, it comes from XML, so get it back from it
345 $sql .= getSqlPartFromXmlArray($columns);
348 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
350 // Yes, prepare the SQL statement
351 $sql = 'SELECT `' . implode('`, `', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
355 return sqlQueryEscaped($sql,
364 // ALTER TABLE wrapper function
365 function sqlQueryAlterTable ($sql, $file, $line, $enableCodes = TRUE) {
366 // Abort if link is down
367 if (!isSqlLinkUp()) return FALSE;
369 // This is the default result...
372 // Determine index/fulltext/unique word
375 isInString('INDEX', $sql)
377 isInString('KEY', $sql)
379 isInString('FULLTEXT', $sql)
381 isInString('UNIQUE', $sql)
385 // Extract table name
386 $tableArray = explode(' ', $sql);
387 $tableName = str_replace('`', '', $tableArray[2]);
390 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
392 // Shall we add/drop?
393 if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === FALSE)) {
394 // Try two columns, one should fix
395 foreach (array(4,5) as $idx) {
396 // If an entry is not set, abort here
397 if (!isset($tableArray[$idx])) {
399 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
403 // And column name as well
404 $columnName = $tableArray[$idx];
407 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)));
409 // Is there no entry on ADD or an entry on DROP/CHANGE?
410 if (((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql)) || ((isInString('CHANGE', $sql)) && ($idx == 4) && ((!ifSqlTableColumnExists($tableName, $tableArray[5])) || ($columnName == $tableArray[5])))))) {
412 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
413 $result = sqlQuery($sql, $file, $line, FALSE);
415 // Skip further attempt(s)
417 } elseif ((((ifSqlTableColumnExists($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!ifSqlTableColumnExists($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
418 // Abort here because it is alreay there
419 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
421 } elseif ((!ifSqlTableColumnExists($tableName, $columnName)) && (isInString('DROP', $sql))) {
422 // Abort here because we tried to drop a column which is not there (never created maybe)
423 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
425 } elseif ($columnName != 'KEY') {
426 // Something didn't fit, we better log it
427 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(ifSqlTableColumnExists($tableName, $columnName)) . '');
430 } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
431 // Skip this query silently because InnoDB does not understand fulltext indexes
432 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf('Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s', $sql, $tableName, intval((is_bool($result)) ? 0 : ifSqlTableColumnExists($columnName)), $file, $line));
433 } elseif ($isAlterIndex === TRUE) {
434 // And column name as well without backticks
435 $keyName = str_replace('`', '', $tableArray[5]);
436 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, TRUE) . '</pre>');
438 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
439 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
443 while (isInString(',', $keyName)) {
445 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
446 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
447 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
450 $keyName = str_replace(array('(', ')'), array('', ''), $keyName);
451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
459 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
460 if (($tableArray[3] == 'ADD') && (!ifSqlTableIndexExist($tableName, $keyName))) {
461 // Send it to the sqlQuery() function to add it
462 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
463 $result = sqlQuery($sql, $file, $line, $enableCodes);
464 } elseif (($tableArray[3] == 'DROP') && (ifSqlTableIndexExist($tableName, $keyName))) {
465 // Send it to the sqlQuery() function to drop it
466 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
467 $result = sqlQuery($sql, $file, $line, $enableCodes);
470 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
473 // Other ALTER TABLE query
474 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
475 $result = sqlQuery($sql, $file, $line, $enableCodes);
482 // Getter for SQL link
483 function getSqlLink () {
487 // Is it in the globals?
488 if (isset($GLOBALS['__sql_link'])) {
490 $link = $GLOBALS['__sql_link'];
491 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - FROM GLOBALS!');
495 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'link[]=' . gettype($link) . ' - EXIT!');
500 // Do *not* add debug lines here. This will cause and endless loop
501 function setSqlLink ($file, $line, $link) {
502 // Is this a resource or null?
503 if ((ifFatalErrorsDetected()) && (isInstaller())) {
504 // This may happen in installation phase
506 } elseif ((!is_resource($link)) && (!is_null($link)) && (!$link instanceof mysqli)) {
507 // This should never happen!
508 reportBug($file . ':' . __FUNCTION__, $line . ':' . __LINE__, sprintf('Type of link is not resource, null or mysqli class, type=%s', gettype($link)));
512 $GLOBALS['__sql_link'] = $link;
515 $GLOBALS['__is_sql_link_up'] = ((function_exists('isValidSqlLink')) && (isValidSqlLink($link)));
518 // Checks if the link is up
519 function isSqlLinkUp () {
520 // Is there cached this?
521 if (!isset($GLOBALS['__is_sql_link_up'])) {
522 // Something bad went wrong
523 reportBug(__FUNCTION__, __LINE__, 'Called before setSqlLink() was called!');
527 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '__is_sql_link_up=' . intval($GLOBALS['__is_sql_link_up']) . ' - EXIT!');
528 return $GLOBALS['__is_sql_link_up'];
531 // Wrapper function to make code more readable
532 function ifSqlHasZeroNums ($result) {
533 // Just pass it through
534 return (sqlNumRows($result) === 0);
537 // Wrapper function to make code more readable
538 function ifSqlHasZeroAffectedRows () {
539 // Just pass it through
540 return (sqlAffectedRows() === 0);
543 // Private function to prepare the SQL query string
544 function sqlPrepareQueryString ($sqlString, $enableCodes = TRUE) {
546 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ' - ENTERED!');
548 // Is it already cached?
549 if (!isset($GLOBALS['sql_strings']['' . $sqlString . ''])) {
550 // Preserve escaping and compile URI codes+config+expression code
551 $sqlString2 = str_replace(chr(92), '{BACKLASH}', $sqlString);
552 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
553 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString2));
556 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString2=' . $sqlString2);
558 // Do final compilation and revert {BACKSLASH}
559 $GLOBALS['sql_strings']['' . $sqlString . ''] = doFinalCompilation($sqlString2, FALSE, $enableCodes);
560 $GLOBALS['sql_strings']['' . $sqlString . ''] = str_replace('{BACKLASH}', chr(92), $GLOBALS['sql_strings']['' . $sqlString . '']);
563 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ' - CACHE!');
567 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlString=' . $sqlString . ',enableCodes=' . intval($enableCodes) . ',returned sql_string=' . $GLOBALS['sql_strings']['' . $sqlString . ''] . ' - EXIT!');
570 return $GLOBALS['sql_strings']['' . $sqlString . ''];
573 // Creates a MySQL TIMESTAMP compatible string from given Uni* timestamp
574 function getSqlTimestampFromUnix ($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 = sqlQueryEscaped("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
590 array($tableName), __FUNCTION__, __LINE__);
593 if (!isValidSqlLink($result)) {
594 // Is installation phase?
596 // Then silently abort here
597 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',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] = (sqlNumRows($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) && (isInstaller()));
630 // Get column information
631 $result = sqlQueryEscaped("SHOW COLUMNS FROM `%s` LIKE '%s'",
635 ), __FUNCTION__, __LINE__);
638 if (!isValidSqlLink($result)) {
639 // Is installation phase?
641 // Then silently abort here
642 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',tableName=' . $tableName . ',columnName=' . $columnName . ' - Returning FALSE ...');
645 // Please report this
646 reportBug(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ' is not a resource.');
651 $doesExist = (!ifSqlHasZeroNums($result));
654 sqlFreeResult($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) && (isInstaller()));
677 $result = sqlQueryEscaped("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
680 if (!isValidSqlLink($result)) {
681 // Is installation phase?
683 // Then silently abort here
684 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'result[]=' . gettype($result) . ',isLinkUp=' . intval(isSqlLinkUp()) . ',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 = sqlFetchArray($result)) {
697 // Is it the requested one?
698 if ($content['Key_name'] == $keyName) {
699 // Then it is found and exit
706 sqlFreeResult($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 = sqlQuery('SHOW ENGINES', __FUNCTION__, __LINE__);
732 // Are there entries? (Bad if not)
733 if (!ifSqlHasZeroNums($result)) {
734 // Load all and check for active entries
735 while ($content = sqlFetchArray($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 sqlFreeResult($result);
760 // "Getter" for result from given table and field/type LIKEs
761 function sqlGetResultFromLikeColumnsType ($tableName, $field, $type) {
762 // The table should be there
763 assert(ifSqlTableExists($tableName));
765 // Default no field set
767 if (!empty($field)) {
769 $fieldSql = "`Field` LIKE '" . $field . "' AND";
773 return sqlQueryEscaped("SHOW COLUMNS FROM
774 `{?_MYSQL_PREFIX?}_%s`
781 ), __FUNCTION__, __LINE__