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