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