9d7409290610c181d7e2e35e67c5c6bf25fe420c
[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.x server             *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Datenbankschicht fuer MySQL +3.x 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, 2010 by Mailer Developer Team                    *
20  * For more information visit: http://www.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         // Trim SQL string
46         $sqlString = trim($sqlString);
47
48         // Link is up?
49         if (!SQL_IS_LINK_UP()) {
50                 // We should not quietly ignore this!
51                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
52                         $sqlString,
53                         basename($F),
54                         $L
55                 ));
56
57                 // Return 'false' because it has failed
58                 return false;
59         } elseif (empty($sqlString)) {
60                 // Empty SQL string!
61                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("SQL string is empty. Please fix this. file=%s, line=%s",
62                         basename($F),
63                         $L
64                 ));
65
66                 // This is invalid, of course
67                 return false;
68         }
69
70         // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
71         $sqlString = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlString)));
72
73         // Compile config entries out
74         $GLOBALS['last_sql'] = SQL_PREPARE_SQL_STRING($sqlString, $enableCodes);
75
76         // Starting time
77         $querytimeBefore = microtime(true);
78
79         // Run SQL command
80         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
81         $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
82                 or debug_report_bug($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . "\n".
83 'Query string:' . $GLOBALS['last_sql']);
84         //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
85
86         // Calculate query time
87         $queryTime = microtime(true) - $querytimeBefore;
88
89         // Add this query to array including timing
90         addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
91
92         // Save last successfull query
93         setConfigEntry('db_last_query', $GLOBALS['last_sql']);
94
95         // Count all query times
96         incrementConfigEntry('sql_time', $queryTime);
97
98         // Count this query
99         incrementConfigEntry('sql_count');
100
101         // Debug output
102         if ((!isCssOutputMode()) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
103                 // Is this the first call?
104                 if (!isset($GLOBALS['sql_first_entry'])) {
105                         // Write first entry
106                         appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
107                         $GLOBALS['sql_first_entry'] = true;
108                 } // END - if
109
110                 // Append debug line
111                 appendLineToFile(getCachePath() . 'mysql.log', $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $GLOBALS['last_sql'])));
112         } // END - if
113
114         // Count DB hits
115         if (!isStatsEntrySet('db_hits')) {
116                 // Count in dummy variable
117                 setStatsEntry('db_hits', 1);
118         } else {
119                 // Count to config array
120                 incrementStatsEntry('db_hits');
121         }
122
123         // Return the result
124         return $result;
125 }
126
127 // SQL num rows
128 function SQL_NUMROWS ($resource) {
129         // Valid link resource?
130         if (!SQL_IS_LINK_UP()) return false;
131
132         // Link is not up, no rows by default
133         $lines = false;
134
135         // Is the result a valid resource?
136         if (isset($GLOBALS['sql_numrows'][$resource])) {
137                 // Use cache
138                 $lines = $GLOBALS['sql_numrows'][intval($resource)];
139         } elseif (is_resource($resource)) {
140                 // Get the count of rows from database
141                 $lines = mysql_num_rows($resource);
142
143                 // Remember it in cache
144                 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
145         } else {
146                 // No resource given, please fix this
147                 debug_report_bug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' .  $GLOBALS['last_sql']);
148         }
149
150         // Return lines
151         return $lines;
152 }
153
154 // SQL affected rows
155 function SQL_AFFECTEDROWS() {
156         // Valid link resource?
157         if (!SQL_IS_LINK_UP()) return false;
158
159         // Get affected rows
160         $lines = mysql_affected_rows(SQL_GET_LINK());
161
162         // Return it
163         return $lines;
164 }
165
166 // SQL fetch row
167 function SQL_FETCHROW ($resource) {
168         // Is a result resource set?
169         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
170
171         // Fetch the data and return it
172         return mysql_fetch_row($resource);
173 }
174
175 // SQL fetch array
176 function SQL_FETCHARRAY ($res) {
177         // Is a result resource set?
178         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
179
180         // Load row from database
181         $row = mysql_fetch_assoc($res);
182
183         // Return only arrays here
184         if (is_array($row)) {
185                 // Return row
186                 return $row;
187         } else {
188                 // Return a false, else some loops would go endless...
189                 return false;
190         }
191 }
192
193 // SQL result
194 function SQL_RESULT ($resource, $row, $field = '0') {
195         // Is $resource valid?
196         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return false;
197
198         // Run the result command
199         $result = mysql_result($resource, $row, $field);
200
201         // ... and return the result
202         return $result;
203 }
204
205 // SQL connect
206 function SQL_CONNECT ($host, $login, $password, $F, $L) {
207         // Try to connect
208         $linkResource = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
209
210         // Set the link resource
211         SQL_SET_LINK($linkResource);
212
213         // Destroy cache
214         unset($GLOBALS['is_sql_link_up']);
215 }
216
217 // SQL select database
218 function SQL_SELECT_DB ($dbName, $F, $L) {
219         // Is there still a valid link? If not, skip it.
220         if (!SQL_IS_LINK_UP()) return false;
221
222         // Return the result
223         return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error());
224 }
225
226 // SQL close link
227 function SQL_CLOSE ($F, $L) {
228         if (!SQL_IS_LINK_UP()) {
229                 // Skip double close
230                 return false;
231         } // END - if
232
233         // Close database link and forget the link
234         $close = mysql_close(SQL_GET_LINK())
235                 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
236
237         // Close link
238         SQL_SET_LINK(null);
239
240         // Destroy cache
241         unset($GLOBALS['is_sql_link_up']);
242
243         // Return the result
244         return $close;
245 }
246
247 // SQL free result
248 function SQL_FREERESULT ($resource) {
249         if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
250                 // Abort here
251                 return false;
252         } // END - if
253
254         // Free result
255         $res = mysql_free_result($resource);
256
257         // And return that result of freeing it...
258         return $res;
259 }
260
261 // SQL string escaping
262 function SQL_QUERY_ESC ($sqlString, $data, $F, $L, $run = true, $strip = true, $secure = true) {
263         // Link is there?
264         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
265
266         // Escape all data
267         $dataSecured['__sql_string'] = $sqlString;
268         foreach ($data as $key => $value) {
269                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
270         } // END - foreach
271
272         // Generate query
273         $query = call_user_func_array('sprintf', $dataSecured);
274
275         if ($run === true) {
276                 // Run SQL query (default)
277                 return SQL_QUERY($query, $F, $L);
278         } else {
279                 // Return secured string
280                 return $query;
281         }
282 }
283
284 // Get id from last INSERT command
285 function SQL_INSERTID () {
286         if (!SQL_IS_LINK_UP()) return false;
287         return mysql_insert_id();
288 }
289
290 // Escape a string for the database
291 function SQL_ESCAPE ($str, $secureString = true, $strip = true) {
292         // Do we have cache?
293         if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
294                 // Secure string first? (which is the default behaviour!)
295                 if ($secureString === true) {
296                         // Then do it here
297                         $str = secureString($str, $strip);
298                 } // END - if
299
300                 if (!SQL_IS_LINK_UP()) {
301                         // Fall-back to escapeQuotes() when there is no link
302                         $ret = escapeQuotes($str);
303                 } elseif (function_exists('mysql_real_escape_string')) {
304                         // The new and improved version
305                         $ret = mysql_real_escape_string($str, SQL_GET_LINK());
306                 } elseif (function_exists('mysql_escape_string')) {
307                         // The obsolete function
308                         $ret = mysql_escape_string($str, SQL_GET_LINK());
309                 } else {
310                         // If nothing else works, fall back to escapeQuotes() again
311                         $ret = escapeQuotes($str);
312                 }
313
314                 // Cache result
315                 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
316         } // END - if
317
318         // Return it
319         return $GLOBALS['sql_escapes'][''.$str.''];
320 }
321
322 // SELECT query string from table, columns and so on... ;-)
323 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
324         // Is columns an array?
325         if (!is_array($columns)) {
326                 // No array
327                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("columns is not an array. %s != array, file=%s, line=%s",
328                         gettype($columns),
329                         basename($F),
330                         $L
331                 ));
332
333                 // Abort here with 'false'
334                 return false;
335         } // END  - if
336
337         // Prepare the SQL statement
338         $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
339
340         // Return the result
341         return SQL_QUERY_ESC($sql,
342                 array(
343                         $table,
344                         $idRow,
345                         bigintval($id),
346                 ), $F, $L
347         );
348 }
349
350 // ALTER TABLE wrapper function
351 function SQL_ALTER_TABLE ($sql, $F, $L, $enableCodes = true) {
352         // Abort if link is down
353         if (!SQL_IS_LINK_UP()) return false;
354
355         // This is the default result...
356         $result = false;
357
358         // Determine index/fulltext/unique word
359         $noIndex = (
360         (
361                 strpos($sql, 'INDEX') === false
362         ) && (
363                 strpos($sql, 'KEY') === false
364         ) && (
365                 strpos($sql, 'FULLTEXT') === false
366         ) && (
367                 strpos($sql, 'UNIQUE') === false
368         )
369         );
370
371         // Extract table name
372         $tableArray = explode(' ', $sql);
373         $tableName = str_replace('`', '', $tableArray[2]);
374
375         // Debug log
376         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sql . ',tableName=' . $tableName);
377
378         // Shall we add/drop?
379         if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false) || (strpos($sql, 'CHANGE') !== false)) && ($noIndex === true)) {
380                 // Try two columns, one should fix
381                 foreach (array(4,5) as $idx) {
382                         // If an entry is not set, abort here
383                         if (!isset($tableArray[$idx])) {
384                                 // Debug log this
385                                 logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ' is missing!');
386                                 break;
387                         } // END - if
388
389                         // And column name as well
390                         $columnName = str_replace('`', '', $tableArray[$idx]);
391
392                         // Get column information
393                         $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
394                                 array($tableName, $columnName), __FUNCTION__, __LINE__);
395
396                         // Debug log
397                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName=' . $columnName . ',idx=' . $idx . ',sql=' . $sql . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)));
398
399                         // Do we have no entry on ADD or an entry on DROP/CHANGE?
400                         // 123               4       43    3      4           4          32    23           4       4     3    3      4            4          32    23                4       43    3      4              4          3    3         321
401                         if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'CHANGE') !== false) && ($idx == 4))) {
402                                 // Do the query
403                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
404                                 $result = SQL_QUERY($sql, $F, $L, false);
405
406                                 // Skip further attempt(s)
407                                 break;
408                         //       1234                5       54    4      5           5          43    34                5       54    4      5            5          43    3      4              4          32    2                    21
409                         } elseif ((((!SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((!SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) || (strpos($sql, 'CHANGE') !== false)) && ($columnName != 'KEY')) {
410                                 // Abort here because it is alreay there
411                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: sql=' . $sql . ',columnName=' . $columnName . ',idx=' . $idx);
412                                 break;
413                         } elseif ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false)) {
414                                 // Abort here because we tried to drop a column which is not there (never created maybe)
415                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No drop: ' . $sql);
416                                 break;
417                         } elseif ($columnName != 'KEY') {
418                                 // Something didn't fit, we better log it
419                                 logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql . ',hasZeroNums=' . intval(SQL_HASZERONUMS($result)) . '');
420                         }
421                 } // END - foreach
422         } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
423                 // Skip this query silently
424                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,tableName=%s,hasZeroNums=%d,file=%s,line=%s", $sql, $tableName, intval((is_bool($result)) ? 0 : SQL_HASZERONUMS($result)), $F, $L));
425         } elseif ($noIndex === false) {
426                 // And column name as well
427                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'tableArray=<pre>' . print_r($tableArray, true) . '</pre>');
428                 $keyName = str_replace('`', '', $tableArray[5]);
429
430                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
431                 if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
432                         // Init loop
433                         $begin = 1; $keyName = ',';
434                         while (strpos($keyName, ',') !== false) {
435                                 // Use last
436                                 $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
437                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
438
439                                 // Remove brackes
440                                 $keyName = str_replace('(', '', str_replace(')', '', $keyName));
441                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
442
443                                 // Continue
444                                 $begin++;
445                         } // END while
446                 } // END - if
447
448                 // Show indexes
449                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FUNCTION__, __LINE__);
450
451                 // Non-skipping is default for ADD
452                 $skip = false;
453
454                 // But should we DROP?
455                 if ($tableArray[3] == 'DROP') {
456                         // Then skip if nothing found!
457                         $skip = true;
458                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
459                 } // END - if
460
461                 // Walk through all
462                 while ($content = SQL_FETCHARRAY($result)) {
463                         // Is it found?
464                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
465                         if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
466                                 // Skip this query!
467                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
468                                 $skip = true;
469                                 break;
470                         } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
471                                 // Don't skip this!
472                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
473                                 $skip = false;
474                                 break;
475                         }
476                 } // END - while
477
478                 // Free result
479                 SQL_FREERESULT($result);
480
481                 // Shall we run it?
482                 if ($skip === false) {
483                         // Send it to the SQL_QUERY() function
484                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
485                         $result = SQL_QUERY($sql, $F, $L, $enableCodes);
486                 } else {
487                         // Not executed
488                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
489                 }
490         } else {
491                 // Other ALTER TABLE query
492                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
493                 $result = SQL_QUERY($sql, $F, $L, $enableCodes);
494         }
495
496         // Return result
497         return $result;
498 }
499
500 // Getter for SQL link
501 function SQL_GET_LINK () {
502         // Init link
503         $link = null;
504
505         // Is it in the globals?
506         if (isset($GLOBALS['sql_link'])) {
507                 // Then take it
508                 $link = $GLOBALS['sql_link'];
509         } // END - if
510
511         // Return it
512         return $link;
513 }
514
515 // Setter for link
516 function SQL_SET_LINK ($link) {
517         // Is this a resource or null?
518         if ((ifFatalErrorsDetected()) && (isInstallationPhase())) {
519                 // This may happen in installation phase
520                 return;
521         } elseif ((!is_resource($link)) && (!is_null($link))) {
522                 // This should never happen!
523                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("link is not resource or null. Type: %s", gettype($link)));
524         } // END - if
525
526         // Set it
527         $GLOBALS['sql_link'] = $link;
528 }
529
530 // Checks if the link is up
531 function SQL_IS_LINK_UP () {
532         // Default is not up
533         $linkUp = false;
534
535         // Do we have cached this?
536         if (isset($GLOBALS['is_sql_link_up'])) {
537                 // Then use this
538                 $linkUp = $GLOBALS['is_sql_link_up'];
539         } else {
540                 // Get it
541                 $linkUp = is_resource(SQL_GET_LINK());
542
543                 // And cache it
544                 $GLOBALS['is_sql_link_up'] = $linkUp;
545         }
546
547         // Return the result
548         return $linkUp;
549 }
550
551 // Wrapper function to make code more readable
552 function SQL_HASZERONUMS ($result) {
553         // Just pass it through
554         return (SQL_NUMROWS($result) === 0);
555 }
556
557 // Wrapper function to make code more readable
558 function SQL_HASZEROAFFECTED () {
559         // Just pass it through
560         return (SQL_AFFECTEDROWS() === 0);
561 }
562
563 // Private function to prepare the SQL query string
564 function SQL_PREPARE_SQL_STRING ($sqlString, $enableCodes = true) {
565         // Is it already cached?
566         if (!isset($GLOBALS['sql_strings'][$sqlString])) {
567                 // Compile config+expression code
568                 $sqlString2 = FILTER_COMPILE_EXPRESSION_CODE(FILTER_COMPILE_CONFIG($sqlString));
569
570                 // Do final compilation
571                 $GLOBALS['sql_strings'][$sqlString] = doFinalCompilation($sqlString2, false, $enableCodes);
572                 //die($sqlString.'<br />'.$sqlString2.'<br />'.$GLOBALS['sql_strings'][$sqlString]);
573         } // END - if
574
575         // Return it
576         return $GLOBALS['sql_strings'][$sqlString];
577 }
578
579 // [EOF]
580 ?>