Fixed handling of SQL strings
[mailer.git] / inc / db / lib-mysqli.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 06/12/2013 *
4  * ===================                          Last change: 06/12/2013 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : lib-mysqli.php                                   *
8  * -------------------------------------------------------------------- *
9  * Short description : Database layer for MySQL 3/4/5 server (MySQLi)   *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Datenbankschicht fuer MySQL 3/4/5 Server (MySQLi)*
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                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlStringModified=' . $sqlStringModified . ',enableCodes=' . intval($enableCodes));
73                 $sqlStringModified = sqlPrepareQueryString($sqlStringModified, $enableCodes);
74                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlStringModified=' . $sqlStringModified . ',enableCodes=' . intval($enableCodes));
75
76                 // Cache it and remember as last SQL query
77                 $GLOBALS[__FUNCTION__][$sqlString] = $sqlStringModified;
78                 $GLOBALS['last_sql']               = $sqlStringModified;
79                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Stored cache: ' . $sqlStringModified);
80         } elseif (!isSqlLinkUp()) {
81                 // Link went down while using cached SQL
82                 reportBug(__FUNCTION__, __LINE__, 'Link went down while using cached SQL: sqlString=' . $sqlString . ',file=' . basename($file) . ',line=' . $line . ',enableCodes=' . intval($enableCodes));
83         } else {
84                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
85
86                 // Use cache (to save a lot function calls
87                 $GLOBALS['last_sql'] = $GLOBALS[__FUNCTION__][$sqlString];
88
89                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache is: ' . $sqlString);
90         }
91
92         // Starting time
93         $querytimeBefore = microtime(TRUE);
94
95         // Run SQL command
96         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($file) . ',line=' . $line . ',sql=' . $GLOBALS['last_sql']);
97         $result = mysqli_query(getSqlLink(), $GLOBALS['last_sql'])
98                 or sqlError($file, $line, 'file='. basename($file) . ',line=' . $line . ':mysqli_error()=' . mysqli_error(getSqlLink()) . ',last_query=' . $GLOBALS['last_sql']);
99         //* DEBUG: */ logDebugMessage($file, $line, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . sqlAffectedRows() . ',numRows='.(isValidSqlLink($result) ? sqlNumRows($result) : gettype($result)));
100
101         // Calculate query time
102         $queryTime = microtime(TRUE) - $querytimeBefore;
103
104         // Add this query to array including timing
105         addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $file, $line);
106
107         // Save last successfull query
108         setConfigEntry('db_last_query', $GLOBALS['last_sql']);
109
110         // Count all query times
111         incrementConfigEntry('sql_time', $queryTime);
112
113         // Count this query
114         incrementConfigEntry('sql_count');
115
116         // Debug output
117         if (isSqlDebugEnabled()) {
118                 // Is this the first call?
119                 if (!isset($GLOBALS['sql_first_entry'])) {
120                         // Write first entry
121                         appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
122                         $GLOBALS['sql_first_entry'] = TRUE;
123                 } // END - if
124
125                 // Append debug line
126                 appendLineToFile(getCachePath() . 'mysql.log', basename($file) . '|LINE=' . $line . '|NUM=' . (isValidSqlLink($result) ? sqlNumRows($result) : 'false') . '|AFFECTED=' . sqlAffectedRows() . '|QUERYTIME:' . ($queryTime * 1000) . 'ms): ' . str_replace(array(chr(13), PHP_EOL), array('', ' '), $GLOBALS['last_sql']));
127         } // END - if
128
129         // Increment stats entry
130         incrementStatsEntry('db_hits');
131
132         // Return the result
133         return $result;
134 }
135
136 // SQL num rows
137 function sqlNumRows ($resource) {
138         // Valid link resource?
139         if (!isSqlLinkUp()) return FALSE;
140
141         // Get the count of rows from database
142         $lines = mysqli_num_rows($resource);
143
144         // Return lines
145         return $lines;
146 }
147
148 // SQL affected rows
149 function sqlAffectedRows () {
150         // Valid link resource?
151         if (!isSqlLinkUp()) return FALSE;
152
153         // Get affected rows
154         $lines = mysqli_affected_rows(getSqlLink());
155
156         // Return it
157         return $lines;
158 }
159
160 // SQL fetch row
161 function sqlFetchRow ($resource) {
162         // Is $resource valid?
163         if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
164
165         // Fetch the data and return it
166         return mysqli_fetch_row($resource);
167 }
168
169 // SQL fetch array
170 function sqlFetchArray ($resource) {
171         // Is $resource valid?
172         if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
173
174         // Load row as array from database
175         $row = mysqli_fetch_assoc($resource);
176
177         // Return only arrays here
178         if (is_array($row)) {
179                 // Return row
180                 return $row;
181         } else {
182                 // Return a false, else some loops would go endless...
183                 return FALSE;
184         }
185 }
186
187 // SQL result
188 function sqlResult ($resource, $row, $field = '0') {
189         // Is $resource valid?
190         if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
191
192         // Run the result command
193         $result = mysqli_result($resource, $row, $field);
194
195         // ... and return the result
196         return $result;
197 }
198
199 // SQL connect
200 function sqlConnectToDatabase ($host, $login, $password, $file, $line) {
201         // Try to connect
202         $linkResource = mysqli_connect($host, $login, $password) or sqlError($file, $line,  mysqli_error(getSqlLink()));
203
204         // Set the link resource
205         if ($linkResource instanceof mysqli) {
206                 /*
207                  * A non-resource (boolean) may happen on installation phase which
208                  * shall not be set here. Only valid link resources shall be set so
209                  * isSqlLinkUp() will only return 'true' if there is really a
210                  * working database link.
211                  */
212                 setSqlLink($file . ':' . __FUNCTION__, $line . ':' . __LINE__, $linkResource);
213
214                 // Init charsets (UTF-8 is default now)
215                 sqlQuery("SET
216         `character_set_results`='utf8',
217         `character_set_client`='utf8',
218         `character_set_connection`='utf8',
219         `character_set_database`='utf8',
220         `character_set_server`='utf8'", $file . ':' . __FUNCTION__, $line . ':' . __LINE__);
221         } // END - if
222
223         // Any errors encountered?
224         if (mysqli_connect_error()) {
225                 // Something went horrible wrong
226                 reportBug($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
227         } // END - if
228
229         // Return the resource
230         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
231         return $linkResource;
232 }
233
234 // SQL select database
235 function sqlSelectDatabase ($dbName, $file, $line) {
236         // Is there still a valid link? If not, skip it.
237         if (!isSqlLinkUp()) return FALSE;
238
239         // Return the result
240         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Selecting database ' . $dbName);
241         return mysqli_select_db(getSqlLink(), $dbName) or sqlError($file, $line,  mysqli_error(getSqlLink()));
242 }
243
244 // SQL close link
245 function sqlCloseLink ($file, $line) {
246         // Is the link up?
247         if (!isSqlLinkUp()) {
248                 // Skip double close
249                 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Called but no link is open.');
250                 return FALSE;
251         } // END - if
252
253         // Close database link and forget the link
254         $close = mysqli_close(getSqlLink()) or sqlError($file . ':' . __FUNCTION__, $line . ':' . __LINE__, mysqli_error(getSqlLink()));
255
256         // Close link in this layer
257         unsetSqlLinkUp(__FUNCTION__, __LINE__);
258
259         // Return the result
260         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
261         return $close;
262 }
263
264 // SQL free result
265 function sqlFreeResult ($resource) {
266         if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) {
267                 // Abort here
268                 return FALSE;
269         } // END - if
270
271         // Free result
272         $res = mysqli_free_result($resource);
273
274         // And return that result of freeing it...
275         return $res;
276 }
277
278 // Get id from last INSERT command and secure id
279 function getSqlInsertId () {
280         if (!isSqlLinkUp()) return FALSE;
281         return bigintval(mysqli_insert_id(getSqlLink()));
282 }
283
284 // Escape a string for the database
285 function sqlEscapeString ($str, $secureString = TRUE, $strip = TRUE) {
286         // Is there cache?
287         if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
288                 // Debug message
289                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
290
291                 // Prepare the string here
292                 $str = sqlPrepareQueryString($str);
293
294                 // Debug message
295                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
296
297                 // Secure string first? (which is the default behaviour!)
298                 if ($secureString === TRUE) {
299                         // Debug message
300                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - BEFORE!');
301
302                         // Then do it here
303                         $str = secureString($str, $strip);
304
305                         // Debug message
306                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - AFTER!');
307                 } // END - if
308
309                 // Init (invalid) value
310                 $ret = '!INVALID!';
311
312                 if (!isSqlLinkUp()) {
313                         // Fall-back to escapeQuotes() when there is no link
314                         $ret = escapeQuotes($str);
315                 } elseif (function_exists('mysqli_real_escape_string')) {
316                         // Debug message
317                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
318
319                         // The new and improved version
320                         $ret = mysqli_real_escape_string(getSqlLink(), $str);
321
322                         // Debug message
323                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
324                 } else {
325                         // If nothing else works, fall back to escapeQuotes() again
326                         $ret = escapeQuotes($str);
327                 }
328
329                 // Log message
330                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
331
332                 // Cache result
333                 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
334         } // END - if
335
336         // Log message
337         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',sql_escapes=' . $GLOBALS['sql_escapes']['' . $str . '']);
338
339         // Return it
340         return $GLOBALS['sql_escapes']['' . $str . ''];
341 }
342
343 // Log SQL errors to debug.log in installation phase or call reportBug()
344 function sqlError ($file, $line, $message) {
345         // Remember plain error in last_sql_error
346         $GLOBALS['last_sql_error'] = mysqli_error(getSqlLink());
347
348         // Is login set?
349         if (!empty($GLOBALS['mysql']['login'])) {
350                 // Secure login name in message
351                 $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
352         } // END - if
353
354         // Is database password set?
355         if (!empty($GLOBALS['mysql']['password'])) {
356                 // Secure password in message
357                 $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
358         } // END - if
359
360         // Is database name set?
361         if (!empty($GLOBALS['mysql']['dbase'])) {
362                 // Secure database name in message
363                 $message = str_replace($GLOBALS['mysql']['dbase'], '***', $message);
364         } // END - if
365
366         // Is there installation phase?
367         if (isInstaller()) {
368                 /*
369                  * In installation phase, we don't want SQL errors abort e.g. connection
370                  * tests, so just log it away.
371                  */
372                 logDebugMessage($file, $line, $message);
373         } else {
374                 // Regular mode, then call reportBug()
375                 reportBug($file, $line, $message);
376         }
377 }
378
379 // Checks whether given link is a valid SQL link
380 function isValidSqlLink ($linkInstance) {
381         // Is it a resource?
382         $isValid = (($linkInstance instanceof mysqli) || ($linkInstance instanceof mysqli_result));
383
384         // Debug message
385         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'linkInstance[]=' . gettype($linkInstance). ',isValid=' . intval($isValid));
386
387         // Return result
388         return $isValid;
389 }
390
391 // [EOF]
392 ?>