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