The yearly copyright-update commit. 2009, 2010 are now copyrighted on the developer...
[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 addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error() . '<br />
89 Query string:<br />
90 ' . $sqlString);
91         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sqlString . ',numRows=' . SQL_NUMROWS($result) . ',affected=' . SQL_AFFECTEDROWS());
92
93         // Calculate query time
94         $queryTime = microtime(true) - $querytimeBefore;
95
96         // Add this query to array including timing
97         addSqlToDebug($result, $sqlString, $queryTime, $F, $L);
98
99         // Save last successfull query
100         setConfigEntry('db_last_query', $sqlString);
101
102         // Count all query times
103         incrementConfigEntry('sql_time', $queryTime);
104
105         // Count this query
106         incrementConfigEntry('sql_count');
107
108         // Debug output
109         if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y')) {
110                 //
111                 // Debugging stuff...
112                 //
113                 $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or app_die(__FILE__, __LINE__, 'Cannot write mysql.log!');
114                 if (!isset($GLOBALS['sql_first_entry'])) {
115                         // Write first entry
116                         fwrite($fp, 'Module=' . getModule() . "\n");
117                         $GLOBALS['sql_first_entry'] = true;
118                 } // END - if
119                 fwrite($fp, $F . '(LINE=' . $L . '|NUM=' . SQL_NUMROWS($result) . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . $queryTime . '): ' . str_replace("\r", '', str_replace("\n", ' ', $sqlString)) . "\n");
120                 fclose($fp);
121         } // END - if
122
123         // Count DB hits
124         if (!isStatsEntrySet('db_hits')) {
125                 // Count in dummy variable
126                 setStatsEntry('db_hits', 1);
127         } else {
128                 // Count to config array
129                 incrementStatsEntry('db_hits');
130         }
131
132         // Return the result
133         return $result;
134 }
135
136 // SQL num rows
137 function SQL_NUMROWS ($result) {
138         // Link is not up, no rows by default
139         $lines = false;
140
141         // Is the result a valid resource?
142         if (is_resource($result)) {
143                 // Get the count of rows from database
144                 $lines = mysql_num_rows($result);
145
146                 // Is the result empty? Then we have an error!
147                 if (empty($lines)) $lines = '0';
148         } elseif (SQL_IS_LINK_UP()) {
149                 // No resource given, no lines found!
150                 $lines = '0';
151         }
152
153         // Return lines
154         return $lines;
155 }
156
157 // SQL affected rows
158 function SQL_AFFECTEDROWS() {
159         // Valid link resource?
160         if (!SQL_IS_LINK_UP()) return false;
161
162         // Get affected rows
163         $lines = mysql_affected_rows(SQL_GET_LINK());
164
165         // Return it
166         return $lines;
167 }
168
169 // SQL fetch row
170 function SQL_FETCHROW ($result) {
171         // Is a result resource set?
172         if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) return false;
173
174         // Fetch the data and return it
175         return mysql_fetch_row($result);
176 }
177
178 // SQL fetch array
179 function SQL_FETCHARRAY ($res, $nr=0, $remove_numerical=true) {
180         // Is a result resource set?
181         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
182
183         // Initialize array
184         $row = array();
185
186         // Load row from database
187         $row = mysql_fetch_array($res);
188
189         // Return only arrays here
190         if (is_array($row)) {
191                 // Shall we remove numerical data here automatically?
192                 if ($remove_numerical) {
193                         // So let's remove all numerical elements to save memory!
194                         $max = count($row);
195                         for ($idx = '0'; $idx < ($max / 2); $idx++) {
196                                 // Remove entry
197                                 unset($row[$idx]);
198                         } // END - for
199                 } // END - if
200
201                 // Return row
202                 return $row;
203         } else {
204                 // Return a false here...
205                 return false;
206         }
207 }
208
209 // SQL result
210 function SQL_RESULT ($res, $row, $field = '0') {
211         // Is $res valid?
212         if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
213
214         // Run the result command and return the result
215         $result = mysql_result($res, $row, $field);
216         return $result;
217 }
218
219 // SQL connect
220 function SQL_CONNECT ($host, $login, $password, $F, $L) {
221         // Try to connect
222         $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
223
224         // Set the link resource
225         SQL_SET_LINK($connect);
226
227         // Destroy cache
228         unset($GLOBALS['sql_link_res']);
229 }
230
231 // SQL select database
232 function SQL_SELECT_DB ($dbName, $F, $L) {
233         // Is there still a valid link? If not, skip it.
234         if (!SQL_IS_LINK_UP()) return false;
235
236         // Return the result
237         return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
238 }
239
240 // SQL close link
241 function SQL_CLOSE ($F, $L) {
242         if (!SQL_IS_LINK_UP()) {
243                 // Skip double close
244                 return false;
245         } // END - if
246
247         // Close database link and forget the link
248         $close = mysql_close(SQL_GET_LINK())
249                 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
250
251         // Close link
252         SQL_SET_LINK(null);
253
254         // Destroy cache
255         unset($GLOBALS['sql_link_res']);
256
257         // Return the result
258         return $close;
259 }
260
261 // SQL free result
262 function SQL_FREERESULT ($result) {
263         if ((!is_resource($result)) || (!SQL_IS_LINK_UP())) {
264                 // Abort here
265                 return false;
266         } // END - if
267
268         $res = mysql_free_result($result);
269         return $res;
270 }
271
272 // SQL string escaping
273 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure=true) {
274         // Link is there?
275         if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
276
277         // Escape all data
278         $dataSecured['__sql_string'] = $qstring;
279         foreach ($data as $key => $value) {
280                 $dataSecured[$key] = SQL_ESCAPE($value, $secure, $strip);
281         } // END - foreach
282
283         // Generate query
284         $query = call_user_func_array('sprintf', $dataSecured);
285
286         // Debugging
287         //
288         //* DEBUG: */ $fp = fopen(getConfig('CACHE_PATH') . 'escape_debug.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write debug.log!");
289         //* DEBUG: */ fwrite($fp, $F.'('.$L."): ".str_replace("\r", '', str_replace("\n", ' ', $eval))."\n");
290         //* DEBUG: */ fclose($fp);
291
292         if ($run === true) {
293                 // Run SQL query (default)
294                 return SQL_QUERY($query, $F, $L);
295         } else {
296                 // Return secured string
297                 return $query;
298         }
299 }
300
301 // Get id from last INSERT command
302 function SQL_INSERTID () {
303         if (!SQL_IS_LINK_UP()) return false;
304         return mysql_insert_id();
305 }
306
307 // Escape a string for the database
308 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
309         // Do we have cache?
310         if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
311                 // Secure string first? (which is the default behaviour!)
312                 if ($secureString === true) {
313                         // Then do it here
314                         $str = secureString($str, $strip);
315                 } // END - if
316
317                 if (!SQL_IS_LINK_UP()) {
318                         // Fall-back to escapeQuotes() when there is no link
319                         $ret = escapeQuotes($str);
320                 } elseif (function_exists('mysql_real_escape_string')) {
321                         // The new and improved version
322                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
323                         $ret = mysql_real_escape_string($str, SQL_GET_LINK());
324                 } elseif (function_exists('mysql_escape_string')) {
325                         // The obsolete function
326                         $ret = mysql_escape_string($str, SQL_GET_LINK());
327                 } else {
328                         // If nothing else works, fall back to escapeQuotes() again
329                         $ret = escapeQuotes($str);
330                 }
331
332                 // Cache result
333                 $GLOBALS['sql_escapes'][''.$str.''] = $ret;
334         } // END - if
335
336         // Return it
337         return $GLOBALS['sql_escapes'][''.$str.''];
338 }
339
340 // SELECT query string from table, columns and so on... ;-)
341 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
342         // Is columns an array?
343         if (!is_array($columns)) {
344                 // No array
345                 debug_report_bug(sprintf("columns is not an array. %s != array, file=%s, line=%s",
346                         gettype($columns),
347                         basename($F),
348                         $L
349                 ));
350
351                 // Abort here with 'false'
352                 return false;
353         } // END  - if
354
355         // Prepare the SQL statement
356         $sql = "SELECT `".implode("`,`", $columns)."` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`='%s' LIMIT 1";
357
358         // Return the result
359         return SQL_QUERY_ESC($sql,
360                 array(
361                         $table,
362                         $idRow,
363                         bigintval($id),
364                 ), $F, $L
365         );
366 }
367
368 // ALTER TABLE wrapper function
369 function SQL_ALTER_TABLE ($sql, $F, $L) {
370         // Abort if link is down
371         if (!SQL_IS_LINK_UP()) return false;
372
373         // This is the default result...
374         $result = false;
375
376         // Determine index/fulltext/unique word
377         $noIndex = (
378         (
379                 strpos($sql, 'INDEX') === false
380         ) && (
381                 strpos($sql, 'KEY') === false
382         ) && (
383                 strpos($sql, 'FULLTEXT') === false
384         ) && (
385                 strpos($sql, 'UNIQUE') === false
386         )
387         );
388
389         // Extract table name
390         $tableArray = explode(' ', $sql);
391         $tableName = str_replace('`', '', $tableArray[2]);
392
393         // Shall we add/drop?
394         if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
395                 // Try two columns, one should fix
396                 foreach (array(4,5) as $idx) {
397                         // And column name as well
398                         $columnName = str_replace('`', '', $tableArray[$idx]);
399
400                         // Get column information
401                         $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
402                                 array($tableName, $columnName), __FILE__, __LINE__);
403
404                         // Do we have no entry on ADD or an entry on DROP?
405                         // 123           4       4     3    3      4           4          32    23           4       4     3    3      4            4          321
406                         if (((SQL_NUMROWS($result) == '0') && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
407                                 // Do the query
408                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
409                                 $result = SQL_QUERY($sql, $F, $L, false);
410
411                                 // Skip further attempt(s)
412                                 break;
413                         } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == '0') && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
414                                 // Abort here because it is alreay there
415                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
416                                 break;
417                         } elseif ($columnName != 'KEY') {
418                                 // Something didn't fit
419                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
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,file=%s,line=%s", $sql, $F, $L));
425         } elseif ($noIndex === false) {
426                 // And column name as well
427                 //* DEBUG: */ print __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), __FILE__, __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: */ print(__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, false);
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, false);
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 ((!is_resource($link)) && (!is_null($link))) {
519                 // This should never happen!
520                 debug_report_bug(sprintf("link is not resource or null. Type: %s", gettype($link)));
521         } // END - if
522
523         // Set it
524         $GLOBALS['sql_link'] = $link;
525 }
526
527 // Checks if the link is up
528 function SQL_IS_LINK_UP () {
529         // Default is not up
530         $linkUp = false;
531
532         // Do we have cached this?
533         if (isset($GLOBALS['sql_link_res'])) {
534                 // Then use this
535                 $linkUp = $GLOBALS['sql_link_res'];
536         } else {
537                 // Get it
538                 $linkUp = is_resource(SQL_GET_LINK());
539
540                 // And cache it
541                 $GLOBALS['sql_link_res'] = $linkUp;
542         }
543
544         // Return the result
545         return $linkUp;
546 }
547
548 // [EOF]
549 ?>