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