88a135789b280c4e573327eebd2eb26aa71c5428
[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(__FUNCTION__, __LINE__, $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         if (($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1") && (isDebugModeEnabled()) && (isBooleanConstantAndTrue('DEBUG_SQL'))) {
76                 //
77                 // Debugging stuff...
78                 //
79                 $fp = fopen(constant('PATH')."inc/cache/mysql.log", 'a') or mxchange_die("Cannot write mysql.log!");
80                 if (!isset($GLOBALS['sql_first_entry'])) {
81                         // Write first entry
82                         fwrite($fp, "Module=".$GLOBALS['module']."\n");
83                         $GLOBALS['sql_first_entry'] = 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 (!isConfigEntrySet('db_hits_run')) {
91                 // Count in dummy variable
92                 setConfigEntry('db_hits_run', 1);
93         } else {
94                 // Count to config array
95                 incrementConfigEntry('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         // Valid link resource?
121         if (!SQL_IS_LINK_UP()) return false;
122
123         // Get affected rows
124         $lines = mysql_affected_rows(SQL_GET_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                         } // END - for
163                 } // END - if
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
179 // SQL connect
180 function SQL_CONNECT ($host, $login, $password, $F, $L) {
181         // Try to connect
182         $connect = mysql_connect($host, $login, $password) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
183
184         // Set the link resource
185         SQL_SET_LINK($connect);
186 }
187
188 // SQL select database
189 function SQL_SELECT_DB ($dbName, $F, $L) {
190         // Is there still a valid link? If not, skip it.
191         if (!SQL_IS_LINK_UP()) return false;
192
193         // Return the result
194         return mysql_select_db($dbName, SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
195 }
196
197 // SQL close link
198 function SQL_CLOSE ($F, $L) {
199         if (!SQL_IS_LINK_UP()) {
200                 // Skip double close
201                 return false;
202         } // END - if
203
204         // Do we need to update cache/db counter?
205         //* DEBUG: */ echo "DB=".getConfig('db_hits').",CACHE=".getConfig('cache_hits')."<br />\n";
206         if ((GET_EXT_VERSION("cache") >= "0.0.7") && (getConfig('db_hits') > 0) && (getConfig('cache_hits') > 0) && (is_object($GLOBALS['cache_instance']))) {
207                 // Add new hits
208                 incrementConfigEntry('db_hits', getConfig('db_hits_run'));
209
210                 // Update counter for db/cache
211                 UPDATE_CONFIG(array("db_hits", "cache_hits"), array(bigintval(getConfig('db_hits')), bigintval(getConfig('cache_hits'))));
212         } // END - if
213
214         // Close database link and forget the link
215         $close = mysql_close(SQL_GET_LINK()) or addFatalMessage(__FUNCTION__, __LINE__, $F." (".$L."):".mysql_error());
216
217         // Close link
218         SQL_SET_LINK(null);
219
220         // Return the result
221         return $close;
222 }
223
224 // SQL free result
225 function SQL_FREERESULT ($result) {
226         if (!is_resource($result)) {
227                 // Abort here
228                 return false;
229         } // END - if
230
231         $res = mysql_free_result($result);
232         return $res;
233 }
234
235 // SQL string escaping
236 function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true) {
237         // Link is there?
238         if (!SQL_IS_LINK_UP()) return false;
239
240         // Init variable
241         $query = "failed";
242
243         if ($strip) {
244                 $strip = "true";
245         } else {
246                 $strip = "false";
247         }
248
249         $eval = "\$query = sprintf(\"".$qstring."\"";
250         foreach ($data as $var) {
251                 if ((!empty($var)) || ($var === 0)) {
252                         $eval .= ", SQL_ESCAPE(\"".$var."\",true,".$strip.")";
253                 } else {
254                         $eval .= ", ''";
255                 }
256         } // END - foreach
257         $eval .= ");";
258         //
259         // Debugging
260         //
261         //* DEBUG: */ $fp = fopen(constant('PATH')."inc/cache/escape_debug.log", 'a') or mxchange_die("Cannot write debug.log!");
262         //* DEBUG: */ fwrite($fp, $F."(".$L."): ".str_replace("\r", "", str_replace("\n", " ", $eval))."\n");
263         //* DEBUG: */ fclose($fp);
264
265         // Run the code
266         eval($eval);
267
268         // Was the eval() command fine?
269         if ($query == "failed") {
270                 // Something went wrong?
271                 debug_report_bug("eval={$eval}");
272         } // END - if
273
274         if ($run === true) {
275                 // Run SQL query (default)
276                 return SQL_QUERY($query, $F, $L);
277         } else {
278                 // Return secured string
279                 return $query;
280         }
281 }
282
283 // Get ID from last INSERT command
284 function SQL_INSERTID () {
285         if (!SQL_IS_LINK_UP()) 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         // Secure string first? (which is the default behaviour!)
292         if ($secureString) {
293                 // Then do it here
294                 $str = secureString($str, $strip);
295         } // END - if
296
297         if (!SQL_IS_LINK_UP()) {
298                 // Fall-back to smartAddSlashes() when there is no link
299                 return smartAddSlashes($str);
300         } elseif (function_exists('mysql_real_escape_string')) {
301                 // The new and improved version
302                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):str={$str}<br />\n";
303                 return mysql_real_escape_string($str, SQL_GET_LINK());
304         } elseif (function_exists('mysql_escape_string')) {
305                 // The obsolete function
306                 return mysql_escape_string($str, SQL_GET_LINK());
307         } else {
308                 // If nothing else works, fall back to smartAddSlashes()
309                 return smartAddSlashes($str);
310         }
311 }
312
313 // SELECT query string from table, columns and so on... ;-)
314 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id, $F, $L) {
315         // Is columns an array?
316         if (!is_array($columns)) {
317                 // No array
318                 trigger_error(sprintf("columns is not array. %s!=array", gettype($columns)));
319         } // END  - if
320
321         // Prepare the SQL statement
322         $sql = "SELECT `".implode("`, `", $columns)."` FROM `{!_MYSQL_PREFIX!}_%s` WHERE ``='%s' LIMIT 1";
323
324         // Return the result
325         return SQL_QUERY_ESC($sql,
326                 array(
327                         bigintval($id),
328                         $table,
329                         $idRow
330                 ), $F, $L);
331 }
332
333 // ALTER TABLE wrapper function
334 function SQL_ALTER_TABLE ($sql, $F, $L) {
335         // This is the default result...
336         $result = false;
337
338         // Determine index/fulltext/unique word
339         //         12     3             3         2    2     3                3         2    2     3              3         21
340         $noIndex = ((eregi("INDEX", $sql) == false) && (eregi("FULLTEXT", $sql) == false) && (eregi("UNIQUE", $sql) == false));
341
342         // Shall we add/drop?
343         if (((eregi("ADD", $sql) > 0) || (eregi("DROP", $sql) > 0)) && ($noIndex)) {
344                 // Extract table name
345                 $tableArray = explode(" ", $sql);
346                 $tableName = str_replace("`", "", $tableArray[2]);
347
348                 // And column name as well
349                 $columnName = str_replace("`", "", $tableArray[4]);
350
351                 // Get column information
352                 $result = SQL_QUERY_ESC("SHOW COLUMNS FROM %s LIKE '%s'",
353                         array($tableName, $columnName), $F, $L);
354
355                 // Do we have no entry on ADD or an entry on DROP?
356                 // 123           4       4     3    3     4           4    32    23           4       4     3    3     4            4    321
357                 if (((SQL_NUMROWS($result) == 0) && (eregi("ADD", $sql) > 0)) || ((SQL_NUMROWS($result) == 1) && (eregi("DROP", $sql) > 0))) {
358                         // Do the query
359                         $result = SQL_QUERY($sql, $F, $L, false);
360                 } // END - if
361         } else {
362                 // Send it to the SQL_QUERY() function
363                 $result = SQL_QUERY($sql, $F, $L, false);
364         }
365
366         // Return result
367         return $result;
368 }
369
370 // Getter for SQL link
371 function SQL_GET_LINK () {
372         // Init link
373         $link = null;
374
375         // Is it in the globals?
376         if (isset($GLOBALS['sql_link'])) {
377                 // Then take it
378                 $link = $GLOBALS['sql_link'];
379         } // END - if
380
381         // Return it
382         return $link;
383 }
384
385 // Setter for link
386 function SQL_SET_LINK ($link) {
387         // Is this a resource or null?
388         if ((!is_resource($link)) && (!is_null($link))) {
389                 // This should never happen!
390                 trigger_error(sprintf("link is not resource or null. Type: %s", gettype($link)));
391         } // END - if
392
393         // Set it
394         $GLOBALS['sql_link'] = $link;
395 }
396
397 // Checks if the link is up
398 function SQL_IS_LINK_UP () {
399         // Get the link
400         $link = SQL_GET_LINK();
401
402         // Return the result
403         return (is_resource($link));
404 }
405
406 //
407 ?>