46b343fba0b13fe59bdbcb48a36dfaac246a0000
[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                 $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 = mysqli_query(getSqlLink(), $GLOBALS['last_sql'])
96                 or sqlError($file, $line, 'file='. basename($file) . ',line=' . $line . ':mysqli_error()=' . mysqli_error() . ',last_query=' . $GLOBALS['last_sql']);
97         //* DEBUG: */ logDebugMessage($file, $line, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . sqlAffectedRows() . ',numRows='.(isValidSqlLink($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=' . (isValidSqlLink($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         // Get the count of rows from database
140         $lines = mysqli_num_rows($resource);
141
142         // Return lines
143         return $lines;
144 }
145
146 // SQL affected rows
147 function sqlAffectedRows () {
148         // Valid link resource?
149         if (!isSqlLinkUp()) return FALSE;
150
151         // Get affected rows
152         $lines = mysqli_affected_rows(getSqlLink());
153
154         // Return it
155         return $lines;
156 }
157
158 // SQL fetch row
159 function sqlFetchRow ($resource) {
160         // Is $resource valid?
161         if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
162
163         // Fetch the data and return it
164         return mysqli_fetch_row($resource);
165 }
166
167 // SQL fetch array
168 function sqlFetchArray ($resource) {
169         // Is $resource valid?
170         if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
171
172         // Load row as array from database
173         $row = mysqli_fetch_assoc($resource);
174
175         // Return only arrays here
176         if (is_array($row)) {
177                 // Return row
178                 return $row;
179         } else {
180                 // Return a false, else some loops would go endless...
181                 return FALSE;
182         }
183 }
184
185 // SQL result
186 function sqlResult ($resource, $row, $field = '0') {
187         // Is $resource valid?
188         if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
189
190         // Run the result command
191         $result = mysqli_result($resource, $row, $field);
192
193         // ... and return the result
194         return $result;
195 }
196
197 // SQL connect
198 function sqlConnectToDatabase ($host, $login, $password, $file, $line) {
199         // Try to connect
200         $linkResource = mysqli_connect($host, $login, $password) or sqlError($file, $line,  mysqli_error());
201
202         // Set the link resource
203         if ($linkResource instanceof mysqli) {
204                 /*
205                  * A non-resource (boolean) may happen on installation phase which
206                  * shall not be set here. Only valid link resources shall be set so
207                  * isSqlLinkUp() will only return 'true' if there is really a
208                  * working database link.
209                  */
210                 setSqlLink($file . ':' . __FUNCTION__, $line . ':' . __LINE__, $linkResource);
211
212                 // Init charsets (UTF-8 is default now)
213                 sqlQuery("SET
214         `character_set_results`='utf8',
215         `character_set_client`='utf8',
216         `character_set_connection`='utf8',
217         `character_set_database`='utf8',
218         `character_set_server`='utf8'", $file . ':' . __FUNCTION__, $line . ':' . __LINE__);
219         } // END - if
220
221         // Any errors encountered?
222         if (mysqli_connect_error()) {
223                 // Something went horrible wrong
224                 reportBug($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
225         } // END - if
226
227         // Return the resource
228         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
229         return $linkResource;
230 }
231
232 // SQL select database
233 function sqlSelectDatabase ($dbName, $file, $line) {
234         // Is there still a valid link? If not, skip it.
235         if (!isSqlLinkUp()) return FALSE;
236
237         // Return the result
238         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Selecting database ' . $dbName);
239         return mysqli_select_db(getSqlLink(), $dbName) or sqlError($file, $line,  mysqli_error());
240 }
241
242 // SQL close link
243 function sqlCloseLink ($file, $line) {
244         // Is the link up?
245         if (!isSqlLinkUp()) {
246                 // Skip double close
247                 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Called but no link is open.');
248                 return FALSE;
249         } // END - if
250
251         // Close database link and forget the link
252         $close = mysqli_close(getSqlLink()) or sqlError($file . ':' . __FUNCTION__, $line . ':' . __LINE__, mysqli_error());
253
254         // Close link in this layer
255         unsetSqlLinkUp(__FUNCTION__, __LINE__);
256
257         // Return the result
258         //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
259         return $close;
260 }
261
262 // SQL free result
263 function sqlFreeResult ($resource) {
264         if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) {
265                 // Abort here
266                 return FALSE;
267         } // END - if
268
269         // Free result
270         $res = mysqli_free_result($resource);
271
272         // And return that result of freeing it...
273         return $res;
274 }
275
276 // Get id from last INSERT command and secure id
277 function getSqlInsertId () {
278         if (!isSqlLinkUp()) return FALSE;
279         return bigintval(mysqli_insert_id(getSqlLink()));
280 }
281
282 // Escape a string for the database
283 function sqlEscapeString ($str, $secureString = TRUE, $strip = TRUE) {
284         // Is there cache?
285         if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
286                 // Debug message
287                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
288
289                 // Prepare the string here
290                 $str = sqlPrepareQueryString($str);
291
292                 // Debug message
293                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
294
295                 // Secure string first? (which is the default behaviour!)
296                 if ($secureString === TRUE) {
297                         // Debug message
298                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - BEFORE!');
299
300                         // Then do it here
301                         $str = secureString($str, $strip);
302
303                         // Debug message
304                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - AFTER!');
305                 } // END - if
306
307                 // Init (invalid) value
308                 $ret = '!INVALID!';
309
310                 if (!isSqlLinkUp()) {
311                         // Fall-back to escapeQuotes() when there is no link
312                         $ret = escapeQuotes($str);
313                 } elseif (function_exists('mysqli_real_escape_string')) {
314                         // Debug message
315                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
316
317                         // The new and improved version
318                         $ret = mysqli_real_escape_string(getSqlLink(), $str);
319
320                         // Debug message
321                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
322                 } else {
323                         // If nothing else works, fall back to escapeQuotes() again
324                         $ret = escapeQuotes($str);
325                 }
326
327                 // Log message
328                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
329
330                 // Cache result
331                 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
332         } // END - if
333
334         // Log message
335         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',sql_escapes=' . $GLOBALS['sql_escapes']['' . $str . '']);
336
337         // Return it
338         return $GLOBALS['sql_escapes']['' . $str . ''];
339 }
340
341 // Log SQL errors to debug.log in installation phase or call reportBug()
342 function sqlError ($file, $line, $message) {
343         // Remember plain error in last_sql_error
344         $GLOBALS['last_sql_error'] = mysqli_error(getSqlLink());
345
346         // Is login set?
347         if (!empty($GLOBALS['mysql']['login'])) {
348                 // Secure login name in message
349                 $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
350         } // END - if
351
352         // Is database password set?
353         if (!empty($GLOBALS['mysql']['password'])) {
354                 // Secure password in message
355                 $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
356         } // END - if
357
358         // Is database name set?
359         if (!empty($GLOBALS['mysql']['dbase'])) {
360                 // Secure database name in message
361                 $message = str_replace($GLOBALS['mysql']['dbase'], '***', $message);
362         } // END - if
363
364         // Is there installation phase?
365         if (isInstaller()) {
366                 /*
367                  * In installation phase, we don't want SQL errors abort e.g. connection
368                  * tests, so just log it away.
369                  */
370                 logDebugMessage($file, $line, $message);
371         } else {
372                 // Regular mode, then call reportBug()
373                 reportBug($file, $line, $message);
374         }
375 }
376
377 // Checks whether given link is a valid SQL link
378 function isValidSqlLink ($linkInstance) {
379         // Is it a resource?
380         $isValid = (($linkInstance instanceof mysqli) || ($linkInstance instanceof mysqli_result));
381
382         // Debug message
383         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'linkInstance[]=' . gettype($linkInstance). ',isValid=' . intval($isValid));
384
385         // Return result
386         return $isValid;
387 }
388
389 // [EOF]
390 ?>