More fixes for surfbar, SQL_QUERY_ESC() now escapes zeros
[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.php                                          *
8  * -------------------------------------------------------------------- *
9  * Short description :                                                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  :                                                  *
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 (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
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         // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
45         $sql_string = str_replace("\t", " ", str_replace("\n", " ", str_replace("\r", " ", $sql_string)));
46
47         // Starting time
48         $querytimeBefore = array_sum(explode(' ', microtime()));
49
50         // Run SQL command
51         $result = @mysql_query($sql_string, $link)
52          or ADD_FATAL($F." (".$L."):".mysql_error()."<br />
53 ".MYSQL_QUERY_STRING."<br />
54 ".$sql_string);
55
56         // Starting time
57         $querytimeAfter = array_sum(explode(' ', microtime()));
58
59         // Calculate query time
60         $queryTime = $querytimeAfter - $querytimeBefore;
61
62         // Count this query
63         if (!isset($_CONFIG['sql_count'])) $_CONFIG['sql_count'] = 0;
64         $_CONFIG['sql_count']++;
65
66         // Debug output
67         //* DEBUG: */ print "Query=<pre>".$sql_string."</pre>, affected=<b>".SQL_AFFECTEDROWS()."</b>, numrows=<b>".SQL_NUMROWS($result)."</b><br />\n";
68
69         if (($CSS != "1") && ($CSS != "-1") && (isBooleanConstantAndTrue('DEBUG_MODE')) && (isBooleanConstantAndTrue('DEBUG_SQL'))) {
70                 //
71                 // Debugging stuff...
72                 //
73                 $fp = @fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write debug.log!");
74                 if (!isset($OK)) {
75                         // Write first entry
76                         fwrite($fp, "Module=".$GLOBALS['module']."\n");
77                         $OK = true;
78                 }
79                 fwrite($fp, $F."(LINE=".$L."|NUM=".SQL_NUMROWS($result)."|AFFECTED=".SQL_AFFECTEDROWS()."|QUERYTIME:".$queryTime."): ".str_replace('\r', "", str_replace('\n', " ", $sql_string))."\n");
80                 fclose($fp);
81         }
82
83         // Count DB hits
84         if (!isset($_CONFIG['db_hits'])) {
85                 // Count in dummy variable
86                 $_CONFIG['db_hits'] = 0;
87         } else {
88                 // Count to config array
89                 $_CONFIG['db_hits']++;
90         }
91         return $result;
92 }
93
94 // SQL num rows
95 function SQL_NUMROWS($result) {
96         // Is the result a valid resource?
97         if (is_resource($result)) {
98                 // Get the count of rows from database
99                 $lines = @mysql_num_rows($result);
100
101                 // Is the result empty? Then we have an error!
102                 if (empty($lines)) $lines = "0";
103         } else {
104                 // No resource given, no lines found!
105                 $lines = "0";
106         }
107         return $lines;
108 }
109
110 // SQL affected rows
111 function SQL_AFFECTEDROWS($lnk="x", $F="dummy", $L="dummy") {
112         global $link;
113         // $lnk will be ignored for now!
114         $lines = @mysql_affected_rows($link);
115         return $lines;
116 }
117
118 // SQL fetch row
119 function SQL_FETCHROW($result) {
120         $DATA = array();
121         $DATA = @mysql_fetch_row($result);
122         return $DATA;
123 }
124
125 // SQL fetch array
126 function SQL_FETCHARRAY($res=false, $nr=0, $remove_numerical=true) {
127         // Is a result resource set?
128         if (!$res) return false;
129
130         // Initialize array
131         $row = array();
132
133         // Load row from database
134         $row = @mysql_fetch_array($res);
135
136         // Return only arrays here
137         if (is_array($row)) {
138                 // Shall we remove numerical data here automatically?
139                 if ($remove_numerical) {
140                                  // So let's remove all numerical elements to save memory!
141                         $max = count($row);
142                         for ($idx = 0; $idx < ($max / 2); $idx++) {
143                                 // Remove entry
144                                 unset($row[$idx]);
145                         }
146                 }
147
148                 // Return row
149                 return $row;
150         } else {
151                 // Return a false here...
152                 return false;
153         }
154 }
155
156 // SQL result
157 function SQL_RESULT($res, $row, $field) {
158         $result = @mysql_result($res, $row, $field);
159         return $result;
160 }
161 // SQL connect
162 function SQL_CONNECT($host, $login, $password, $F, $L) {
163         $connect = @mysql_connect($host, $login, $password) or ADD_FATAL($F." (".$L."):".mysql_error());
164         return $connect;
165 }
166 // SQL select database
167 function SQL_SELECT_DB($dbName, $link, $F, $L) {
168         $select = false;
169         if (is_resource($link)) {
170                 $select = @mysql_select_db($dbName, $link) or ADD_FATAL($F." (".$L."):".mysql_error());
171         }
172         return $select;
173 }
174 // SQL close link
175 function SQL_CLOSE($link, $F, $L) {
176         global $_CONFIG, $cacheInstance, $cacheArray;
177         if ((GET_EXT_VERSION("cache") >= "0.0.7") && (isset($_CONFIG['db_hits'])) && (isset($_CONFIG['cache_hits'])) && (is_object($cacheInstance))) {
178                 // Update counter for db/cache
179                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_config SET db_hits=%s, cache_hits=%s WHERE config=0 LIMIT 1",
180                         array(bigintval($_CONFIG['db_hits']), bigintval($_CONFIG['cache_hits'])), __FILE__, __LINE__);
181
182                 // Update cache here
183                 if (GET_EXT_VERSION("cache") >= "0.1.2") {
184                         if ($cacheInstance->cache_file("config", true)) {
185                                 // Replace data
186                                 $cacheInstance->cache_replace("cache_hits", $_CONFIG['cache_hits'], "0", $cacheArray);
187                                 $cacheInstance->cache_replace("db_hits"   , $_CONFIG['db_hits']   , "0", $cacheArray);
188                         }
189                 }
190         }
191
192         // Close database link
193         $close = @mysql_close($link) or ADD_FATAL($F." (".$L."):".mysql_error());
194         return $close;
195 }
196 // SQL free result
197 function SQL_FREERESULT($result) {
198         $res = @mysql_free_result($result);
199         return $res;
200 }
201 // SQL string escaping
202 function SQL_QUERY_ESC($qstring, $data, $file, $line, $run=true, $strip=true) {
203         global $link;
204         $eval = "\$query = sprintf(\"".$qstring."\"";
205         foreach ($data as $var) {
206                 if ((!empty($var)) || ($var === 0)) {
207                         if ($strip) {
208                                 $eval .= ", SQL_ESCAPE(\"".strip_tags($var)."\")";
209                         } else {
210                                 $eval .= ", SQL_ESCAPE(\"".$var."\")";
211                         }
212                 } else {
213                         $eval .= ", ''";
214                 }
215         }
216         $eval .= ");";
217         //
218         // Debugging
219         //
220         //$fp = fopen(PATH."escape_debug.log", 'a') or mxchange_die("Cannot write debug.log!");
221         //fwrite($fp, $file."(".$line."): ".str_replace('\r', "", str_replace('\n', " ", $eval))."\n");
222         //fclose($fp);
223         eval($eval);
224         if ($run) {
225                 // Run SQL query (default)
226                 return SQL_QUERY($query, $file, $line);
227         } else {
228                 // Return secured string
229                 return $query;
230         }
231 }
232 // Get ID from last INSERT command
233 function SQL_INSERTID() {
234         return @mysql_insert_id();
235 }
236 // Escape a string for the database
237 function SQL_ESCAPE($str, $secureString = true) {
238         global $link;
239
240         // Secure string first? (which is the default behaviour!)
241         if ($secureString) {
242                 // Then do it here
243                 $str = secureString($str);
244         } // END - if
245
246         if (!is_resource($link)) {
247                 // Fall-back to addslashes() when there is no link
248                 return addslashes($str);
249         } // END - if
250
251         if (function_exists('mysql_real_escape_string')) {
252                 // The new and improved version
253                 return mysql_real_escape_string($str, $link);
254         } elseif (function_exists('mysql_escape_string')) {
255                 // The obsulete function
256                 return mysql_escape_string($str, $link);
257         } else {
258                 // If nothing else works
259                 return addslashes($str);
260         }
261 }
262 // SELECT query string from table, columns and so on... ;-)
263 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id) {
264         // Prepare the SQL statement
265         $SQL = "SELECT ".implode(", ", $columns)." FROM "._MYSQL_PREFIX."_".$table." WHERE ".$idRow."=%s LIMIT 1";
266
267         // Return the result
268         return SQL_QUERY_ESC($SQL, array(bigintval($id)), __FILE__, __LINE__);
269 }
270 // ALTER TABLE wrapper function
271 function SQL_ALTER_TABLE($sql, $F, $L) {
272         // Shall we add?
273         if (eregi("ADD", $sql) > 0) {
274                 // Extract table name
275                 $tableArray = explode(" ", $sql);
276                 $tableName = str_replace("`", "", $tableArray[2]);
277
278                 // And column name as well
279                 $columnName = str_replace("`", "", $tableArray[4]);
280
281                 // Get column information
282                 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM %s LIKE '%s'",
283                         array($tableName, $columnName), __FILE__, __LINE__);
284
285                 // Do we have no entry?
286                 if (SQL_NUMROWS($result) == 0) {
287                         // Do the query
288                         return SQL_QUERY($sql, $F, $L, false);
289                 } // END - if
290         } else {
291                 // Send it to the SQL_QUERY() function
292                 return SQL_QUERY($sql, $F, $L, false);
293         }
294 }
295 //
296 ?>