2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/29/2004 *
4 * =================== Last change: 08/29/2004 *
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 * -------------------------------------------------------------------- *
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 = 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='.(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 // Link is not up, no rows by default
142 // Is the result a valid resource?
143 if (isset($GLOBALS['sql_numrows'][intval($resource)])) {
145 $lines = $GLOBALS['sql_numrows'][intval($resource)];
146 } elseif (isValidSqlLink($resource)) {
147 // Get the count of rows from database
148 $lines = mysql_num_rows($resource);
150 // Remember it in cache
151 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
153 // No resource given, please fix this
154 reportBug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
162 function sqlAffectedRows () {
163 // Valid link resource?
164 if (!isSqlLinkUp()) return FALSE;
167 $lines = mysql_affected_rows(getSqlLink());
174 function sqlFetchRow ($resource) {
175 // Is $resource valid?
176 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
178 // Fetch the data and return it
179 return mysql_fetch_row($resource);
183 function sqlFetchArray ($resource) {
184 // Is $resource valid?
185 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
187 // Load row as array from database
188 $row = mysql_fetch_assoc($resource);
190 // Return only arrays here
191 if (is_array($row)) {
195 // Return a false, else some loops would go endless...
201 function sqlResult ($resource, $row, $field = '0') {
202 // Is $resource valid?
203 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
205 // Run the result command
206 $result = mysql_result($resource, $row, $field);
208 // ... and return the result
213 function sqlConnectToDatabase ($host, $login, $password, $file, $line) {
215 $linkResource = mysql_connect($host, $login, $password) or sqlError($file, $line, mysql_error());
217 // Set the link resource
218 if (isValidSqlLink($linkResource)) {
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.
225 setSqlLink($file . ':' . __FUNCTION__, $line . ':' . __LINE__, $linkResource);
227 // Init charsets (UTF-8 is default now)
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'", $file . ':' . __FUNCTION__, $line . ':' . __LINE__);
236 // Return the resource
237 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
238 return $linkResource;
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;
247 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Selecting database ' . $dbName);
248 return mysql_select_db($dbName, getSqlLink()) or sqlError($file, $line, mysql_error());
252 function sqlCloseLink ($file, $line) {
254 if (!isSqlLinkUp()) {
256 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Called but no link is open.');
260 // Close database link and forget the link
261 $close = mysql_close(getSqlLink()) or sqlError($file . ':' . __FUNCTION__, $line . ':' . __LINE__, mysql_error());
263 // Close link in this layer
264 unsetSqlLinkUp(__FUNCTION__, __LINE__);
267 //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
272 function sqlFreeResult ($resource) {
273 if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) {
279 $res = mysql_free_result($resource);
281 // And return that result of freeing it...
285 // Get id from last INSERT command and secure id
286 function getSqlInsertId () {
287 if (!isSqlLinkUp()) return FALSE;
288 return bigintval(mysql_insert_id());
291 // Escape a string for the database
292 function sqlEscapeString ($str, $secureString = TRUE, $strip = TRUE) {
294 if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
296 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
298 // Prepare the string here
299 $str = sqlPrepareQueryString($str);
302 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
304 // Secure string first? (which is the default behaviour!)
305 if ($secureString === TRUE) {
307 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - BEFORE!');
310 $str = secureString($str, $strip);
313 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - AFTER!');
316 // Init (invalid) value
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')) {
324 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
326 // The new and improved version
327 $ret = mysql_real_escape_string($str, getSqlLink());
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());
335 // If nothing else works, fall back to escapeQuotes() again
336 $ret = escapeQuotes($str);
340 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
343 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
347 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',sql_escapes=' . $GLOBALS['sql_escapes']['' . $str . '']);
350 return $GLOBALS['sql_escapes']['' . $str . ''];
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();
359 if (!empty($GLOBALS['mysql']['login'])) {
360 // Secure login name in message
361 $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
364 // Is database password set?
365 if (!empty($GLOBALS['mysql']['password'])) {
366 // Secure password in message
367 $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
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);
376 // Is there installation phase?
379 * In installation phase, we don't want SQL errors abort e.g. connection
380 * tests, so just log it away.
382 logDebugMessage($file, $line, $message);
384 // Regular mode, then call reportBug()
385 reportBug($file, $line, $message);
389 // Checks whether given link is a valid SQL link
390 function isValidSqlLink ($linkResource) {
392 return is_resource($linkResource);