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