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