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