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 - 2012 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 SQL_QUERY ($sqlString, $F, $L, $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 (!SQL_IS_LINK_UP()) {
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 = SQL_PREPARE_SQL_STRING($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);
79 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
81 // Use cache (to save a lot function calls
82 $GLOBALS['last_sql'] = $GLOBALS[__FUNCTION__][$sqlString];
84 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache is: ' . $sqlString);
88 $querytimeBefore = microtime(TRUE);
91 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
92 $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
93 or SQL_ERROR($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . ',last_query=' . $GLOBALS['last_sql']);
94 //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
96 // Calculate query time
97 $queryTime = microtime(TRUE) - $querytimeBefore;
99 // Add this query to array including timing
100 addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
102 // Save last successfull query
103 setConfigEntry('db_last_query', $GLOBALS['last_sql']);
105 // Count all query times
106 incrementConfigEntry('sql_time', $queryTime);
109 incrementConfigEntry('sql_count');
112 if (SQL_DEBUG_ENABLED()) {
113 // Is this the first call?
114 if (!isset($GLOBALS['sql_first_entry'])) {
116 appendLineToFile(getCachePath() . 'mysql.log', 'Module=' . getModule());
117 $GLOBALS['sql_first_entry'] = TRUE;
121 appendLineToFile(getCachePath() . 'mysql.log', basename($F) . '|LINE=' . $L . '|NUM=' . (is_resource($result) ? SQL_NUMROWS($result) : 'false') . '|AFFECTED=' . SQL_AFFECTEDROWS() . '|QUERYTIME:' . ($queryTime * 1000) . 'ms): ' . str_replace(array(chr(13), PHP_EOL), array('', ' '), $GLOBALS['last_sql']));
124 // Increment stats entry
125 incrementStatsEntry('db_hits');
132 function SQL_NUMROWS ($resource) {
133 // Valid link resource?
134 if (!SQL_IS_LINK_UP()) return FALSE;
136 // Link is not up, no rows by default
139 // Is the result a valid resource?
140 if (isset($GLOBALS['sql_numrows'][intval($resource)])) {
142 $lines = $GLOBALS['sql_numrows'][intval($resource)];
143 } elseif (is_resource($resource)) {
144 // Get the count of rows from database
145 $lines = mysql_num_rows($resource);
147 // Remember it in cache
148 $GLOBALS['sql_numrows'][intval($resource)] = $lines;
150 // No resource given, please fix this
151 reportBug(__FUNCTION__, __LINE__, 'No resource given! result[]=' . gettype($resource) . ',last_sql=' . $GLOBALS['last_sql']);
159 function SQL_AFFECTEDROWS() {
160 // Valid link resource?
161 if (!SQL_IS_LINK_UP()) return FALSE;
164 $lines = mysql_affected_rows(SQL_GET_LINK());
171 function SQL_FETCHROW ($resource) {
172 // Is a result resource set?
173 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
175 // Fetch the data and return it
176 return mysql_fetch_row($resource);
180 function SQL_FETCHARRAY ($resource) {
181 // Is a result resource set?
182 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
184 // Load row from database
185 $row = mysql_fetch_assoc($resource);
187 // Return only arrays here
188 if (is_array($row)) {
192 // Return a false, else some loops would go endless...
198 function SQL_RESULT ($resource, $row, $field = '0') {
199 // Is $resource valid?
200 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
202 // Run the result command
203 $result = mysql_result($resource, $row, $field);
205 // ... and return the result
210 function SQL_CONNECT ($host, $login, $password, $F, $L) {
212 $linkResource = mysql_connect($host, $login, $password) or SQL_ERROR($F, $L, mysql_error());
214 // Set the link resource
215 if (is_resource($linkResource)) {
217 * A non-resource (boolean) may happen on installation phase which
218 * shall not be set here. Only valid link resources shall be set so
219 * SQL_IS_LINK_UP() will only return 'true' if there is really a
220 * working database link.
222 SQL_SET_LINK($linkResource);
225 // Return the resource
226 return $linkResource;
229 // SQL select database
230 function SQL_SELECT_DB ($dbName, $F, $L) {
231 // Is there still a valid link? If not, skip it.
232 if (!SQL_IS_LINK_UP()) return FALSE;
235 return mysql_select_db($dbName, SQL_GET_LINK()) or SQL_ERROR($F, $L, mysql_error());
239 function SQL_CLOSE ($F, $L) {
240 if (!SQL_IS_LINK_UP()) {
245 // Close database link and forget the link
246 $close = mysql_close(SQL_GET_LINK()) or SQL_ERROR($F, $L, mysql_error());
256 function SQL_FREERESULT ($resource) {
257 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
263 $res = mysql_free_result($resource);
265 // And return that result of freeing it...
269 // Get id from last INSERT command
270 function SQL_INSERTID () {
271 if (!SQL_IS_LINK_UP()) return FALSE;
272 return mysql_insert_id();
275 // Escape a string for the database
276 function SQL_ESCAPE ($str, $secureString = TRUE, $strip = TRUE) {
278 if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
280 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
282 // Prepare the string here
283 $str = SQL_PREPARE_SQL_STRING($str);
286 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
288 // Secure string first? (which is the default behaviour!)
289 if ($secureString === TRUE) {
291 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - BEFORE!');
294 $str = secureString($str, $strip);
297 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',strip=' . intval($strip) . ' - AFTER!');
300 // Init (invalid) value
303 if (!SQL_IS_LINK_UP()) {
304 // Fall-back to escapeQuotes() when there is no link
305 $ret = escapeQuotes($str);
306 } elseif (function_exists('mysql_real_escape_string')) {
308 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
310 // The new and improved version
311 $ret = mysql_real_escape_string($str, SQL_GET_LINK());
314 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
315 } elseif (function_exists('mysql_escape_string')) {
316 // The obsolete function
317 $ret = mysql_escape_string($str, SQL_GET_LINK());
319 // If nothing else works, fall back to escapeQuotes() again
320 $ret = escapeQuotes($str);
324 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
327 $GLOBALS['sql_escapes']['' . $str . ''] = $ret;
331 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',sql_escapes=' . $GLOBALS['sql_escapes']['' . $str . '']);
334 return $GLOBALS['sql_escapes']['' . $str . ''];
337 // Log SQL errors to debug.log in installation phase or call reportBug()
338 function SQL_ERROR ($file, $line, $message) {
339 // Remember plain error in last_sql_error
340 $GLOBALS['last_sql_error'] = mysql_error();
342 // Is there installation phase?
343 if (isInstallationPhase()) {
345 * In installation phase, we don't want SQL errors abort e.g. connection
346 * tests, so just log it away.
348 logDebugMessage($file, $line, $message);
350 // Regular mode, then call reportBug()
351 reportBug($file, $line, $message);