Renamed more:
[mailer.git] / inc / db / lib-mysql3.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                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/4/5 server            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Datenbankschicht fuer MySQL 3/4/5 Server         *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2013 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // SQL queries
44 function sqlQuery ($sqlString, $file, $line, $enableCodes = TRUE) {
45         // Is there cache?
46         if (!isset($GLOBALS[__FUNCTION__][$sqlString])) {
47                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called: ' . $sqlString);
48
49                 // Trim SQL string
50                 $sqlStringModified = trim($sqlString);
51
52                 // Empty query string or link is not up?
53                 if (empty($sqlStringModified)) {
54                         // Empty SQL string!
55                         reportBug(__FUNCTION__, __LINE__, sprintf("SQL string is empty, please fix this: file=%s, line=%s",
56                                 basename($file),
57                                 $line
58                         ));
59                 } elseif (!isSqlLinkUp()) {
60                         // We should not quietly ignore this
61                         reportBug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
62                                 $sqlStringModified,
63                                 basename($file),
64                                 $line
65                         ));
66                 }
67
68                 // Remove \t, \n and \r from queries they may confuse some MySQL versions
69                 $sqlStringModified = str_replace(array(chr(9), PHP_EOL, chr(13)), array(' ', ' ', ' '), $sqlStringModified);
70
71                 // Compile config entries out
72                 $sqlStringModified = sqlPrepareQueryString($sqlStringModified, $enableCodes);
73
74                 // Cache it and remember as last SQL query
75                 $GLOBALS[__FUNCTION__][$sqlString] = $sqlStringModified;
76                 $GLOBALS['last_sql']               = $sqlStringModified;
77                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Stored cache: ' . $sqlStringModified);
78         } elseif (!isSqlLinkUp()) {
79                 // Link went down while using cached SQL
80                 reportBug(__FUNCTION__, __LINE__, 'Link went down while using cached SQL: sqlString=' . $sqlString . ',file=' . basename($file) . ',line=' . $line . ',enableCodes=' . intval($enableCodes));
81         } else {
82                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
83
84                 // Use cache (to save a lot function calls
85                 $GLOBALS['last_sql'] = $GLOBALS[__FUNCTION__][$sqlString];
86
87                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache is: ' . $sqlString);
88         }
89
90         // Starting time
91         $querytimeBefore = microtime(TRUE);
92
93         // Run SQL command
94         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($file) . ',line=' . $line . ',sql=' . $GLOBALS['last_sql']);
95         $result = mysql_query($GLOBALS['last_sql'], getSqlLink())
96                 or sqlError($file, $line, 'file='. basename($file) . ',line=' . $line . ':mysql_error()=' . mysql_error() . ',last_query=' . $GLOBALS['last_sql']);
97         //* DEBUG: */ logDebugMessage($file, $line, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . sqlAffectedRows() . ',numRows='.(is_resource($result) ? sqlNumRows($result) : gettype($result)));
98
99         // Calculate query time
100         $queryTime = microtime(TRUE) - $querytimeBefore;
101
102         // Add this query to array including timing
103         addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $file, $line);
104
105         // Save last successfull query
106         setConfigEntry('db_last_query', $GLOBALS['last_sql']);
107
108         // Count all query times
109         incrementConfigEntry('sql_time', $queryTime);
110
111         // Count this query
112         incrementConfigEntry('sql_count');
113
114         // Debug output
115         if (isSqlDebugEnabled()) {
116                 // Is this the first call?
117                 if (!isset($GLOBALS['sql_first_entry'])) {
118                         // Write first entry
119                         appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
120                         $GLOBALS['sql_first_entry'] = TRUE;
121                 } // END - if
122
123                 // Append debug line
124                 appendLineToFile(getCachePath() . 'mysql.log', basename($file) . '|LINE=' . $line . '|NUM=' . (is_resource($result) ? sqlNumRows($result) : 'false') . '|AFFECTED=' . sqlAffectedRows() . '|QUERYTIME:' . ($queryTime * 1000) . 'ms): ' . str_replace(array(chr(13), PHP_EOL), array('', ' '), $GLOBALS['last_sql']));
125         } // END - if
126
127         // Increment stats entry
128         incrementStatsEntry('db_hits');
129
130         // Return the result
131         return $result;
132 }
133
134 // SQL num rows
135 function sqlNumRows ($resource) {
136         // Valid link resource?
137         if (!isSqlLinkUp()) return FALSE;
138
139         // Link is not up, no rows by default
140         $lines = FALSE;
141
142         // Is the result a valid resource?
143         if (isset($GLOBALS['sql_numrows'][intval($resource)])) {
144                 // Use cache
145                 $lines = $GLOBALS['sql_numrows'][intval($resource)];
146         } elseif (is_resource($resource)) {
147                 // Get the count of rows from database
148                 $lines = mysql_num_rows($resource);
149
150                 // Remember it in cache
151                 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
152         } else {
153                 // No resource given, please fix this
154                 reportBug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' .  $GLOBALS['last_sql']);
155         }
156
157         // Return lines
158         return $lines;
159 }
160
161 // SQL affected rows
162 function sqlAffectedRows () {
163         // Valid link resource?
164         if (!isSqlLinkUp()) return FALSE;
165
166         // Get affected rows
167         $lines = mysql_affected_rows(getSqlLink());
168
169         // Return it
170         return $lines;
171 }
172
173 // SQL fetch row
174 function sqlFetchRow ($resource) {
175         // Is $resource valid?
176         if ((!is_resource($resource)) || (!isSqlLinkUp())) return FALSE;
177
178         // Fetch the data and return it
179         return mysql_fetch_row($resource);
180 }
181
182 // SQL fetch array
183 function sqlFetchArray ($resource) {
184         // Is $resource valid?
185         if ((!is_resource($resource)) || (!isSqlLinkUp())) return FALSE;
186
187         // Load row as array from database
188         $row = mysql_fetch_assoc($resource);
189
190         // Return only arrays here
191         if (is_array($row)) {
192                 // Return row
193                 return $row;
194         } else {
195                 // Return a false, else some loops would go endless...
196                 return FALSE;
197         }
198 }
199
200 // SQL result
201 function sqlResult ($resource, $row, $field = '0') {
202         // Is $resource valid?
203         if ((!is_resource($resource)) || (!isSqlLinkUp())) return FALSE;
204
205         // Run the result command
206         $result = mysql_result($resource, $row, $field);
207
208         // ... and return the result
209         return $result;
210 }
211
212 // SQL connect
213 function sqlConnectToDatabase ($host, $login, $password, $file, $line) {
214         // Try to connect
215         $linkResource = mysql_connect($host, $login, $password) or sqlError($file, $line,  mysql_error());
216
217         // Set the link resource
218         if (is_resource($linkResource)) {
219                 /*
220                  * A non-resource (boolean) may happen on installation phase which
221                  * shall not be set here. Only valid link resources shall be set so
222                  * isSqlLinkUp() will only return 'true' if there is really a
223                  * working database link.
224                  */
225                 setSqlLink(__FUNCTION__, __LINE__, $linkResource);
226
227                 // Init charsets (UTF-8 is default now)
228                 sqlQuery("SET
229         `character_set_results`='utf8',
230         `character_set_client`='utf8',
231         `character_set_connection`='utf8',
232         `character_set_database`='utf8',
233         `character_set_server`='utf8'", __FUNCTION__, __LINE__);
234         } // END - if
235
236         // Return the resource
237         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
238         return $linkResource;
239 }
240
241 // SQL select database
242 function sqlSelectDatabase ($dbName, $file, $line) {
243         // Is there still a valid link? If not, skip it.
244         if (!isSqlLinkUp()) return FALSE;
245
246         // Return the result
247         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Selecting database ' . $dbName);
248         return mysql_select_db($dbName, getSqlLink()) or sqlError($file, $line,  mysql_error());
249 }
250
251 // SQL close link
252 function sqlCloseLink ($file, $line) {
253         // Is the link up?
254         if (!isSqlLinkUp()) {
255                 // Skip double close
256                 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Called but no link is open.');
257                 return FALSE;
258         } // END - if
259
260         // Close database link and forget the link
261         $close = mysql_close(getSqlLink()) or sqlError($file . ':' . __FUNCTION__, $line . ':' . __LINE__, mysql_error());
262
263         // Close link in this layer
264         unsetSqlLinkUp(__FUNCTION__, __LINE__);
265
266         // Return the result
267         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
268         return $close;
269 }
270
271 // SQL free result
272 function sqlFreeResult ($resource) {
273         if ((!is_resource($resource)) || (!isSqlLinkUp())) {
274                 // Abort here
275                 return FALSE;
276         } // END - if
277
278         // Free result
279         $res = mysql_free_result($resource);
280
281         // And return that result of freeing it...
282         return $res;
283 }
284
285 // Get id from last INSERT command and secure id
286 function getSqlInsertId () {
287         if (!isSqlLinkUp()) return FALSE;
288         return bigintval(mysql_insert_id());
289 }
290
291 // Escape a string for the database
292 function sqlEscapeString ($str, $secureString = TRUE, $strip = TRUE) {
293         // Is there cache?
294         if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
295                 // Debug message
296                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
297
298                 // Prepare the string here
299                 $str = sqlPrepareQueryString($str);
300
301                 // Debug message
302                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
303
304                 // Secure string first? (which is the default behaviour!)
305                 if ($secureString === TRUE) {
306                         // Debug message
307                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - BEFORE!');
308
309                         // Then do it here
310                         $str = secureString($str, $strip);
311
312                         // Debug message
313                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - AFTER!');
314                 } // END - if
315
316                 // Init (invalid) value
317                 $ret = '!INVALID!';
318
319                 if (!isSqlLinkUp()) {
320                         // Fall-back to escapeQuotes() when there is no link
321                         $ret = escapeQuotes($str);
322                 } elseif (function_exists('mysql_real_escape_string')) {
323                         // Debug message
324                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
325
326                         // The new and improved version
327                         $ret = mysql_real_escape_string($str, getSqlLink());
328
329                         // Debug message
330                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
331                 } elseif (function_exists('mysql_escape_string')) {
332                         // The obsolete function
333                         $ret = mysql_escape_string($str, getSqlLink());
334                 } else {
335                         // If nothing else works, fall back to escapeQuotes() again
336                         $ret = escapeQuotes($str);
337                 }
338
339                 // Log message
340                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
341
342                 // Cache result
343                 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
344         } // END - if
345
346         // Log message
347         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',sql_escapes=' . $GLOBALS['sql_escapes']['' . $str . '']);
348
349         // Return it
350         return $GLOBALS['sql_escapes']['' . $str . ''];
351 }
352
353 // Log SQL errors to debug.log in installation phase or call reportBug()
354 function sqlError ($file, $line, $message) {
355         // Remember plain error in last_sql_error
356         $GLOBALS['last_sql_error'] = mysql_error();
357
358         // Is login set?
359         if (!empty($GLOBALS['mysql']['login'])) {
360                 // Secure login name in message
361                 $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
362         } // END - if
363
364         // Is database password set?
365         if (!empty($GLOBALS['mysql']['password'])) {
366                 // Secure password in message
367                 $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
368         } // END - if
369
370         // Is database name set?
371         if (!empty($GLOBALS['mysql']['dbase'])) {
372                 // Secure database name in message
373                 $message = str_replace($GLOBALS['mysql']['dbase'], '***', $message);
374         } // END - if
375
376         // Is there installation phase?
377         if (isInstallationPhase()) {
378                 /*
379                  * In installation phase, we don't want SQL errors abort e.g. connection
380                  * tests, so just log it away.
381                  */
382                 logDebugMessage($file, $line, $message);
383         } else {
384                 // Regular mode, then call reportBug()
385                 reportBug($file, $line, $message);
386         }
387 }
388
389 // [EOF]
390 ?>