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