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