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 $sqlStringModified = sqlPrepareQueryString($sqlStringModified, $enableCodes);
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));
82 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
84 // Use cache (to save a lot function calls
85 $GLOBALS['last_sql'] = $GLOBALS[__FUNCTION__][$sqlString];
87 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache is: ' . $sqlString);
91 $querytimeBefore = microtime(TRUE);
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(getSqlLink()) . ',last_query=' . $GLOBALS['last_sql']);
97 //* DEBUG: */ logDebugMessage($file, $line, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . sqlAffectedRows() . ',numRows='.(isValidSqlLink($result) ? sqlNumRows($result) : gettype($result)));
99 // Calculate query time
100 $queryTime = microtime(TRUE) - $querytimeBefore;
102 // Add this query to array including timing
103 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $file, $line);
105 // Save last successfull query
106 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
108 // Count all query times
109 incrementConfigEntry('sql_time', $queryTime);
112 incrementConfigEntry('sql_count');
115 if (isSqlDebugEnabled()) {
116 // Is this the first call?
117 if (!isset($GLOBALS['sql_first_entry'])) {
119 appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
120 $GLOBALS['sql_first_entry'] = TRUE;
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']));
127 // Increment stats entry
128 incrementStatsEntry('db_hits');
135 function sqlNumRows ($resource) {
136 // Valid link resource?
137 if (!isSqlLinkUp()) return FALSE;
139 // Get the count of rows from database
140 $lines = mysqli_num_rows($resource);
147 function sqlAffectedRows () {
148 // Valid link resource?
149 if (!isSqlLinkUp()) return FALSE;
152 $lines = mysqli_affected_rows(getSqlLink());
159 function sqlFetchRow ($resource) {
160 // Is $resource valid?
161 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
163 // Fetch the data and return it
164 return mysqli_fetch_row($resource);
168 function sqlFetchArray ($resource) {
169 // Is $resource valid?
170 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
172 // Load row as array from database
173 $row = mysqli_fetch_assoc($resource);
175 // Return only arrays here
176 if (is_array($row)) {
180 // Return a false, else some loops would go endless...
186 function sqlResult ($resource, $row, $field = '0') {
187 // Is $resource valid?
188 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
190 // Run the result command
191 $result = mysqli_result($resource, $row, $field);
193 // ... and return the result
198 function sqlConnectToDatabase ($host, $login, $password, $file, $line) {
200 $linkResource = mysqli_connect($host, $login, $password) or sqlError($file, $line, mysqli_error(getSqlLink()));
202 // Set the link resource
203 if ($linkResource instanceof mysqli) {
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.
210 setSqlLink($file . ':' . __FUNCTION__, $line . ':' . __LINE__, $linkResource);
212 // Init charsets (UTF-8 is default now)
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__);
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());
227 // Return the resource
228 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
229 return $linkResource;
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;
238 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Selecting database ' . $dbName);
239 return mysqli_select_db(getSqlLink(), $dbName) or sqlError($file, $line, mysqli_error(getSqlLink()));
243 function sqlCloseLink ($file, $line) {
245 if (!isSqlLinkUp()) {
247 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Called but no link is open.');
251 // Close database link and forget the link
252 $close = mysqli_close(getSqlLink()) or sqlError($file . ':' . __FUNCTION__, $line . ':' . __LINE__, mysqli_error(getSqlLink()));
254 // Close link in this layer
255 unsetSqlLinkUp(__FUNCTION__, __LINE__);
258 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
263 function sqlFreeResult ($resource) {
264 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) {
270 $res = mysqli_free_result($resource);
272 // And return that result of freeing it...
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()));
282 // Escape a string for the database
283 function sqlEscapeString ($str, $secureString = TRUE, $strip = TRUE) {
285 if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
287 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
289 // Prepare the string here
290 $str = sqlPrepareQueryString($str);
293 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
295 // Secure string first? (which is the default behaviour!)
296 if ($secureString === TRUE) {
298 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - BEFORE!');
301 $str = secureString($str, $strip);
304 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - AFTER!');
307 // Init (invalid) value
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')) {
315 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
317 // The new and improved version
318 $ret = mysqli_real_escape_string(getSqlLink(), $str);
321 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
323 // If nothing else works, fall back to escapeQuotes() again
324 $ret = escapeQuotes($str);
328 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
331 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
335 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',sql_escapes=' . $GLOBALS['sql_escapes']['' . $str . '']);
338 return $GLOBALS['sql_escapes']['' . $str . ''];
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());
347 if (!empty($GLOBALS['mysql']['login'])) {
348 // Secure login name in message
349 $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
352 // Is database password set?
353 if (!empty($GLOBALS['mysql']['password'])) {
354 // Secure password in message
355 $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
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);
364 // Is there installation phase?
367 * In installation phase, we don't want SQL errors abort e.g. connection
368 * tests, so just log it away.
370 logDebugMessage($file, $line, $message);
372 // Regular mode, then call reportBug()
373 reportBug($file, $line, $message);
377 // Checks whether given link is a valid SQL link
378 function isValidSqlLink ($linkInstance) {
380 $isValid = (($linkInstance instanceof mysqli) || ($linkInstance instanceof mysqli_result));
383 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'linkInstance[]=' . gettype($linkInstance). ',isValid=' . intval($isValid));