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