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);
78 } elseif (!SQL_IS_LINK_UP()) {
79 // Link went down while using cached SQL
80 reportBug(__FUNCTION__, __LINE__, 'Link went down while using cached SQL: sqlString=' . $sqlString . ',F=' . basename($F) . ',L=' . $L . ',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__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
95 $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
96 or SQL_ERROR($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . ',last_query=' . $GLOBALS['last_sql']);
97 //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($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, $F, $L);
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 (SQL_DEBUG_ENABLED()) {
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($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']));
127 // Increment stats entry
128 incrementStatsEntry('db_hits');
135 function SQL_NUMROWS ($resource) {
136 // Valid link resource?
137 if (!SQL_IS_LINK_UP()) 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 (is_resource($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 SQL_AFFECTEDROWS() {
163 // Valid link resource?
164 if (!SQL_IS_LINK_UP()) return FALSE;
167 $lines = mysql_affected_rows(SQL_GET_LINK());
174 function SQL_FETCHROW ($resource) {
175 // Is $resource valid?
176 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
178 // Fetch the data and return it
179 return mysql_fetch_row($resource);
183 function SQL_FETCHARRAY ($resource) {
184 // Is $resource valid?
185 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) 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 SQL_RESULT ($resource, $row, $field = '0') {
202 // Is $resource valid?
203 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
205 // Run the result command
206 $result = mysql_result($resource, $row, $field);
208 // ... and return the result
213 function SQL_CONNECT ($host, $login, $password, $F, $L) {
215 $linkResource = mysql_connect($host, $login, $password) or SQL_ERROR($F, $L, mysql_error());
217 // Set the link resource
218 if (is_resource($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 * SQL_IS_LINK_UP() will only return 'true' if there is really a
223 * working database link.
225 SQL_SET_LINK(__FUNCTION__, __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'", __FUNCTION__, __LINE__);
236 // Return the resource
237 //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
238 return $linkResource;
241 // SQL select database
242 function SQL_SELECT_DB ($dbName, $F, $L) {
243 // Is there still a valid link? If not, skip it.
244 if (!SQL_IS_LINK_UP()) return FALSE;
247 //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'Selecting database ' . $dbName);
248 return mysql_select_db($dbName, SQL_GET_LINK()) or SQL_ERROR($F, $L, mysql_error());
252 function SQL_CLOSE ($F, $L) {
254 if (!SQL_IS_LINK_UP()) {
256 //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'Called but no link is open.');
260 // Close database link and forget the link
261 $close = mysql_close(SQL_GET_LINK()) or SQL_ERROR($F . ':' . __FUNCTION__, $L . ':' . __LINE__, mysql_error());
263 // Close link in this layer
264 unsetSqlLinkUp(__FUNCTION__, __LINE__);
267 //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
272 function SQL_FREERESULT ($resource) {
273 if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
279 $res = mysql_free_result($resource);
281 // And return that result of freeing it...
285 // Get id from last INSERT command
286 function SQL_INSERTID () {
287 if (!SQL_IS_LINK_UP()) return FALSE;
288 return mysql_insert_id();
291 // Escape a string for the database
292 function SQL_ESCAPE ($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 = SQL_PREPARE_SQL_STRING($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 (!SQL_IS_LINK_UP()) {
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, SQL_GET_LINK());
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, SQL_GET_LINK());
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 SQL_ERROR ($file, $line, $message) {
355 // Remember plain error in last_sql_error
356 $GLOBALS['last_sql_error'] = mysql_error();
358 // Is there installation phase?
359 if (isInstallationPhase()) {
361 * In installation phase, we don't want SQL errors abort e.g. connection
362 * tests, so just log it away.
364 logDebugMessage($file, $line, $message);
366 // Regular mode, then call reportBug()
367 reportBug($file, $line, $message);