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