e07cd405b535edf5239bf4120767c76b1fb07f2f
[mailer.git] / inc / db / lib-mysql3.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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 - 2008 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
42         require($INC);
43 }
44
45 // SQL queries
46 function SQL_QUERY ($sql_string, $F, $L) {
47         // Link is up?
48         if (!SQL_IS_LINK_UP()) {
49                 // We should not quietly ignore this!
50                 trigger_error(sprintf("Cannot query database: sql_string=%s,file=%s,line=%s",
51                         $sql_string,
52                         basename($F),
53                         $L
54                 ));
55
56                 // Return 'false' because it has failed
57                 return false;
58         } // END - if
59
60         // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
61         $sql_string = str_replace("\t", " ", str_replace("\n", " ", str_replace("\r", " ", $sql_string)));
62
63         // Replace {!_MYSQL_PREFIX!} with constant, closes #84. Thanks to profi-concept
64         $sql_string = str_replace("{!_MYSQL_PREFIX!}", getConfig('_MYSQL_PREFIX'), $sql_string);
65
66         // Replace {!_TABLE_TYPE!} with constant
67         $sql_string = str_replace("{!_TABLE_TYPE!}", getConfig('_TABLE_TYPE'), $sql_string);
68
69         // Starting time
70         $querytimeBefore = array_sum(explode(' ', microtime()));
71
72         // Run SQL command
73         //* DEBUG: */ echo $sql_string."<br />\n";
74         $result = mysql_query($sql_string, SQL_GET_LINK())
75                 or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error()."<br />
76 Query string:<br />
77 ".$sql_string);
78
79         // Ending time
80         $querytimeAfter = array_sum(explode(' ', microtime()));
81
82         // Calculate query time
83         $queryTime = $querytimeAfter - $querytimeBefore;
84
85         // Save last successfull query
86         setConfigEntry('db_last_query', $sql_string);
87
88         // Count this query
89         incrementConfigEntry('sql_count');
90
91         // Debug output
92         //* DEBUG: */ print "Query=<pre>".$sql_string."</pre>, affected=<strong>".SQL_AFFECTEDROWS()."</strong>, numrows=<strong>".SQL_NUMROWS($result)."</strong><br />\n";
93         if ((getOutputMode() != '1') && (getOutputMode() != '-1') && (isDebugModeEnabled()) && (getConfig('DEBUG_SQL') == 'Y')) {
94                 //
95                 // Debugging stuff...
96                 //
97                 $fp = fopen(constant('PATH') . 'inc/cache/mysql.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write mysql.log!");
98                 if (!isset($GLOBALS['sql_first_entry'])) {
99                         // Write first entry
100                         fwrite($fp, 'Module=' . getModule() . "\n");
101                         $GLOBALS['sql_first_entry'] = true;
102                 } // END - if
103                 fwrite($fp, $F."(LINE=".$L."|NUM=".SQL_NUMROWS($result)."|AFFECTED=".SQL_AFFECTEDROWS()."|QUERYTIME:".$queryTime."): ".str_replace("\r", '', str_replace("\n", " ", $sql_string))."\n");
104                 fclose($fp);
105         } // END - if
106
107         // Count DB hits
108         if (!isConfigEntrySet('db_hits_run')) {
109                 // Count in dummy variable
110                 setConfigEntry('db_hits_run', 1);
111         } else {
112                 // Count to config array
113                 incrementConfigEntry('db_hits_run');
114         }
115
116         // Return the result
117         return $result;
118 }
119
120 // SQL num rows
121 function SQL_NUMROWS ($result) {
122         // Is the result a valid resource?
123         if (is_resource($result)) {
124                 // Get the count of rows from database
125                 $lines = mysql_num_rows($result);
126
127                 // Is the result empty? Then we have an error!
128                 if (empty($lines)) $lines = 0;
129         } else {
130                 // No resource given, no lines found!
131                 $lines = 0;
132         }
133         return $lines;
134 }
135
136 // SQL affected rows
137 function SQL_AFFECTEDROWS() {
138         // Valid link resource?
139         if (!SQL_IS_LINK_UP()) return false;
140
141         // Get affected rows
142         $lines = mysql_affected_rows(SQL_GET_LINK());
143
144         // Return it
145         return $lines;
146 }
147
148 // SQL fetch row
149 function SQL_FETCHROW ($result) {
150         // Is a result resource set?
151         if (!is_resource($result)) return false;
152
153         // Fetch the data and return it
154         return mysql_fetch_row($result);
155 }
156
157 // SQL fetch array
158 function SQL_FETCHARRAY($res, $nr=0, $remove_numerical=true) {
159         // Is a result resource set?
160         if (!is_resource($res)) return false;
161
162         // Initialize array
163         $row = array();
164
165         // Load row from database
166         $row = mysql_fetch_array($res);
167
168         // Return only arrays here
169         if (is_array($row)) {
170                 // Shall we remove numerical data here automatically?
171                 if ($remove_numerical) {
172                         // So let's remove all numerical elements to save memory!
173                         $max = count($row);
174                         for ($idx = 0; $idx < ($max / 2); $idx++) {
175                                 // Remove entry
176                                 unset($row[$idx]);
177                         } // END - for
178                 } // END - if
179
180                 // Return row
181                 return $row;
182         } else {
183                 // Return a false here...
184                 return false;
185         }
186 }
187
188 // SQL result
189 function SQL_RESULT ($res, $row, $field = 0) {
190         // Is $res valid?
191         if (!is_resource($res)) return false;
192
193         // Run the result command and return the result
194         $result = mysql_result($res, $row, $field);
195         return $result;
196 }
197
198 // SQL connect
199 function SQL_CONNECT ($host, $login, $password, $F, $L) {
200         // Try to connect
201         $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
202
203         // Set the link resource
204         SQL_SET_LINK($connect);
205 }
206
207 // SQL select database
208 function SQL_SELECT_DB ($dbName, $F, $L) {
209         // Is there still a valid link? If not, skip it.
210         if (!SQL_IS_LINK_UP()) return false;
211
212         // Return the result
213         return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
214 }
215
216 // SQL close link
217 function SQL_CLOSE ($F, $L) {
218         if (!SQL_IS_LINK_UP()) {
219                 // Skip double close
220                 return false;
221         } // END - if
222
223         // Do we need to update cache/db counter?
224         //* DEBUG: */ echo "DB=".getConfig('db_hits').",CACHE=".getConfig('cache_hits')."<br />\n";
225         if ((GET_EXT_VERSION('cache') >= '0.0.7') && (getConfig('db_hits') > 0) && (getConfig('cache_hits') > 0) && (isCacheInstanceValid())) {
226                 // Add new hits
227                 incrementConfigEntry('db_hits', getConfig('db_hits_run'));
228
229                 // Update counter for db/cache
230                 updateConfiguration(array('db_hits', 'cache_hits'), array(getConfig('db_hits'), getConfig('cache_hits')));
231         } // END - if
232
233         // Close database link and forget the link
234         $close = mysql_close(SQL_GET_LINK())
235                 or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):'.mysql_error());
236
237         // Close link
238         SQL_SET_LINK(null);
239
240         // Return the result
241         return $close;
242 }
243
244 // SQL free result
245 function SQL_FREERESULT ($result) {
246         if (!is_resource($result)) {
247                 // Abort here
248                 return false;
249         } // END - if
250
251         $res = mysql_free_result($result);
252         return $res;
253 }
254
255 // SQL string escaping
256 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure=true) {
257         // Link is there?
258         if (!SQL_IS_LINK_UP()) return false;
259
260         // Init variable
261         $query = 'failed';
262
263         if ($strip === true) {
264                 $strip = 'true';
265         } else {
266                 $strip = 'false';
267         }
268
269         if ($secure === true) {
270                 $secure = 'true';
271         } else {
272                 $secure = 'false';
273         }
274
275         $eval = "\$query = sprintf(\"".$qstring."\"";
276         foreach ($data as $var) {
277                 if ((!empty($var)) || ($var === 0)) {
278                         $eval .= ", SQL_ESCAPE(\"".$var."\", ".$secure.", ".$strip.")";
279                 } else {
280                         $eval .= ", ''";
281                 }
282         } // END - foreach
283         $eval .= ");";
284
285         // Debugging
286         //
287         //* DEBUG: */ $fp = fopen(constant('PATH')."inc/cache/escape_debug.log", 'a') or app_die(__FILE__, __LINE__, "Cannot write debug.log!");
288         //* DEBUG: */ fwrite($fp, $F.'('.$L."): ".str_replace("\r", '', str_replace("\n", " ", $eval))."\n");
289         //* DEBUG: */ fclose($fp);
290
291         // Run the code
292         eval($eval);
293
294         // Was the eval() command fine?
295         if ($query == 'failed') {
296                 // Something went wrong?
297                 debug_report_bug('eval=' . $eval);
298         } // END - if
299
300         if ($run === true) {
301                 // Run SQL query (default)
302                 return SQL_QUERY($query, $F, $L);
303         } else {
304                 // Return secured string
305                 return $query;
306         }
307 }
308
309 // Get ID from last INSERT command
310 function SQL_INSERTID () {
311         if (!SQL_IS_LINK_UP()) return false;
312         return mysql_insert_id();
313 }
314
315 // Escape a string for the database
316 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
317         // Secure string first? (which is the default behaviour!)
318         if ($secureString) {
319                 // Then do it here
320                 $str = secureString($str, $strip);
321         } // END - if
322
323         if (!SQL_IS_LINK_UP()) {
324                 // Fall-back to smartAddSlashes() when there is no link
325                 return smartAddSlashes($str);
326         } elseif (function_exists('mysql_real_escape_string')) {
327                 // The new and improved version
328                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):str={$str}<br />\n";
329                 return mysql_real_escape_string($str, SQL_GET_LINK());
330         } elseif (function_exists('mysql_escape_string')) {
331                 // The obsolete function
332                 return mysql_escape_string($str, SQL_GET_LINK());
333         } else {
334                 // If nothing else works, fall back to smartAddSlashes()
335                 return smartAddSlashes($str);
336         }
337 }
338
339 // SELECT query string from table, columns and so on... ;-)
340 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
341         // Is columns an array?
342         if (!is_array($columns)) {
343                 // No array
344                 trigger_error(sprintf("columns is not array. %s!=array", gettype($columns)));
345         } // END  - if
346
347         // Prepare the SQL statement
348         $sql = "SELECT `".implode("`,`", $columns)."` FROM `{!_MYSQL_PREFIX!}_%s` WHERE `%s`='%s' LIMIT 1";
349
350         // Return the result
351         return SQL_QUERY_ESC($sql,
352                 array(
353                         $table,
354                         $idRow,
355                         bigintval($id),
356                 ), $F, $L
357         );
358 }
359
360 // ALTER TABLE wrapper function
361 function SQL_ALTER_TABLE ($sql, $F, $L) {
362         // This is the default result...
363         $result = false;
364
365         // Determine index/fulltext/unique word
366         $noIndex = (
367         (
368                 strpos($sql, 'INDEX') === false
369         ) && (
370                 strpos($sql, 'FULLTEXT') === false
371         ) && (
372                 strpos($sql, 'UNIQUE') === false
373         )
374         );
375
376         // Extract table name
377         $tableArray = explode(" ", $sql);
378         $tableName = str_replace('`', '', $tableArray[2]);
379
380         // Shall we add/drop?
381         if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
382                 // And column name as well
383                 $columnName = str_replace('`', '', $tableArray[4]);
384
385                 // Get column information
386                 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
387                         array($tableName, $columnName), __FILE__, __LINE__);
388
389                 // Do we have no entry on ADD or an entry on DROP?
390                 // 123           4       4     3    3      4           4          32    23           4       4     3    3      4            4          321
391                 if (((SQL_NUMROWS($result) == 0) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
392                         // Do the query
393                         //* DEBUG: */ print __LINE__.':'.$sql."<br />\n";
394                         $result = SQL_QUERY($sql, $F, $L, false);
395                 } // END - if
396         } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
397                 // Skip this query silently
398                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
399         } elseif (!$noIndex) {
400                 // And column name as well
401                 $columnName = str_replace('`', '', $tableArray[4]);
402
403                 // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
404                 if (in_array(strtoupper($columnName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
405                         // Init loop
406                         $begin = 1; $columnName = ',';
407                         while (strpos($columnName, ',') !== false) {
408                                 // Use last
409                                 $columnName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
410                                 //* DEBUG: */ print __LINE__.':'.$columnName."----------------".$begin."<br />\n";
411
412                                 // Remove brackes
413                                 $columnName = str_replace('(', '', str_replace(')', '', $columnName));
414                                 //* DEBUG: */ print __LINE__.':'.$columnName."----------------".$begin."<br />\n";
415
416                                 // Continue
417                                 $begin++;
418                         } // END while
419                 } // END - if
420
421                 // Show indexes
422                 $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`",
423                         array($tableName), __FILE__, __LINE__);
424
425                 // Walk through all
426                 $skip = false;
427                 while ($content = SQL_FETCHARRAY($result)) {
428                         // Is it found?
429                         //* DEBUG: */ print "<pre>".print_r($content, true)."</pre>";
430                         if (($content['Column_name'] == $columnName) || ($content['Key_name'] == $columnName)) {
431                                 // Skip this query!
432                                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Skiped: %s", $sql));
433                                 $skip = true;
434                                 break;
435                         } // END - if
436                 } // END - while
437
438                 // Free result
439                 SQL_FREERESULT($result);
440
441                 // Shall we run it?
442                 if (!$skip) {
443                         // Send it to the SQL_QUERY() function
444                         //* DEBUG: */ print __LINE__.':'.$sql."<br />\n";
445                         $result = SQL_QUERY($sql, $F, $L, false);
446                 } // END - if
447         } else {
448                 // Other ALTER TABLE query
449                 //* DEBUG: */ print __LINE__.':'.$sql."<br />\n";
450                 $result = SQL_QUERY($sql, $F, $L, false);
451         }
452
453         // Return result
454         return $result;
455 }
456
457 // Getter for SQL link
458 function SQL_GET_LINK () {
459         // Init link
460         $link = null;
461
462         // Is it in the globals?
463         if (isset($GLOBALS['sql_link'])) {
464                 // Then take it
465                 $link = $GLOBALS['sql_link'];
466         } // END - if
467
468         // Return it
469         return $link;
470 }
471
472 // Setter for link
473 function SQL_SET_LINK ($link) {
474         // Is this a resource or null?
475         if ((!is_resource($link)) && (!is_null($link))) {
476                 // This should never happen!
477                 trigger_error(sprintf("link is not resource or null. Type: %s", gettype($link)));
478         } // END - if
479
480         // Set it
481         $GLOBALS['sql_link'] = $link;
482 }
483
484 // Checks if the link is up
485 function SQL_IS_LINK_UP () {
486         // Get the link
487         $link = SQL_GET_LINK();
488
489         // Return the result
490         return (is_resource($link));
491 }
492
493 //
494 ?>