b64e3937ec828ef647e2bec44dc6b9be87949201
[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.php                                          *
8  * -------------------------------------------------------------------- *
9  * Short description :                                                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  :                                                  *
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 (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
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         // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
45         $sql_string = str_replace("\t", " ", str_replace("\n", " ", str_replace("\r", " ", $sql_string)));
46
47         // Starting time
48         $querytimeBefore = array_sum(explode(' ', microtime()));
49
50         // Run SQL command
51         $result = @mysql_query($sql_string, $link)
52          or ADD_FATAL($F." (".$L."):".mysql_error()."<br />
53 ".MYSQL_QUERY_STRING."<br />
54 ".$sql_string);
55
56         // Starting time
57         $querytimeAfter = array_sum(explode(' ', microtime()));
58
59         // Calculate query time
60         $queryTime = $querytimeAfter - $querytimeBefore;
61
62         // Count this query
63         if (!isset($_CONFIG['sql_count'])) $_CONFIG['sql_count'] = 0;
64         $_CONFIG['sql_count']++;
65
66         // Debug output
67         //* DEBUG: */ print "Query=<pre>".$sql_string."</pre>, affected=<b>".SQL_AFFECTEDROWS()."</b>, numrows=<b>".SQL_NUMROWS($result)."</b><br />\n";
68
69         if (($CSS != "1") && ($CSS != "-1") && (isBooleanConstantAndTrue('DEBUG_MODE')) && (DEBUG_SQL)) {
70                 //
71                 // Debugging stuff...
72                 //
73                 $fp = @fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write debug.log!");
74                 if (!isset($OK)) {
75                         // Write first entry
76                         fwrite($fp, "Module=".$GLOBALS['module']."\n");
77                         $OK = true;
78                 }
79                 fwrite($fp, $F."(LINE=".$L."|NUM=".SQL_NUMROWS($result)."|AFFECTED=".SQL_AFFECTEDROWS()."|QUERYTIME:".$queryTime."): ".str_replace('\r', "", str_replace('\n', " ", $sql_string))."\n");
80                 fclose($fp);
81         }
82
83         // Count DB hits
84         if (!isset($_CONFIG['db_hits'])) {
85                 // Count in dummy variable
86                 $_CONFIG['db_hits'] = 0;
87         } else {
88                 // Count to config array
89                 $_CONFIG['db_hits']++;
90         }
91         return $result;
92 }
93
94 // SQL num rows
95 function SQL_NUMROWS($result) {
96         // Is the result a valid resource?
97         if (is_resource($result)) {
98                 // Get the count of rows from database
99                 $lines = @mysql_num_rows($result);
100
101                 // Is the result empty? Then we have an error!
102                 if (empty($lines)) $lines = "0";
103         } else {
104                 // No resource given, no lines found!
105                 $lines = "0";
106         }
107         return $lines;
108 }
109
110 // SQL affected rows
111 function SQL_AFFECTEDROWS($lnk="x", $F="dummy", $L="dummy") {
112         global $link;
113         // $lnk will be ignored for now!
114         $lines = @mysql_affected_rows($link);
115         return $lines;
116 }
117
118 // SQL fetch row
119 function SQL_FETCHROW($result) {
120         $DATA = array();
121         $DATA = @mysql_fetch_row($result);
122         return $DATA;
123 }
124
125 // SQL fetch array
126 function SQL_FETCHARRAY($res=false, $nr=0, $remove_numerical=true) {
127         // Is a result resource set?
128         if (!$res) return false;
129
130         // Initialize array
131         $row = array();
132
133         // Load row from database
134         $row = @mysql_fetch_array($res);
135
136         // Return only arrays here
137         if (is_array($row)) {
138                 // Shall we remove numerical data here automatically?
139                 if ($remove_numerical) {
140                                  // So let's remove all numerical elements to save memory!
141                         $max = count($row);
142                         for ($idx = 0; $idx < ($max / 2); $idx++) {
143                                 // Remove entry
144                                 unset($row[$idx]);
145                         }
146                 }
147
148                 // Return row
149                 return $row;
150         } else {
151                 // Return a false here...
152                 return false;
153         }
154 }
155
156 // SQL result
157 function SQL_RESULT($res, $row, $field) {
158         $result = @mysql_result($res, $row, $field);
159         return $result;
160 }
161 // SQL connect
162 function SQL_CONNECT($host, $login, $password, $F, $L) {
163         $connect = @mysql_connect($host, $login, $password) or ADD_FATAL($F." (".$L."):".mysql_error());
164         return $connect;
165 }
166 // SQL select database
167 function SQL_SELECT_DB($dbName, $link, $F, $L) {
168         $select = false;
169         if (is_resource($link)) {
170                 $select = @mysql_select_db($dbName, $link) or ADD_FATAL($F." (".$L."):".mysql_error());
171         }
172         return $select;
173 }
174 // SQL close link
175 function SQL_CLOSE($link, $F, $L) {
176         global $_CONFIG, $cacheInstance, $cacheArray;
177         if ((GET_EXT_VERSION("cache") >= "0.0.7") && (isset($_CONFIG['db_hits'])) && (isset($_CONFIG['cache_hits'])) && (is_object($cacheInstance))) {
178                 // Update counter for db/cache
179                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_config SET db_hits=%d, cache_hits=%d WHERE config=0 LIMIT 1",
180                         array(bigintval($_CONFIG['db_hits']), bigintval($_CONFIG['cache_hits'])), __FILE__, __LINE__);
181
182                 // Update cache here
183                 if (GET_EXT_VERSION("cache") >= "0.1.2") {
184                         if ($cacheInstance->cache_file("config", true)) {
185                                 // Replace data
186                                 $cacheInstance->cache_replace("cache_hits", $_CONFIG['cache_hits'], "0", $cacheArray);
187                                 $cacheInstance->cache_replace("db_hits"   , $_CONFIG['db_hits']   , "0", $cacheArray);
188                         }
189                 }
190         }
191
192         // Close database link
193         $close = @mysql_close($link) or ADD_FATAL($F." (".$L."):".mysql_error());
194         return $close;
195 }
196 // SQL free result
197 function SQL_FREERESULT($result) {
198         $res = @mysql_free_result($result);
199         return $res;
200 }
201 // SQL string escaping
202 function SQL_QUERY_ESC($qstring, $data, $file, $line, $run=true, $strip=true) {
203         global $link;
204         $eval = "\$query = sprintf(\"".$qstring."\"";
205         foreach ($data as $var) {
206                 if (!empty($var)) {
207                         if ($strip) {
208                                 $eval .= ", SQL_ESCAPE(\"".strip_tags($var)."\")";
209                         } else {
210                                 $eval .= ", SQL_ESCAPE(\"".$var."\")";
211                         }
212                 } else {
213                         $eval .= ", ''";
214                 }
215         }
216         $eval .= ");";
217         //
218         // Debugging
219         //
220         //$fp = fopen(PATH."escape_debug.log", 'a') or mxchange_die("Cannot write debug.log!");
221         //fwrite($fp, $file."(".$line."): ".str_replace('\r', "", str_replace('\n', " ", $eval))."\n");
222         //fclose($fp);
223         eval($eval);
224         if ($run) {
225                 // Run SQL query (default)
226                 return SQL_QUERY($query, $file, $line);
227         } else {
228                 // Return secured string
229                 return $query;
230         }
231 }
232 // Get ID from last INSERT command
233 function SQL_INSERTID() {
234         return @mysql_insert_id();
235 }
236 // Escape a string for the database
237 function SQL_ESCAPE($str) {
238         global $link;
239         if (!is_resource($link)) {
240                 // Fall-back to addslashes() when there is no link
241                 return addslashes($str);
242         }
243
244         if (function_exists('mysql_real_escape_string')) {
245                 // The new and improved version
246                 return mysql_real_escape_string($str, $link);
247         } elseif (function_exists('mysql_escape_string')) {
248                 // The obsulete function
249                 return mysql_escape_string($str, $link);
250         } else {
251                 // If nothing else works
252                 return addslashes($str);
253         }
254 }
255 // SELECT query string from table, columns and so on... ;-)
256 function SQL_RESULT_FROM_ARRAY ($table, $columns, $idRow, $id) {
257         // Prepare the SQL statement
258         $SQL = "SELECT ".implode(", ", $columns)." FROM "._MYSQL_PREFIX."_".$table." WHERE ".$idRow."=%d LIMIT 1";
259
260         // Return the result
261         return SQL_QUERY_ESC($SQL, array(bigintval($id)), __FILE__, __LINE__);
262 }
263 //
264 ?>