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