Failed SQL queries are now also reported in bug mails, SQL queries improved (more...
[mailer.git] / inc / db / lib-mysql3.php
index 465e0d5b2c790c602bbf58be38eab47c5244cdc9..02e1722fe25d3d1b08db80b59f99d2429e2c38b6 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /************************************************************************
- * MXChange v0.2.1                                    Start: 08/29/2004 *
- * ===============                              Last change: 08/29/2004 *
+ * Mailer v0.2.1-FINAL                                Start: 08/29/2004 *
+ * ===================                          Last change: 08/29/2004 *
  *                                                                      *
  * -------------------------------------------------------------------- *
  * File              : lib-mysql3.php                                   *
@@ -18,6 +18,7 @@
  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
+ * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
  * For more information visit: http://www.mxchange.org                  *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -71,25 +72,25 @@ function SQL_QUERY ($sqlString, $F, $L) {
        // Remove \t, \n and \r from queries they may confuse some MySQL version I have heard
        $sqlString = str_replace("\t", ' ', str_replace("\n", ' ', str_replace("\r", ' ', $sqlString)));
 
-       // Compile config out
-       $sqlString = FILTER_COMPILE_CONFIG($sqlString);
+       // Replace {PER}
+       $sqlString = str_replace('{PER}', '%', $sqlString);
+
+       // Compile config entries out
+       $eval = "\$sqlString = \"".FILTER_COMPILE_CONFIG(escapeQuotes($sqlString))."\";";
+       eval($eval);
 
        // Starting time
-       $querytimeBefore = array_sum(explode(' ', microtime()));
+       $querytimeBefore = microtime(true);
 
        // Run SQL command
-       //* DEBUG: */ print($sqlString . '<br />');
+       //* DEBUG: */ print('F=' . basename($F) . ',L=' . $L . 'sql=' . htmlentities($sqlString) . '<br />');
        $result = mysql_query($sqlString, SQL_GET_LINK())
-               or addFatalMessage(__FUNCTION__, __LINE__, $F . ' (' . $L . '):' . mysql_error() . '<br />
-Query string:<br />
-' . $sqlString);
-       //* DEBUG: */ print(__LINE__ . ': numRows=' . SQL_NUMROWS($result) . ',affected=' . SQL_AFFECTEDROWS() . "<br />");
-
-       // Ending time
-       $querytimeAfter = array_sum(explode(' ', microtime()));
+               or debug_report_bug('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . $F . ' (' . $L . '):' . mysql_error() . "\n".
+'Query string:' . $sqlString);
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sql=' . $sqlString . ',numRows=' . SQL_NUMROWS($result) . ',affected=' . SQL_AFFECTEDROWS());
 
        // Calculate query time
-       $queryTime = $querytimeAfter - $querytimeBefore;
+       $queryTime = microtime(true) - $querytimeBefore;
 
        // Add this query to array including timing
        addSqlToDebug($result, $sqlString, $queryTime, $F, $L);
@@ -104,11 +105,11 @@ Query string:<br />
        incrementConfigEntry('sql_count');
 
        // Debug output
-       if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y')) {
+       if ((getOutputMode() != 1) && (isDebugModeEnabled()) && (isSqlDebuggingEnabled())) {
                //
                // Debugging stuff...
                //
-               $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write mysql.log!");
+               $fp = fopen(getConfig('CACHE_PATH') . 'mysql.log', 'a') or app_die(__FILE__, __LINE__, 'Cannot write mysql.log!');
                if (!isset($GLOBALS['sql_first_entry'])) {
                        // Write first entry
                        fwrite($fp, 'Module=' . getModule() . "\n");
@@ -119,12 +120,12 @@ Query string:<br />
        } // END - if
 
        // Count DB hits
-       if (!isStatsEntrySet('db_hits_run')) {
+       if (!isStatsEntrySet('db_hits')) {
                // Count in dummy variable
-               setStatsEntry('db_hits_run', 1);
+               setStatsEntry('db_hits', 1);
        } else {
                // Count to config array
-               incrementStatsEntry('db_hits_run');
+               incrementStatsEntry('db_hits');
        }
 
        // Return the result
@@ -133,6 +134,9 @@ Query string:<br />
 
 // SQL num rows
 function SQL_NUMROWS ($result) {
+       // Valid link resource?
+       if (!SQL_IS_LINK_UP()) return false;
+
        // Link is not up, no rows by default
        $lines = false;
 
@@ -142,10 +146,10 @@ function SQL_NUMROWS ($result) {
                $lines = mysql_num_rows($result);
 
                // Is the result empty? Then we have an error!
-               if (empty($lines)) $lines = 0;
-       } elseif (SQL_IS_LINK_UP()) {
-               // No resource given, no lines found!
-               $lines = 0;
+               if (empty($lines)) $lines = '0';
+       } else {
+               // No resource given, please fix this
+               trigger_error('No resource given! result[]=' . gettype($result));
        }
 
        // Return lines
@@ -190,7 +194,7 @@ function SQL_FETCHARRAY ($res, $nr=0, $remove_numerical=true) {
                if ($remove_numerical) {
                        // So let's remove all numerical elements to save memory!
                        $max = count($row);
-                       for ($idx = 0; $idx < ($max / 2); $idx++) {
+                       for ($idx = '0'; $idx < ($max / 2); $idx++) {
                                // Remove entry
                                unset($row[$idx]);
                        } // END - for
@@ -199,13 +203,13 @@ function SQL_FETCHARRAY ($res, $nr=0, $remove_numerical=true) {
                // Return row
                return $row;
        } else {
-               // Return a false here...
+               // Return a false, else some loops would go endless...
                return false;
        }
 }
 
 // SQL result
-function SQL_RESULT ($res, $row, $field = 0) {
+function SQL_RESULT ($res, $row, $field = '0') {
        // Is $res valid?
        if ((!is_resource($res)) || (!SQL_IS_LINK_UP())) return false;
 
@@ -223,7 +227,7 @@ function SQL_CONNECT ($host, $login, $password, $F, $L) {
        SQL_SET_LINK($connect);
 
        // Destroy cache
-       unset($GLOBALS['sql_link_res']);
+       unset($GLOBALS['is_sql_link_up']);
 }
 
 // SQL select database
@@ -250,10 +254,7 @@ function SQL_CLOSE ($F, $L) {
        SQL_SET_LINK(null);
 
        // Destroy cache
-       unset($GLOBALS['sql_link_res']);
-
-       // Move stats
-       incrementStatsEntry('db_hits', getStatsEntry('db_hits_run'));
+       unset($GLOBALS['is_sql_link_up']);
 
        // Return the result
        return $close;
@@ -275,7 +276,6 @@ function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure
        // Link is there?
        if ((!SQL_IS_LINK_UP()) || (!is_array($data))) return false;
 
-       /* Other way */
        // Escape all data
        $dataSecured['__sql_string'] = $qstring;
        foreach ($data as $key => $value) {
@@ -284,51 +284,13 @@ function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure
 
        // Generate query
        $query = call_user_func_array('sprintf', $dataSecured);
-       /*
-       /* Old eval() way... *
-       // Init variable
-       $query = 'failed';
-
-       if ($strip === true) {
-               $strip = 'true';
-       } else {
-               $strip = 'false';
-       }
-
-       if ($secure === true) {
-               $secure = 'true';
-       } else {
-               $secure = 'false';
-       }
-
-       $eval = "\$query = sprintf(\"" . $qstring . "\"";
-       foreach ($data as $var) {
-               if ((!empty($var)) || ($var === 0)) {
-                       $eval .= ", SQL_ESCAPE('" . $var . "', " . $secure . ', ' . $strip . ')';
-               } else {
-                       $eval .= ", ''";
-               }
-       } // END - foreach
-       $eval .= ');';
-       **/
 
        // Debugging
        //
        //* DEBUG: */ $fp = fopen(getConfig('CACHE_PATH') . 'escape_debug.log', 'a') or app_die(__FILE__, __LINE__, "Cannot write debug.log!");
-       //* DEBUG: */ fwrite($fp, $F.'('.$L."): ".str_replace("\r", '', str_replace("\n", " ", $eval))."\n");
+       //* DEBUG: */ fwrite($fp, $F.'('.$L."): ".str_replace("\r", '', str_replace("\n", ' ', $eval))."\n");
        //* DEBUG: */ fclose($fp);
 
-       // Run the code
-       /**
-       eval($eval);
-
-       // Was the eval() command fine?
-       if ($query == 'failed') {
-               // Something went wrong?
-               debug_report_bug('eval=' . $eval);
-       } // END - if
-       **/
-
        if ($run === true) {
                // Run SQL query (default)
                return SQL_QUERY($query, $F, $L);
@@ -338,7 +300,7 @@ function SQL_QUERY_ESC ($qstring, $data, $F, $L, $run=true, $strip=true, $secure
        }
 }
 
-// Get ID from last INSERT command
+// Get id from last INSERT command
 function SQL_INSERTID () {
        if (!SQL_IS_LINK_UP()) return false;
        return mysql_insert_id();
@@ -347,37 +309,34 @@ function SQL_INSERTID () {
 // Escape a string for the database
 function SQL_ESCAPE ($str, $secureString=true, $strip=true) {
        // Do we have cache?
-       if (isset($GLOBALS['sql_escapes'][$str])) {
-               // Then use it instead
-               return $GLOBALS['sql_escapes'][$str];
-       } // END - if
-
-       // Secure string first? (which is the default behaviour!)
-       if ($secureString === true) {
-               // Then do it here
-               $str = secureString($str, $strip);
-       } // END - if
+       if (!isset($GLOBALS['sql_escapes'][''.$str.''])) {
+               // Secure string first? (which is the default behaviour!)
+               if ($secureString === true) {
+                       // Then do it here
+                       $str = secureString($str, $strip);
+               } // END - if
 
-       if (!SQL_IS_LINK_UP()) {
-               // Fall-back to smartAddSlashes() when there is no link
-               $ret = smartAddSlashes($str);
-       } elseif (function_exists('mysql_real_escape_string')) {
-               // The new and improved version
-               //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):str={$str}<br />");
-               $ret = mysql_real_escape_string($str, SQL_GET_LINK());
-       } elseif (function_exists('mysql_escape_string')) {
-               // The obsolete function
-               $ret = mysql_escape_string($str, SQL_GET_LINK());
-       } else {
-               // If nothing else works, fall back to smartAddSlashes() again
-               $ret = smartAddSlashes($str);
-       }
+               if (!SQL_IS_LINK_UP()) {
+                       // Fall-back to escapeQuotes() when there is no link
+                       $ret = escapeQuotes($str);
+               } elseif (function_exists('mysql_real_escape_string')) {
+                       // The new and improved version
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str='.$str);
+                       $ret = mysql_real_escape_string($str, SQL_GET_LINK());
+               } elseif (function_exists('mysql_escape_string')) {
+                       // The obsolete function
+                       $ret = mysql_escape_string($str, SQL_GET_LINK());
+               } else {
+                       // If nothing else works, fall back to escapeQuotes() again
+                       $ret = escapeQuotes($str);
+               }
 
-       // Cache result
-       $GLOBALS['sql_escapes'][$str] = $ret;
+               // Cache result
+               $GLOBALS['sql_escapes'][''.$str.''] = $ret;
+       } // END - if
 
        // Return it
-       return $ret;
+       return $GLOBALS['sql_escapes'][''.$str.''];
 }
 
 // SELECT query string from table, columns and so on... ;-)
@@ -420,6 +379,8 @@ function SQL_ALTER_TABLE ($sql, $F, $L) {
        $noIndex = (
        (
                strpos($sql, 'INDEX') === false
+       ) && (
+               strpos($sql, 'KEY') === false
        ) && (
                strpos($sql, 'FULLTEXT') === false
        ) && (
@@ -428,44 +389,58 @@ function SQL_ALTER_TABLE ($sql, $F, $L) {
        );
 
        // Extract table name
-       $tableArray = explode(" ", $sql);
+       $tableArray = explode(' ', $sql);
        $tableName = str_replace('`', '', $tableArray[2]);
 
        // Shall we add/drop?
        if (((strpos($sql, 'ADD') !== false) || (strpos($sql, 'DROP') !== false)) && ($noIndex === true)) {
-               // And column name as well
-               $columnName = str_replace('`', '', $tableArray[4]);
-
-               // Get column information
-               $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
-                       array($tableName, $columnName), __FILE__, __LINE__);
-
-               // Do we have no entry on ADD or an entry on DROP?
-               // 123           4       4     3    3      4           4          32    23           4       4     3    3      4            4          321
-               if (((SQL_NUMROWS($result) == 0) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
-                       // Do the query
-                       //* DEBUG: */ print(__LINE__.':'.$sql."<br />");
-                       $result = SQL_QUERY($sql, $F, $L, false);
-               } // END - if
+               // Try two columns, one should fix
+               foreach (array(4,5) as $idx) {
+                       // And column name as well
+                       $columnName = str_replace('`', '', $tableArray[$idx]);
+
+                       // Get column information
+                       $result = SQL_QUERY_ESC("SHOW COLUMNS FROM `%s` LIKE '%s'",
+                               array($tableName, $columnName), __FILE__, __LINE__);
+
+                       // Do we have no entry on ADD or an entry on DROP?
+                       // 123           4       4     3    3      4           4          32    23           4       4     3    3      4            4          321
+                       if (((SQL_HASZERONUMS($result)) && (strpos($sql, 'ADD') !== false)) || ((SQL_NUMROWS($result) == 1) && (strpos($sql, 'DROP') !== false))) {
+                               // Do the query
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Executing: ' . $sql);
+                               $result = SQL_QUERY($sql, $F, $L, false);
+
+                               // Skip further attempt(s)
+                               break;
+                       } elseif ((((SQL_NUMROWS($result) == 1) && (strpos($sql, 'ADD') !== false)) || ((SQL_HASZERONUMS($result)) && (strpos($sql, 'DROP') !== false))) && ($columnName != 'KEY')) {
+                               // Abort here because it is alreay there
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $sql);
+                               break;
+                       } elseif ($columnName != 'KEY') {
+                               // Something didn't fit
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Possible problem: ' . $sql);
+                       }
+               } // END - foreach
        } elseif ((getConfig('_TABLE_TYPE') == 'InnoDB') && (strpos($sql, 'FULLTEXT') !== false)) {
                // Skip this query silently
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skipped FULLTEXT: sql=%s,file=%s,line=%s", $sql, $F, $L));
        } elseif ($noIndex === false) {
                // And column name as well
-               $columnName = str_replace('`', '', $tableArray[4]);
+               //* DEBUG: */ print __LINE__.':tableArray=<pre>' . print_r($tableArray, true) . '</pre>';
+               $keyName = str_replace('`', '', $tableArray[5]);
 
                // Is this "UNIQUE" or so? FULLTEXT has been handled the elseif() block above
-               if (in_array(strtoupper($columnName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
+               if (in_array(strtoupper($keyName), array('INDEX', 'UNIQUE', 'KEY', 'FULLTEXT'))) {
                        // Init loop
-                       $begin = 1; $columnName = ',';
-                       while (strpos($columnName, ',') !== false) {
+                       $begin = 1; $keyName = ',';
+                       while (strpos($keyName, ',') !== false) {
                                // Use last
-                               $columnName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
-                               //* DEBUG: */ print(__LINE__.':'.$columnName."----------------".$begin."<br />");
+                               $keyName = str_replace('`', '', $tableArray[count($tableArray) - $begin]);
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
 
                                // Remove brackes
-                               $columnName = str_replace('(', '', str_replace(')', '', $columnName));
-                               //* DEBUG: */ print(__LINE__.':'.$columnName."----------------".$begin."<br />");
+                               $keyName = str_replace('(', '', str_replace(')', '', $keyName));
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $keyName . '----------------' . $begin);
 
                                // Continue
                                $begin++;
@@ -473,20 +448,33 @@ function SQL_ALTER_TABLE ($sql, $F, $L) {
                } // END - if
 
                // Show indexes
-               $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`",
-                       array($tableName), __FILE__, __LINE__);
+               $result = SQL_QUERY_ESC("SHOW INDEX FROM `%s`", array($tableName), __FILE__, __LINE__);
 
-               // Walk through all
+               // Non-skipping is default for ADD
                $skip = false;
+
+               // But should we DROP?
+               if ($tableArray[3] == 'DROP') {
+                       // Then skip if nothing found!
+                       $skip = true;
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Going to drop key ' . $keyName);
+               } // END - if
+
+               // Walk through all
                while ($content = SQL_FETCHARRAY($result)) {
                        // Is it found?
-                       //* DEBUG: */ print("<pre>".print_r($content, true)."</pre>");
-                       if (($content['Column_name'] == $columnName) || ($content['Key_name'] == $columnName)) {
+                       //* DEBUG: */ print(__LINE__.':columnName='.$keyName.',content=<pre>' . print_r($content, true) . '</pre>');
+                       if (($content['Key_name'] == $keyName) && ($tableArray[3] == 'ADD')) {
                                // Skip this query!
-                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Skiped: %s", $sql));
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ADD: Skiped: %s", $sql));
                                $skip = true;
                                break;
-                       } // END - if
+                       } elseif (($content['Key_name'] == $keyName) && ($tableArray[3] == 'DROP')) {
+                               // Don't skip this!
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("DROP: Not skiped: %s", $sql));
+                               $skip = false;
+                               break;
+                       }
                } // END - while
 
                // Free result
@@ -495,12 +483,15 @@ function SQL_ALTER_TABLE ($sql, $F, $L) {
                // Shall we run it?
                if ($skip === false) {
                        // Send it to the SQL_QUERY() function
-                       //* DEBUG: */ print(__LINE__.':'.$sql."<br />");
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
                        $result = SQL_QUERY($sql, $F, $L, false);
-               } // END - if
+               } else {
+                       // Not executed
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not executed: ' . $sql);
+               }
        } else {
                // Other ALTER TABLE query
-               //* DEBUG: */ print(__LINE__.':'.$sql."<br />");
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $sql);
                $result = SQL_QUERY($sql, $F, $L, false);
        }
 
@@ -541,20 +532,26 @@ function SQL_IS_LINK_UP () {
        $linkUp = false;
 
        // Do we have cached this?
-       if (isset($GLOBALS['sql_link_res'])) {
+       if (isset($GLOBALS['is_sql_link_up'])) {
                // Then use this
-               $linkUp = $GLOBALS['sql_link_res'];
+               $linkUp = $GLOBALS['is_sql_link_up'];
        } else {
                // Get it
                $linkUp = is_resource(SQL_GET_LINK());
 
                // And cache it
-               $GLOBALS['sql_link_res'] = $linkUp;
+               $GLOBALS['is_sql_link_up'] = $linkUp;
        }
 
        // Return the result
        return $linkUp;
 }
 
+// Wrapper function to make code more readable
+function SQL_HASZERONUMS ($result) {
+       // Just pass it through
+       return (SQL_NUMROWS($result) === 0);
+}
+
 // [EOF]
 ?>