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