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