Some more improvements:
[mailer.git] / inc / db / lib-mysql3.php
index d7a7fd3872ea7f8138fb851a8c0be9aace892320..fd86300e36f564c9617c005197002a3a793df0bd 100644 (file)
@@ -16,7 +16,7 @@
  * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
+ * Copyright (c) 2009 - 2013 by Mailer Developer Team                   *
  * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -41,7 +41,7 @@ if (!defined('__SECURITY')) {
 } // END - if
 
 // SQL queries
-function SQL_QUERY ($sqlString, $F, $L, $enableCodes = TRUE) {
+function sqlQuery ($sqlString, $file, $line, $enableCodes = TRUE) {
        // Is there cache?
        if (!isset($GLOBALS[__FUNCTION__][$sqlString])) {
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Called: ' . $sqlString);
@@ -52,16 +52,16 @@ function SQL_QUERY ($sqlString, $F, $L, $enableCodes = TRUE) {
                // Empty query string or link is not up?
                if (empty($sqlStringModified)) {
                        // Empty SQL string!
-                       reportBug(__FUNCTION__, __LINE__, sprintf("SQL string is empty, please fix this: file=%s, line=%s",
-                               basename($F),
-                               $L
+                       reportBug(__FUNCTION__, __LINE__, sprintf('SQL string is empty, please fix this: file=%s, line=%s',
+                               basename($file),
+                               $line
                        ));
-               } elseif (!SQL_IS_LINK_UP()) {
+               } elseif (!isSqlLinkUp()) {
                        // We should not quietly ignore this
-                       reportBug(__FUNCTION__, __LINE__, sprintf("Cannot query database: sqlString=%s,file=%s,line=%s",
+                       reportBug(__FUNCTION__, __LINE__, sprintf('Cannot query database: sqlString=%s,file=%s,line=%s',
                                $sqlStringModified,
-                               basename($F),
-                               $L
+                               basename($file),
+                               $line
                        ));
                }
 
@@ -69,15 +69,15 @@ function SQL_QUERY ($sqlString, $F, $L, $enableCodes = TRUE) {
                $sqlStringModified = str_replace(array(chr(9), PHP_EOL, chr(13)), array(' ', ' ', ' '), $sqlStringModified);
 
                // Compile config entries out
-               $sqlStringModified = SQL_PREPARE_SQL_STRING($sqlStringModified, $enableCodes);
+               $sqlStringModified = sqlPrepareQueryString($sqlStringModified, $enableCodes);
 
                // Cache it and remember as last SQL query
                $GLOBALS[__FUNCTION__][$sqlString] = $sqlStringModified;
                $GLOBALS['last_sql']               = $sqlStringModified;
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Stored cache: ' . $sqlStringModified);
-       } elseif (!SQL_IS_LINK_UP()) {
+       } elseif (!isSqlLinkUp()) {
                // Link went down while using cached SQL
-               reportBug(__FUNCTION__, __LINE__, 'Link went down while using cached SQL: sqlString=' . $sqlString . ',F=' . basename($F) . ',L=' . $L . ',enableCodes=' . intval($enableCodes));
+               reportBug(__FUNCTION__, __LINE__, 'Link went down while using cached SQL: sqlString=' . $sqlString . ',file=' . basename($file) . ',line=' . $line . ',enableCodes=' . intval($enableCodes));
        } else {
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cache used: ' . $sqlString);
 
@@ -91,16 +91,16 @@ function SQL_QUERY ($sqlString, $F, $L, $enableCodes = TRUE) {
        $querytimeBefore = microtime(TRUE);
 
        // Run SQL command
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'F=' . basename($F) . ',L=' . $L . ',sql=' . $GLOBALS['last_sql']);
-       $result = mysql_query($GLOBALS['last_sql'], SQL_GET_LINK())
-               or SQL_ERROR($F, $L, 'file='. basename($F) . ',line=' . $L . ':mysql_error()=' . mysql_error() . ',last_query=' . $GLOBALS['last_sql']);
-       //* DEBUG: */ logDebugMessage($F, $L, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . SQL_AFFECTEDROWS() . ',numRows='.(is_resource($result) ? SQL_NUMROWS($result) : gettype($result)));
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($file) . ',line=' . $line . ',sql=' . $GLOBALS['last_sql']);
+       $result = mysql_query($GLOBALS['last_sql'], getSqlLink())
+               or sqlError($file, $line, 'file='. basename($file) . ',line=' . $line . ':mysql_error()=' . mysql_error() . ',last_query=' . $GLOBALS['last_sql']);
+       //* DEBUG: */ logDebugMessage($file, $line, 'sql=' . $GLOBALS['last_sql'] . ',affected=' . sqlAffectedRows() . ',numRows='.(isValidSqlLink($result) ? sqlNumRows($result) : gettype($result)));
 
        // Calculate query time
        $queryTime = microtime(TRUE) - $querytimeBefore;
 
        // Add this query to array including timing
-       addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $F, $L);
+       addSqlToDebug($result, $GLOBALS['last_sql'], $queryTime, $file, $line);
 
        // Save last successfull query
        setConfigEntry('db_last_query', $GLOBALS['last_sql']);
@@ -112,7 +112,7 @@ function SQL_QUERY ($sqlString, $F, $L, $enableCodes = TRUE) {
        incrementConfigEntry('sql_count');
 
        // Debug output
-       if (SQL_DEBUG_ENABLED()) {
+       if (isSqlDebugEnabled()) {
                // Is this the first call?
                if (!isset($GLOBALS['sql_first_entry'])) {
                        // Write first entry
@@ -121,7 +121,7 @@ function SQL_QUERY ($sqlString, $F, $L, $enableCodes = TRUE) {
                } // END - if
 
                // Append debug line
-               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']));
+               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']));
        } // END - if
 
        // Increment stats entry
@@ -132,9 +132,9 @@ function SQL_QUERY ($sqlString, $F, $L, $enableCodes = TRUE) {
 }
 
 // SQL num rows
-function SQL_NUMROWS ($resource) {
+function sqlNumRows ($resource) {
        // Valid link resource?
-       if (!SQL_IS_LINK_UP()) return FALSE;
+       if (!isSqlLinkUp()) return FALSE;
 
        // Link is not up, no rows by default
        $lines = FALSE;
@@ -143,7 +143,7 @@ function SQL_NUMROWS ($resource) {
        if (isset($GLOBALS['sql_numrows'][intval($resource)])) {
                // Use cache
                $lines = $GLOBALS['sql_numrows'][intval($resource)];
-       } elseif (is_resource($resource)) {
+       } elseif (isValidSqlLink($resource)) {
                // Get the count of rows from database
                $lines = mysql_num_rows($resource);
 
@@ -159,30 +159,30 @@ function SQL_NUMROWS ($resource) {
 }
 
 // SQL affected rows
-function SQL_AFFECTEDROWS() {
+function sqlAffectedRows () {
        // Valid link resource?
-       if (!SQL_IS_LINK_UP()) return FALSE;
+       if (!isSqlLinkUp()) return FALSE;
 
        // Get affected rows
-       $lines = mysql_affected_rows(SQL_GET_LINK());
+       $lines = mysql_affected_rows(getSqlLink());
 
        // Return it
        return $lines;
 }
 
 // SQL fetch row
-function SQL_FETCHROW ($resource) {
+function sqlFetchRow ($resource) {
        // Is $resource valid?
-       if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
+       if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
 
        // Fetch the data and return it
        return mysql_fetch_row($resource);
 }
 
 // SQL fetch array
-function SQL_FETCHARRAY ($resource) {
+function sqlFetchArray ($resource) {
        // Is $resource valid?
-       if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
+       if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
 
        // Load row as array from database
        $row = mysql_fetch_assoc($resource);
@@ -198,9 +198,9 @@ function SQL_FETCHARRAY ($resource) {
 }
 
 // SQL result
-function SQL_RESULT ($resource, $row, $field = '0') {
+function sqlResult ($resource, $row, $field = '0') {
        // Is $resource valid?
-       if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) return FALSE;
+       if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) return FALSE;
 
        // Run the result command
        $result = mysql_result($resource, $row, $field);
@@ -210,59 +210,70 @@ function SQL_RESULT ($resource, $row, $field = '0') {
 }
 
 // SQL connect
-function SQL_CONNECT ($host, $login, $password, $F, $L) {
+function sqlConnectToDatabase ($host, $login, $password, $file, $line) {
        // Try to connect
-       $linkResource = mysql_connect($host, $login, $password) or SQL_ERROR($F, $L,  mysql_error());
+       $linkResource = mysql_connect($host, $login, $password) or sqlError($file, $line,  mysql_error());
 
        // Set the link resource
-       if (is_resource($linkResource)) {
+       if (isValidSqlLink($linkResource)) {
                /*
                 * A non-resource (boolean) may happen on installation phase which
                 * shall not be set here. Only valid link resources shall be set so
-                * SQL_IS_LINK_UP() will only return 'true' if there is really a
+                * isSqlLinkUp() will only return 'true' if there is really a
                 * working database link.
                 */
-               SQL_SET_LINK(__FUNCTION__, __LINE__, $linkResource);
+               setSqlLink($file . ':' . __FUNCTION__, $line . ':' . __LINE__, $linkResource);
+
+               // Init charsets (UTF-8 is default now)
+               sqlQuery("SET
+       `character_set_results`='utf8',
+       `character_set_client`='utf8',
+       `character_set_connection`='utf8',
+       `character_set_database`='utf8',
+       `character_set_server`='utf8'", $file . ':' . __FUNCTION__, $line . ':' . __LINE__);
+
+               // Disallow subtraction for unsigned columns
+               sqlQuery("SET `sql_mode`='NO_UNSIGNED_SUBTRACTION'", $file . ':' . __FUNCTION__, $line . ':' . __LINE__);
        } // END - if
 
        // Return the resource
-       //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
+       //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'linkResource[]=' . gettype($linkResource));
        return $linkResource;
 }
 
 // SQL select database
-function SQL_SELECT_DB ($dbName, $F, $L) {
+function sqlSelectDatabase ($dbName, $file, $line) {
        // Is there still a valid link? If not, skip it.
-       if (!SQL_IS_LINK_UP()) return FALSE;
+       if (!isSqlLinkUp()) return FALSE;
 
        // Return the result
-       //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'Selecting database ' . $dbName);
-       return mysql_select_db($dbName, SQL_GET_LINK()) or SQL_ERROR($F, $L,  mysql_error());
+       //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Selecting database ' . $dbName);
+       return mysql_select_db($dbName, getSqlLink()) or sqlError($file, $line,  mysql_error());
 }
 
 // SQL close link
-function SQL_CLOSE ($F, $L) {
+function sqlCloseLink ($file, $line) {
        // Is the link up?
-       if (!SQL_IS_LINK_UP()) {
+       if (!isSqlLinkUp()) {
                // Skip double close
-               //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'Called but no link is open.');
+               //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'Called but no link is open.');
                return FALSE;
        } // END - if
 
        // Close database link and forget the link
-       $close = mysql_close(SQL_GET_LINK()) or SQL_ERROR($F . ':' . __FUNCTION__, $L . ':' . __LINE__, mysql_error());
+       $close = mysql_close(getSqlLink()) or sqlError($file . ':' . __FUNCTION__, $line . ':' . __LINE__, mysql_error());
 
        // Close link in this layer
        unsetSqlLinkUp(__FUNCTION__, __LINE__);
 
        // Return the result
-       //* DEBUG: */ logDebugMessage($F . ':' . __FUNCTION__, $L . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
+       //* DEBUG: */ logDebugMessage($file . ':' . __FUNCTION__, $line . ':' . __LINE__, 'close[' . gettype($close) . ']=' . intval($close));
        return $close;
 }
 
 // SQL free result
-function SQL_FREERESULT ($resource) {
-       if ((!is_resource($resource)) || (!SQL_IS_LINK_UP())) {
+function sqlFreeResult ($resource) {
+       if ((!isValidSqlLink($resource)) || (!isSqlLinkUp())) {
                // Abort here
                return FALSE;
        } // END - if
@@ -274,21 +285,21 @@ function SQL_FREERESULT ($resource) {
        return $res;
 }
 
-// Get id from last INSERT command
-function SQL_INSERTID () {
-       if (!SQL_IS_LINK_UP()) return FALSE;
-       return mysql_insert_id();
+// Get id from last INSERT command and secure id
+function getSqlInsertId () {
+       if (!isSqlLinkUp()) return FALSE;
+       return bigintval(mysql_insert_id());
 }
 
 // Escape a string for the database
-function SQL_ESCAPE ($str, $secureString = TRUE, $strip = TRUE) {
+function sqlEscapeString ($str, $secureString = TRUE, $strip = TRUE) {
        // Is there cache?
        if (!isset($GLOBALS['sql_escapes']['' . $str . ''])) {
                // Debug message
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - BEFORE!');
 
                // Prepare the string here
-               $str = SQL_PREPARE_SQL_STRING($str);
+               $str = sqlPrepareQueryString($str);
 
                // Debug message
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ' - AFTER!');
@@ -308,7 +319,7 @@ function SQL_ESCAPE ($str, $secureString = TRUE, $strip = TRUE) {
                // Init (invalid) value
                $ret = '!INVALID!';
 
-               if (!SQL_IS_LINK_UP()) {
+               if (!isSqlLinkUp()) {
                        // Fall-back to escapeQuotes() when there is no link
                        $ret = escapeQuotes($str);
                } elseif (function_exists('mysql_real_escape_string')) {
@@ -316,13 +327,13 @@ function SQL_ESCAPE ($str, $secureString = TRUE, $strip = TRUE) {
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
 
                        // The new and improved version
-                       $ret = mysql_real_escape_string($str, SQL_GET_LINK());
+                       $ret = mysql_real_escape_string($str, getSqlLink());
 
                        // Debug message
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str . ',ret=' . $ret);
                } elseif (function_exists('mysql_escape_string')) {
                        // The obsolete function
-                       $ret = mysql_escape_string($str, SQL_GET_LINK());
+                       $ret = mysql_escape_string($str, getSqlLink());
                } else {
                        // If nothing else works, fall back to escapeQuotes() again
                        $ret = escapeQuotes($str);
@@ -343,12 +354,30 @@ function SQL_ESCAPE ($str, $secureString = TRUE, $strip = TRUE) {
 }
 
 // Log SQL errors to debug.log in installation phase or call reportBug()
-function SQL_ERROR ($file, $line, $message) {
+function sqlError ($file, $line, $message) {
        // Remember plain error in last_sql_error
        $GLOBALS['last_sql_error'] = mysql_error();
 
+       // Is login set?
+       if (!empty($GLOBALS['mysql']['login'])) {
+               // Secure login name in message
+               $message = str_replace($GLOBALS['mysql']['login'], '***', $message);
+       } // END - if
+
+       // Is database password set?
+       if (!empty($GLOBALS['mysql']['password'])) {
+               // Secure password in message
+               $message = str_replace($GLOBALS['mysql']['password'], '***', $message);
+       } // END - if
+
+       // Is database name set?
+       if (!empty($GLOBALS['mysql']['dbase'])) {
+               // Secure database name in message
+               $message = str_replace($GLOBALS['mysql']['dbase'], '***', $message);
+       } // END - if
+
        // Is there installation phase?
-       if (isInstallationPhase()) {
+       if (isInstaller()) {
                /*
                 * In installation phase, we don't want SQL errors abort e.g. connection
                 * tests, so just log it away.
@@ -360,5 +389,11 @@ function SQL_ERROR ($file, $line, $message) {
        }
 }
 
+// Checks whether given link is a valid SQL link
+function isValidSqlLink ($linkResource) {
+       // Is it a resource?
+       return is_resource($linkResource);
+}
+
 // [EOF]
 ?>