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