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