Fix for broken SQL queries (all). Resolves #84
[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  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
37         require($INC);
38 }
39
40 // SQL queries
41 function SQL_QUERY ($sql_string, $F, $L) {
42         global $link, $CSS, $_CONFIG, $OK;
43
44         // Link is up?
45         if (!is_resource($link)) return false;
46
47         // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
48         $sql_string = str_replace("\t", " ", str_replace("\n", " ", str_replace("\r", " ", $sql_string)));
49
50         // Starting time
51         $querytimeBefore = array_sum(explode(' ', microtime()));
52
53         // Replace {!_MYSQL_PREFIX!} with constant, closes #84. Thanks to profi-concept
54         $sql_string = str_replace("{!_MYSQL_PREFIX!}", constant('_MYSQL_PREFIX'), $sql_string);
55
56         // Run SQL command
57         //* DEBUG: */ echo $sql_string."<br />\n";
58         $result = mysql_query($sql_string, $link)
59          or addFatalMessage($F." (".$L."):".mysql_error()."<br />
60 Query string:<br />
61 ".$sql_string);
62
63         // Ending time
64         $querytimeAfter = array_sum(explode(' ', microtime()));
65
66         // Calculate query time
67         $queryTime = $querytimeAfter - $querytimeBefore;
68
69         // Save last successfull query
70         $_CONFIG['db_last_query'] = $sql_string;
71
72         // Count this query
73         incrementConfigEntry('sql_count');
74
75         // Debug output
76         //* DEBUG: */ print "Query=<pre>".$sql_string."</pre>, affected=<strong>".SQL_AFFECTEDROWS()."</strong>, numrows=<strong>".SQL_NUMROWS($result)."</strong><br />\n";
77
78         if (($CSS != "1") && ($CSS != "-1") && (isBooleanConstantAndTrue('DEBUG_MODE')) && (isBooleanConstantAndTrue('DEBUG_SQL'))) {
79                 //
80                 // Debugging stuff...
81                 //
82                 $fp = @fopen(PATH."inc/cache/mysql.log", 'a') or mxchange_die("Cannot write mysql.log!");
83                 if (!isset($OK)) {
84                         // Write first entry
85                         fwrite($fp, "Module=".$GLOBALS['module']."\n");
86                         $OK = true;
87                 } // END - if
88                 fwrite($fp, $F."(LINE=".$L."|NUM=".SQL_NUMROWS($result)."|AFFECTED=".SQL_AFFECTEDROWS()."|QUERYTIME:".$queryTime."): ".str_replace('\r', "", str_replace('\n', " ", $sql_string))."\n");
89                 fclose($fp);
90         } // END - if
91
92         // Count DB hits
93         if (getConfig('db_hits_run') == null) {
94                 // Count in dummy variable
95                 $_CONFIG['db_hits_run'] = 1;
96         } else {
97                 // Count to config array
98                 $_CONFIG['db_hits_run']++;
99         }
100
101         // Return the result
102         return $result;
103 }
104
105 // SQL num rows
106 function SQL_NUMROWS($result) {
107         // Is the result a valid resource?
108         if (is_resource($result)) {
109                 // Get the count of rows from database
110                 $lines = mysql_num_rows($result);
111
112                 // Is the result empty? Then we have an error!
113                 if (empty($lines)) $lines = 0;
114         } else {
115                 // No resource given, no lines found!
116                 $lines = 0;
117         }
118         return $lines;
119 }
120
121 // SQL affected rows
122 function SQL_AFFECTEDROWS() {
123         global $link;
124
125         // Valid link resource?
126         if (!is_resource($link)) return false;
127
128         // Get affected rows
129         $lines = mysql_affected_rows($link);
130
131         // Return it
132         return $lines;
133 }
134
135 // SQL fetch row
136 function SQL_FETCHROW($result) {
137         // Init data
138         $DATA = array();
139
140         // Is a result resource set?
141         if (!is_resource($result)) return false;
142
143         $DATA = mysql_fetch_row($result);
144         return $DATA;
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                         }
168                 }
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) {
180         $result = mysql_result($res, $row, $field);
181         return $result;
182 }
183 // SQL connect
184 function SQL_CONNECT($host, $login, $password, $F, $L) {
185         $connect = mysql_connect($host, $login, $password) or addFatalMessage($F." (".$L."):".mysql_error());
186         return $connect;
187 }
188 // SQL select database
189 function SQL_SELECT_DB($dbName, $link, $F, $L) {
190         $select = false;
191         if (is_resource($link)) {
192                 $select = mysql_select_db($dbName, $link) or addFatalMessage($F." (".$L."):".mysql_error());
193         }
194         return $select;
195 }
196 // SQL close link
197 function SQL_CLOSE(&$link, $F, $L) {
198         global $_CONFIG, $cacheInstance, $cacheArray;
199
200         // Is there still a valid link?
201         if (!is_resource($link)) {
202                 // Skip double close
203                 return false;
204         } // END - if
205
206         // Do we need to update cache/db counter?
207         //* DEBUG: */ echo "DB=".getConfig('db_hits').",CACHE=".getConfig('cache_hits')."<br />\n";
208         if ((GET_EXT_VERSION("cache") >= "0.0.7") && (getConfig('db_hits') > 0) && (getConfig('cache_hits') > 0) && (is_object($cacheInstance))) {
209                 // Add new hits
210                 $_CONFIG['db_hits'] += getConfig('db_hits_run');
211
212                 // Update counter for db/cache
213                 UPDATE_CONFIG(array("db_hits", "cache_hits"), array(bigintval(getConfig('db_hits')), bigintval(getConfig('cache_hits'))));
214         } // END - if
215
216         // Close database link and forget the link
217         $close = mysql_close($link) or addFatalMessage($F." (".$L."):".mysql_error());
218         $link = null;
219         return $close;
220 }
221
222 // SQL free result
223 function SQL_FREERESULT ($result) {
224         if (!is_resource($result)) {
225                 // Abort here
226                 return false;
227         } // END - if
228
229         $res = mysql_free_result($result);
230         return $res;
231 }
232
233 // SQL string escaping
234 function SQL_QUERY_ESC ($qstring, $data, $file, $line, $run=true, $strip=true) {
235         global $link;
236
237         // Link is there?
238         if (!is_resource($link)) return false;
239
240         // Init variable
241         $query = "failed";
242
243         if ($strip) {
244                 $strip = "true";
245         } else {
246                 $strip = "false";
247         }
248
249         $eval = "\$query = sprintf(\"".$qstring."\"";
250         foreach ($data as $var) {
251                 if ((!empty($var)) || ($var === 0)) {
252                         $eval .= ", SQL_ESCAPE(\"".$var."\",true,".$strip.")";
253                 } else {
254                         $eval .= ", ''";
255                 }
256         }
257         $eval .= ");";
258         //
259         // Debugging
260         //
261         //* DEBUG: */ $fp = fopen(PATH."inc/cache/escape_debug.log", 'a') or mxchange_die("Cannot write debug.log!");
262         //* DEBUG: */ fwrite($fp, $file."(".$line."): ".str_replace("\r", "", str_replace("\n", " ", $eval))."\n");
263         //* DEBUG: */ fclose($fp);
264
265         // Run the code
266         eval($eval);
267
268         // Was the eval() command fine?
269         if ($query == "failed") {
270                 // Something went wrong?
271                 print "eval=".htmlentities($eval)."<pre>";
272                 debug_print_backtrace();
273                 die("</pre>");
274         } // END - if
275
276         if ($run) {
277                 // Run SQL query (default)
278                 return SQL_QUERY($query, $file, $line);
279         } else {
280                 // Return secured string
281                 return $query;
282         }
283 }
284
285 // Get ID from last INSERT command
286 function SQL_INSERTID () {
287         global $link;
288         if (!is_resource($link)) return false;
289         return mysql_insert_id();
290 }
291
292 // Escape a string for the database
293 function SQL_ESCAPE ($str, $secureString=true,$strip=true) {
294         global $link;
295
296         // Secure string first? (which is the default behaviour!)
297         if ($secureString) {
298                 // Then do it here
299                 $str = secureString($str, $strip);
300         } // END - if
301
302         if (!is_resource($link)) {
303                 // Fall-back to addslashes() when there is no link
304                 return addslashes($str);
305         } // END - if
306
307         if (function_exists('mysql_real_escape_string')) {
308                 // The new and improved version
309                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):str={$str}<br />\n";
310                 return mysql_real_escape_string($str, $link);
311         } elseif (function_exists('mysql_escape_string')) {
312                 // The obsolete function
313                 return mysql_escape_string($str, $link);
314         } else {
315                 // If nothing else works
316                 return addslashes($str);
317         }
318 }
319
320 // SELECT query string from table, columns and so on... ;-)
321 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
322         // Is columns an array?
323         if (!is_array($columns) {
324                 // No array
325                 trigger_error(sprintf("columns is not array. %s!=array", gettype($columns)));
326         }
327
328         // Prepare the SQL statement
329         $SQL = "SELECT `".implode("`, `", $columns)."` FROM `{!_MYSQL_PREFIX!}_%s` WHERE ``='%s' LIMIT 1";
330
331         // Return the result
332         return SQL_QUERY_ESC($SQL,
333                 array(
334                         bigintval($id),
335                         $table,
336                         $idRow
337                 ), $F, $L);
338 }
339
340 // ALTER TABLE wrapper function
341 function SQL_ALTER_TABLE ($sql, $F, $L) {
342         // This is the default result...
343         $result = false;
344
345         // Determine index/fulltext/unique word
346         $noIndex = ((eregi("INDEX", $sql) == false) && (eregi("FULLTEXT", $sql) == false) && (eregi("UNIQUE", $sql) == false);
347
348         // Shall we add/drop?
349         if (((eregi("ADD", $sql) > 0) || (eregi("DROP", $sql) > 0)) && ($noIndex)) {
350                 // Extract table name
351                 $tableArray = explode(" ", $sql);
352                 $tableName = str_replace("`", "", $tableArray[2]);
353
354                 // And column name as well
355                 $columnName = str_replace("`", "", $tableArray[4]);
356
357                 // Get column information
358                 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM %s LIKE '%s'",
359                         array($tableName, $columnName), $F, $L);
360
361                 // Do we have no entry on ADD or an entry on DROP?
362                 if (((SQL_NUMROWS($result) == 0) && (eregi("ADD", $sql) > 0)) || ((SQL_NUMROWS($result) == 1) && (eregi("DROP", $sql) > 0))) {
363                         // Do the query
364                         $result = SQL_QUERY($sql, $F, $L, false);
365                 } // END - if
366         } else {
367                 // Send it to the SQL_QUERY() function
368                 $result = SQL_QUERY($sql, $F, $L, false);
369         }
370
371         // Return result
372         return $result;
373 }
374 //
375 ?>