Added (unfinished) a way to edit forced ads, rwritten many XML templates
[mailer.git] / inc / db / lib-mysql3.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/29/2004 *
4  * ===================                          Last change: 08/29/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : lib-mysql3.php                                   *
8  * -------------------------------------------------------------------- *
9  * Short description : Database layer for MySQL 3/4/5 server            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Datenbankschicht fuer MySQL 3/4/5 Server         *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // SQL queries
44 function SQL_QUERY ($sqlString, $F, $L, $enableCodes = true) {
45         // Do we have cache?
46         if (!isset($GLOBALS[__FUNCTION__][$sqlString])) {
47                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called: ' . $sqlString);
48
49                 // Trim SQL string
50                 $sqlStringModified = trim($sqlString);
51
52                 // Empty query string or link is not up?
53                 if (empty($sqlStringModified)) {
54                         // Empty SQL string!
55                         debug_report_bug(__FUNCTION__, __LINE__, sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
56                                 basename($F),
57                                 $L
58                         ));
59                 } elseif (!SQL_IS_LINK_UP()) {
60                         // We should not quietly ignore this
61                         debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
62                                 $sqlStringModified,
63                                 basename($F),
64                                 $L
65                         ));
66                 }
67
68                 // Remove \t, \n and \r from queries they may confuse some MySQL versions
69                 $sqlStringModified = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlStringModified)));
70
71                 // Compile config entries out
72                 $sqlStringModified = SQL_PREPARE_SQL_STRING($sqlStringModified, $enableCodes);
73
74                 // Cache it and remember as last SQL query
75                 $GLOBALS[__FUNCTION__][$sqlString] = $sqlStringModified;
76                 $GLOBALS['last_sql'] = $sqlStringModified;
77                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Stored cache: ' . $sqlStringModified);
78         }  else {
79                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
80
81                 // Use cache (to save a lot function calls
82                 $GLOBALS['last_sql'] = $GLOBALS[__FUNCTION__][$sqlString];
83
84                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache is: ' . $sqlString);
85         }
86
87         // Starting time
88         $querytimeBefore = microtime(true);
89
90         // Run SQL command
91         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
92         $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
93                 or debug_report_bug($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . "\n".
94 'Query string:' . $GLOBALS['last_sql']);
95         //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
96
97         // Calculate query time
98         $queryTime = microtime(true) - $querytimeBefore;
99
100         // Add this query to array including timing
101         addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
102
103         // Save last successfull query
104         setConfigEntry('db_last_query', $GLOBALS['last_sql']);
105
106         // Count all query times
107         incrementConfigEntry('sql_time', $queryTime);
108
109         // Count this query
110         incrementConfigEntry('sql_count');
111
112         // Debug output
113         if ((!isCssOutputMode()) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
114                 // Is this the first call?
115                 if (!isset($GLOBALS['sql_first_entry'])) {
116                         // Write first entry
117                         appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
118                         $GLOBALS['sql_first_entry'] = true;
119                 } // END - if
120
121                 // Append debug line
122                 appendLineToFile(getCachePath() . 'mysql.log', basename($F) . '|LINE=' . $L . '|NUM=' . (is_resource($result) ? SQL_NUMROWS($result) : 'false') . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $GLOBALS['last_sql'])));
123         } // END - if
124
125         // Count DB hits
126         if (!isStatsEntrySet('db_hits')) {
127                 // Count in dummy variable
128                 setStatsEntry('db_hits', 1);
129         } else {
130                 // Count to config array
131                 incrementStatsEntry('db_hits');
132         }
133
134         // Return the result
135         return $result;
136 }
137
138 // SQL num rows
139 function SQL_NUMROWS ($resource) {
140         // Valid link resource?
141         if (!SQL_IS_LINK_UP()) return false;
142
143         // Link is not up, no rows by default
144         $lines = false;
145
146         // Is the result a valid resource?
147         if (isset($GLOBALS['sql_numrows'][$resource])) {
148                 // Use cache
149                 $lines = $GLOBALS['sql_numrows'][intval($resource)];
150         } elseif (is_resource($resource)) {
151                 // Get the count of rows from database
152                 $lines = mysql_num_rows($resource);
153
154                 // Remember it in cache
155                 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
156         } else {
157                 // No resource given, please fix this
158                 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' .  $GLOBALS['last_sql']);
159         }
160
161         // Return lines
162         return $lines;
163 }
164
165 // SQL affected rows
166 function SQL_AFFECTEDROWS() {
167         // Valid link resource?
168         if (!SQL_IS_LINK_UP()) return false;
169
170         // Get affected rows
171         $lines = mysql_affected_rows(SQL_GET_LINK());
172
173         // Return it
174         return $lines;
175 }
176
177 // SQL fetch row
178 function SQL_FETCHROW ($resource) {
179         // Is a result resource set?
180         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
181
182         // Fetch the data and return it
183         return mysql_fetch_row($resource);
184 }
185
186 // SQL fetch array
187 function SQL_FETCHARRAY ($res) {
188         // Is a result resource set?
189         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
190
191         // Load row from database
192         $row = mysql_fetch_assoc($res);
193
194         // Return only arrays here
195         if (is_array($row)) {
196                 // Return row
197                 return $row;
198         } else {
199                 // Return a false, else some loops would go endless...
200                 return false;
201         }
202 }
203
204 // SQL result
205 function SQL_RESULT ($resource, $row, $field = '0') {
206         // Is $resource valid?
207         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
208
209         // Run the result command
210         $result = mysql_result($resource, $row, $field);
211
212         // ... and return the result
213         return $result;
214 }
215
216 // SQL connect
217 function SQL_CONNECT ($host, $login, $password, $F, $L) {
218         // Try to connect
219         $linkResource = mysql_connect($host, $login, $password) or debug_report_bug(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
220
221         // Set the link resource
222         SQL_SET_LINK($linkResource);
223 }
224
225 // SQL select database
226 function SQL_SELECT_DB ($dbName, $F, $L) {
227         // Is there still a valid link? If not, skip it.
228         if (!SQL_IS_LINK_UP()) return false;
229
230         // Return the result
231         return mysql_select_db($dbName, SQL_GET_LINK()) or debug_report_bug(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
232 }
233
234 // SQL close link
235 function SQL_CLOSE ($F, $L) {
236         if (!SQL_IS_LINK_UP()) {
237                 // Skip double close
238                 return false;
239         } // END - if
240
241         // Close database link and forget the link
242         $close = mysql_close(SQL_GET_LINK()) or debug_report_bug(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
243
244         // Close link
245         SQL_SET_LINK(null);
246
247         // Return the result
248         return $close;
249 }
250
251 // SQL free result
252 function SQL_FREERESULT ($resource) {
253         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
254                 // Abort here
255                 return false;
256         } // END - if
257
258         // Free result
259         $res = mysql_free_result($resource);
260
261         // And return that result of freeing it...
262         return $res;
263 }
264
265 // SQL string escaping
266 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
267         // Link is there?
268         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
269
270         // Escape all data
271         $dataSecured['__sql_string'] = $sqlString;
272         foreach ($data as $key => $value) {
273                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
274         } // END - foreach
275
276         // Generate query
277         $query = call_user_func_array('sprintf', $dataSecured);
278
279         if ($run === true) {
280                 // Run SQL query (default)
281                 return SQL_QUERY($query, $F, $L);
282         } else {
283                 // Return secured string
284                 return $query;
285         }
286 }
287
288 // Get id from last INSERT command
289 function SQL_INSERTID () {
290         if (!SQL_IS_LINK_UP()) return false;
291         return mysql_insert_id();
292 }
293
294 // Escape a string for the database
295 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
296         // Do we have cache?
297         if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
298                 // Prepare the string here
299                 $str = SQL_PREPARE_SQL_STRING($str);
300
301                 // Secure string first? (which is the default behaviour!)
302                 if ($secureString === true) {
303                         // Then do it here
304                         $str = secureString($str, $strip);
305                 } // END - if
306
307                 if (!SQL_IS_LINK_UP()) {
308                         // Fall-back to escapeQuotes() when there is no link
309                         $ret = escapeQuotes($str);
310                 } elseif (function_exists('mysql_real_escape_string')) {
311                         // The new and improved version
312                         $ret = mysql_real_escape_string($str, SQL_GET_LINK());
313                 } elseif (function_exists('mysql_escape_string')) {
314                         // The obsolete function
315                         $ret = mysql_escape_string($str, SQL_GET_LINK());
316                 } else {
317                         // If nothing else works, fall back to escapeQuotes() again
318                         $ret = escapeQuotes($str);
319                 }
320
321                 // Cache result
322                 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
323         } // END - if
324
325         // Return it
326         return $GLOBALS['sql_escapes'][''.$str.''];
327 }
328
329 // SELECT query string from table, columns and so on... ;-)
330 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
331         // Is columns an array?
332         if (!is_array($columns)) {
333                 // No array
334                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
335                         gettype($columns),
336                         basename($F),
337                         $L
338                 ));
339
340                 // Abort here with 'false'
341                 return false;
342         } // END  - if
343
344         // Is this is a simple array?
345         if ((is_array($columns[0])) && (isset($columns[0]['column']))) {
346                 // Begin with SQL query
347                 $sql = 'SELECT ';
348
349                 // No, it comes from XML, so get it back from it
350                 $sql .= getSqlPartFromXmlArray($columns);
351
352                 // Finalize it
353                 $sql .= " FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
354         } else {
355                 // Yes, prepare the SQL statement
356                 $sql = 'SELECT `' . implode('`,`', $columns) . "` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
357         }
358
359         // Return the result
360         return SQL_QUERY_ESC($sql,
361                 array(
362                         $table,
363                         $idRow,
364                         bigintval($id),
365                 ), $F, $L
366         );
367 }
368
369 // ALTER TABLE wrapper function
370 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = true) {
371         // Abort if link is down
372         if (!SQL_IS_LINK_UP()) return false;
373
374         // This is the default result...
375         $result = false;
376
377         // Determine index/fulltext/unique word
378         $isAlterIndex = (
379                 (
380                         isInString('INDEX', $sql)
381                 ) || (
382                         isInString('KEY', $sql)
383                 ) || (
384                         isInString('FULLTEXT', $sql)
385                 ) || (
386                         isInString('UNIQUE', $sql)
387                 )
388         );
389
390         // Extract table name
391         $tableArray = explode(' ', $sql);
392         $tableName = str_replace('`', '', $tableArray[2]);
393
394         // Debug log
395         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName . ',tableArray=<pre>' . print_r($tableArray, true) . '</pre>,isAlterIndex=' . intval($isAlterIndex));
396
397         // Shall we add/drop?
398         if (((isInString('ADD', $sql)) || (isInString('DROP', $sql)) || (isInString('CHANGE', $sql))) && ($isAlterIndex === false)) {
399                 // Try two columns, one should fix
400                 foreach (array(4,5) as $idx) {
401                         // If an entry is not set, abort here
402                         if (!isset($tableArray[$idx])) {
403                                 // Debug log this
404                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
405                                 break;
406                         } // END - if
407
408                         // And column name as well
409                         $columnName = $tableArray[$idx];
410
411                         // Debug log
412                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(isSqlTableColumnFound($tableName, $columnName)));
413
414                         // Do we have no entry on ADD or an entry on DROP/CHANGE?
415                         if (((!isSqlTableColumnFound($tableName, $columnName)) && (isInString('ADD', $sql))) || ((isSqlTableColumnFound($tableName, $columnName)) && ((isInString('DROP', $sql)) || ((isInString('CHANGE', $sql)) && ($idx == 4) && ((!isSqlTableColumnFound($tableName, $tableArray[5])) || ($columnName == $tableArray[5])))))) {
416                                 // Do the query
417                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
418                                 $result = SQL_QUERY($sql, $F, $L, false);
419
420                                 // Skip further attempt(s)
421                                 break;
422                         } elseif ((((isSqlTableColumnFound($tableName, $columnName)) && (isInString('ADD', $sql))) || ((!isSqlTableColumnFound($tableName, $columnName)) && ((isInString('DROP', $sql))) || (isInString('CHANGE', $sql)))) && ($columnName != 'KEY')) {
423                                 // Abort here because it is alreay there
424                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
425                                 break;
426                         } elseif ((!isSqlTableColumnFound($tableName, $columnName)) && (isInString('DROP', $sql))) {
427                                 // Abort here because we tried to drop a column which is not there (never created maybe)
428                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
429                                 break;
430                         } elseif ($columnName != 'KEY') {
431                                 // Something didn't fit, we better log it
432                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(isSqlTableColumnFound($tableName, $columnName)) . '');
433                         }
434                 } // END - foreach
435         } elseif ((getTableType() == 'InnoDB') && (isInString('FULLTEXT', $sql))) {
436                 // Skip this query silently because InnoDB does not understand fulltext indexes
437                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s", $sql, $tableName, intval((is_bool($result)) ? 0 : isSqlTableColumnFound($columnName)), $F, $L));
438         } elseif ($isAlterIndex === true) {
439                 // And column name as well without backticks
440                 $keyName = str_replace('`', '', $tableArray[5]);
441                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . ',tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
442
443                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
444                 if (in_array(strtoupper($tableArray[4]), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
445                         // Init loop
446                         $begin = 1;
447                         $keyName = ',';
448                         while (isInString(',', $keyName)) {
449                                 // Use last
450                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BEFORE');
451                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
452                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - BETWEEN');
453
454                                 // Remove brackes
455                                 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
456                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'keyName=' . $keyName . 'begin=' . $begin . ' - AFTER');
457
458                                 // Continue
459                                 $begin++;
460                         } // END while
461                 } // END - if
462
463                 // Shall we run it?
464                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ', tableArray[3]=' . $tableArray[3] . ',keyName=' . $keyName);
465                 if (($tableArray[3] == 'ADD') && (!isSqlTableIndexFound($tableName, $keyName))) {
466                         // Send it to the SQL_QUERY() function to add it
467                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - ADDING!');
468                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
469                 } elseif (($tableArray[3] == 'DROP') && (isSqlTableIndexFound($tableName, $keyName))) {
470                         // Send it to the SQL_QUERY() function to drop it
471                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ' - DROPPING!');
472                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
473                 } else {
474                         // Not executed
475                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
476                 }
477         } else {
478                 // Other ALTER TABLE query
479                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
480                 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
481         }
482
483         // Return result
484         return $result;
485 }
486
487 // Getter for SQL link
488 function SQL_GET_LINK () {
489         // Init link
490         $link = NULL;
491
492         // Is it in the globals?
493         if (isset($GLOBALS['sql_link'])) {
494                 // Then take it
495                 $link = $GLOBALS['sql_link'];
496         } // END - if
497
498         // Return it
499         return $link;
500 }
501
502 // Setter for link
503 function SQL_SET_LINK ($link) {
504         // Is this a resource or null?
505         if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
506                 // This may happen in installation phase
507                 return;
508         } elseif ((!is_resource($link)) && (!is_null($link))) {
509                 // This should never happen!
510                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Type of link is not resource or null, type=%s", gettype($link)));
511         } // END - if
512
513         // Set it
514         $GLOBALS['sql_link'] = $link;
515
516         // Re-init cache
517         $GLOBALS['is_sql_link_up'] = is_resource($link);
518 }
519
520 // Checks if the link is up
521 function SQL_IS_LINK_UP () {
522         // Default is not up
523         $linkUp = false;
524
525         // Do we have cached this?
526         if (isset($GLOBALS['is_sql_link_up'])) {
527                 // Then use this
528                 $linkUp = $GLOBALS['is_sql_link_up'];
529         } else {
530                 // Get it
531                 $linkUp = is_resource(SQL_GET_LINK());
532
533                 // And cache it
534                 $GLOBALS['is_sql_link_up'] = $linkUp;
535         }
536
537         // Return the result
538         return $linkUp;
539 }
540
541 // Wrapper function to make code more readable
542 function SQL_HASZERONUMS ($result) {
543         // Just pass it through
544         return (SQL_NUMROWS($result) === 0);
545 }
546
547 // Wrapper function to make code more readable
548 function SQL_HASZEROAFFECTED () {
549         // Just pass it through
550         return (SQL_AFFECTEDROWS() === 0);
551 }
552
553 // Private function to prepare the SQL query string
554 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
555         // Is it already cached?
556         if (!isset($GLOBALS['sql_strings'][$sqlString])) {
557                 // Compile URI codes+config+expression code
558                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG(compileUriCode($sqlString)));
559
560                 // Do final compilation
561                 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
562         } // END - if
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 SQL_EPOCHE_TO_TIMESTAMP ($timestamp) {
570         return generateDateTime($timestamp, 7);
571 }
572
573 // Check if there is a SQL table created
574 function isSqlTableCreated ($tableName) {
575         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ' - ENTERED!');
576         // Do we have cache?
577         if (!isset($GLOBALS[__FUNCTION__][$tableName])) {
578                 // Check if the table is there
579                 $result = SQL_QUERY_ESC("SHOW TABLES FROM `{?__DB_NAME?}` WHERE `Tables_in_{?__DB_NAME?}`='{?_MYSQL_PREFIX?}_%s'",
580                         array($tableName), __FILE__, __LINE__);
581
582                 // Is there an entry?
583                 $GLOBALS[__FUNCTION__][$tableName] = (SQL_NUMROWS($result) == 1);
584                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName]));
585         } // END - if
586
587         // Return cache
588         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName]) . ' - EXIT!');
589         return $GLOBALS[__FUNCTION__][$tableName];
590 }
591
592 // Is a table column there?
593 function isSqlTableColumnFound ($tableName, $columnName) {
594         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ' - ENTERED!');
595         // Do we have cache?
596         if (!isset($GLOBALS[__FUNCTION__][$tableName][$columnName])) {
597                 // And column name as well
598                 $columnName = str_replace('`', '', $columnName);
599
600                 // Get column information
601                 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
602                         array($tableName, $columnName), __FUNCTION__, __LINE__);
603
604                 // Determine it
605                 $GLOBALS[__FUNCTION__][$tableName][$columnName] = (!SQL_HASZERONUMS($result));
606                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)) . ',numRows=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]));
607
608                 // Free result
609                 SQL_FREERESULT($result);
610         } // END - if
611
612         // Return cache
613         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $columnName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$columnName]) . ' - EXIT!');
614         return $GLOBALS[__FUNCTION__][$tableName][$columnName];
615 }
616
617 // Checks depending on the mode if the index is there
618 function isSqlTableIndexFound ($tableName, $keyName) {
619         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ' - ENTERED!');
620         // Do we have cache?
621         if (!isset($GLOBALS[__FUNCTION__][$tableName][$keyName])) {
622                 // Show indexes
623                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
624
625                 // The column is not found by default
626                 $GLOBALS[__FUNCTION__][$tableName][$keyName] = false;
627
628                 // Walk through all
629                 while ($content = SQL_FETCHARRAY($result)) {
630                         // Add all entries for better caching behavior
631                         $GLOBALS[__FUNCTION__][$tableName][$content['Key_name']] = true;
632                 } // END - while
633
634                 // Free result
635                 SQL_FREERESULT($result);
636         } else {
637                 // Cache used
638                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$keyName]) . ' - CACHE!');
639         } // END - if
640
641         // Return cache
642         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableName=' . $tableName . ',columnName=' . $keyName . ',result=' . intval($GLOBALS[__FUNCTION__][$tableName][$keyName]) . ' - EXIT!');
643         return $GLOBALS[__FUNCTION__][$tableName][$keyName];
644 }
645
646 // [EOF]
647 ?>