2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 06/12/2013 *
4 * =================== Last change: 06/12/2013 *
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 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
44 function sqlQuery ($sqlString, $file, $line, $enableCodes = TRUE) {
46 if (!isset($GLOBALS[__FUNCTION__][$sqlString])) {
47 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called: ' . $sqlString);
50 $sqlStringModified = trim($sqlString);
52 // Empty query string or link is not up?
53 if (empty($sqlStringModified)) {
55 reportBug(__FUNCTION__, __LINE__, sprintf('SQL string is empty, please fix this: file=%s, line=%s',
59 } elseif (!isSqlLinkUp()) {
60 // We should not quietly ignore this
61 reportBug(__FUNCTION__, __LINE__, sprintf('Cannot query database: sqlString=%s,file=%s,line=%s',
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);
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));
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));
84 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
86 // Use cache (to save a lot function calls
87 $GLOBALS['last_sql'] = $GLOBALS[__FUNCTION__][$sqlString];
89 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache is: ' . $sqlString);
93 $querytimeBefore = microtime(TRUE);
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)));
101 // Calculate query time
102 $queryTime = microtime(TRUE) - $querytimeBefore;
104 // Add this query to array including timing
105 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $file, $line);
107 // Save last successfull query
108 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
110 // Count all query times
111 incrementConfigEntry('sql_time', $queryTime);
114 incrementConfigEntry('sql_count');
117 if (isSqlDebugEnabled()) {
118 // Is this the first call?
119 if (!isset($GLOBALS['sql_first_entry'])) {
121 appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
122 $GLOBALS['sql_first_entry'] = TRUE;
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']));
129 // Increment stats entry
130 incrementStatsEntry('db_hits');
137 function sqlNumRows ($resource) {
138 // Valid link resource?
139 if (!isSqlLinkUp()) return FALSE;
141 // Get the count of rows from database
142 $lines = mysqli_num_rows($resource);
149 function sqlAffectedRows () {
150 // Valid link resource?
151 if (!isSqlLinkUp()) return FALSE;
154 $lines = mysqli_affected_rows(getSqlLink());
161 function sqlFetchRow ($resource) {
162 // Is $resource valid?
163 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
165 // Fetch the data and return it
166 return mysqli_fetch_row($resource);
170 function sqlFetchArray ($resource) {
171 // Is $resource valid?
172 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
174 // Load row as array from database
175 $row = mysqli_fetch_assoc($resource);
177 // Return only arrays here
178 if (is_array($row)) {
182 // Return a false, else some loops would go endless...
188 function sqlResult ($resource, $row, $field = '0') {
189 // Is $resource valid?
190 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
192 // Run the result command
193 $result = mysqli_result($resource, $row, $field);
195 // ... and return the result
200 function sqlConnectToDatabase ($host, $login, $password, $file, $line) {
202 $linkResource = mysqli_connect($host, $login, $password) or sqlError($file, $line, mysqli_error(getSqlLink()));
204 // Set the link resource
205 if ($linkResource instanceof mysqli) {
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.
212 setSqlLink($file . ':' . __FUNCTION__, $line . ':' . __LINE__, $linkResource);
214 // Init charsets (UTF-8 is default now)
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__);
222 // Disallow subtraction for unsigned columns
223 sqlQuery("SET `sql_mode`='NO_UNSIGNED_SUBTRACTION'", $file . ':' . __FUNCTION__, $line . ':' . __LINE__);
226 // Any errors encountered?
227 if (mysqli_connect_error()) {
228 // Something went horrible wrong
229 reportBug($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
232 // Return the resource
233 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
234 return $linkResource;
237 // SQL select database
238 function sqlSelectDatabase ($dbName, $file, $line) {
239 // Is there still a valid link? If not, skip it.
240 if (!isSqlLinkUp()) return FALSE;
243 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Selecting database ' . $dbName);
244 return mysqli_select_db(getSqlLink(), $dbName) or sqlError($file, $line, mysqli_error(getSqlLink()));
248 function sqlCloseLink ($file, $line) {
250 if (!isSqlLinkUp()) {
252 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Called but no link is open.');
256 // Close database link and forget the link
257 $close = mysqli_close(getSqlLink()) or sqlError($file . ':' . __FUNCTION__, $line . ':' . __LINE__, mysqli_error(getSqlLink()));
259 // Close link in this layer
260 unsetSqlLinkUp(__FUNCTION__, __LINE__);
263 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
268 function sqlFreeResult ($resource) {
269 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) {
275 $res = mysqli_free_result($resource);
277 // And return that result of freeing it...
281 // Get id from last INSERT command and secure id
282 function getSqlInsertId () {
283 if (!isSqlLinkUp()) return FALSE;
284 return bigintval(mysqli_insert_id(getSqlLink()));
287 // Escape a string for the database
288 function sqlEscapeString ($str, $secureString = TRUE, $strip = TRUE) {
290 if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
292 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
294 // Prepare the string here
295 $str = sqlPrepareQueryString($str);
298 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
300 // Secure string first? (which is the default behaviour!)
301 if ($secureString === TRUE) {
303 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - BEFORE!');
306 $str = secureString($str, $strip);
309 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - AFTER!');
312 // Init (invalid) value
315 if (!isSqlLinkUp()) {
316 // Fall-back to escapeQuotes() when there is no link
317 $ret = escapeQuotes($str);
318 } elseif (function_exists('mysqli_real_escape_string')) {
320 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
322 // The new and improved version
323 $ret = mysqli_real_escape_string(getSqlLink(), $str);
326 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
328 // If nothing else works, fall back to escapeQuotes() again
329 $ret = escapeQuotes($str);
333 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
336 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
340 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',sql_escapes=' . $GLOBALS['sql_escapes']['' . $str . '']);
343 return $GLOBALS['sql_escapes']['' . $str . ''];
346 // Log SQL errors to debug.log in installation phase or call reportBug()
347 function sqlError ($file, $line, $message) {
348 // Remember plain error in last_sql_error
349 $GLOBALS['last_sql_error'] = mysqli_error(getSqlLink());
352 if (!empty($GLOBALS['mysql']['login'])) {
353 // Secure login name in message
354 $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
357 // Is database password set?
358 if (!empty($GLOBALS['mysql']['password'])) {
359 // Secure password in message
360 $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
363 // Is database name set?
364 if (!empty($GLOBALS['mysql']['dbase'])) {
365 // Secure database name in message
366 $message = str_replace($GLOBALS['mysql']['dbase'], '***', $message);
369 // Is there installation phase?
372 * In installation phase, we don't want SQL errors abort e.g. connection
373 * tests, so just log it away.
375 logDebugMessage($file, $line, $message);
377 // Regular mode, then call reportBug()
378 reportBug($file, $line, $message);
382 // Checks whether given link is a valid SQL link
383 function isValidSqlLink ($linkInstance) {
385 $isValid = (($linkInstance instanceof mysqli) || ($linkInstance instanceof mysqli_result));
388 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'linkInstance[]=' . gettype($linkInstance). ',isValid=' . intval($isValid));