Fixed bug #11599: TYPO3 dies without an error message when the mysql-module for php...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_db.php
old mode 100755 (executable)
new mode 100644 (file)
index ed80914..e64e38d
@@ -2,7 +2,7 @@
 /***************************************************************
 *  Copyright notice
 *
-*  (c) 2004-2006 Kasper Skaarhoj (kasperYYYY@typo3.com)
+*  (c) 2004-2009 Kasper Skaarhoj (kasperYYYY@typo3.com)
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
@@ -25,7 +25,9 @@
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
 /**
- * Contains the class "t3lib_db" containing functions for building SQL queries and mysql wrappers, thus providing a foundational API to all database interaction.
+ * Contains the class "t3lib_db" containing functions for building SQL queries
+ * and mysql wrappers, thus providing a foundational API to all database
+ * interaction.
  * This class is instantiated globally as $TYPO3_DB in TYPO3 scripts.
  *
  * $Id$
@@ -142,10 +144,14 @@ class t3lib_DB {
        var $debugOutput = FALSE;               // Set "TRUE" if you want database errors outputted.
        var $debug_lastBuiltQuery = '';         // Internally: Set to last built query (not necessarily executed...)
        var $store_lastBuiltQuery = FALSE;      // Set "TRUE" if you want the last built query to be stored in $debug_lastBuiltQuery independent of $this->debugOutput
+       var $explainOutput = 0;                 // Set this to 1 to get queries explained (devIPmask must match). Set the value to 2 to the same but disregarding the devIPmask. There is an alternative option to enable explain output in the admin panel under "TypoScript", which will produce much nicer output, but only works in FE.
 
                // Default link identifier:
        var $link = FALSE;
 
+               // Default character set, applies unless character set or collation are explicitely set
+       var $default_charset = 'utf8';
+
 
 
 
@@ -223,8 +229,16 @@ class t3lib_DB {
         * @return      pointer         MySQL result pointer / DBAL object
         */
        function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')   {
-               $res = mysql_query($this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit), $this->link);
-               if ($this->debugOutput) $this->debug('exec_SELECTquery');
+               $query = $this->SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit);
+               $res = mysql_query($query, $this->link);
+
+               if ($this->debugOutput) {
+                       $this->debug('exec_SELECTquery');
+               }
+               if ($this->explainOutput) {
+                       $this->explain($query, $from_table, $this->sql_num_rows($res));
+               }
+
                return $res;
        }
 
@@ -256,7 +270,7 @@ class t3lib_DB {
                $mmWhere.= ($local_table AND $foreign_table) ? ' AND ' : '';
                $mmWhere.= $foreign_table ? ($foreign_table_as ? $foreign_table_as : $foreign_table).'.uid='.$mm_table.'.uid_foreign' : '';
 
-               return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+               return $this->exec_SELECTquery(
                                        $select,
                                        ($local_table ? $local_table.',' : '').$mm_table.($foreign_table ? ','. $foreign_table.($foreign_table_as ? ' AS '.$foreign_table_as : '') : ''),
                                        $mmWhere.' '.$whereClause,              // whereClauseMightContainGroupOrderBy
@@ -313,10 +327,29 @@ class t3lib_DB {
                                while($output[] = $this->sql_fetch_assoc($res));
                                array_pop($output);
                        }
+                       $this->sql_free_result($res);
                }
                return $output;
        }
 
+       /**
+        * Counts the number of rows in a table.
+        *
+        * @param       string          $field: Name of the field to use in the COUNT() expression (e.g. '*')
+        * @param       string          $table: Name of the table to count rows for
+        * @param       string          $where: (optional) WHERE statement of the query
+        * @return      mixed           Number of rows counter (integer) or false if something went wrong (boolean)
+        */
+       public function exec_SELECTcountRows($field, $table, $where = '') {
+               $count = false;
+               $resultSet = $this->exec_SELECTquery('COUNT(' . $field . ')', $table, $where);
+               if ($resultSet !== false) {
+                       list($count) = $this->sql_fetch_row($resultSet);
+                       $this->sql_free_result($resultSet);
+               }
+               return $count;
+       }
+
 
 
 
@@ -341,7 +374,6 @@ class t3lib_DB {
         * @param       array           See exec_INSERTquery()
         * @param       string/array            See fullQuoteArray()
         * @return      string          Full SQL query for INSERT (unless $fields_values does not contain any elements in which case it will be false)
-        * @deprecated                  use exec_INSERTquery() instead if possible!
         */
        function INSERTquery($table,$fields_values,$no_quote_fields=FALSE)      {
 
@@ -376,7 +408,6 @@ class t3lib_DB {
         * @param       array           See exec_UPDATEquery()
         * @param       array           See fullQuoteArray()
         * @return      string          Full SQL query for UPDATE (unless $fields_values does not contain any elements in which case it will be false)
-        * @deprecated                  use exec_UPDATEquery() instead if possible!
         */
        function UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)       {
 
@@ -417,7 +448,6 @@ class t3lib_DB {
         * @param       string          See exec_DELETEquery()
         * @param       string          See exec_DELETEquery()
         * @return      string          Full SQL query for DELETE
-        * @deprecated                  use exec_DELETEquery() instead if possible!
         */
        function DELETEquery($table,$where)     {
                if (is_string($where))  {
@@ -446,7 +476,6 @@ class t3lib_DB {
         * @param       string          See exec_SELECTquery()
         * @param       string          See exec_SELECTquery()
         * @return      string          Full SQL query for SELECT
-        * @deprecated                  use exec_SELECTquery() instead if possible!
         */
        function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')        {
 
@@ -490,8 +519,9 @@ class t3lib_DB {
         * @return      string          WHERE clause for a query
         */
        function listQuery($field, $value, $table)      {
-               $command = $this->quoteStr($value, $table);
-               $where = '('.$field.' LIKE \'%,'.$command.',%\' OR '.$field.' LIKE \''.$command.',%\' OR '.$field.' LIKE \'%,'.$command.'\' OR '.$field.'=\''.$command.'\')';
+               $pattern = $this->quoteStr($value, $table);
+               $patternForLike = $this->escapeStrForLike($pattern, $table);
+               $where = '('.$field.' LIKE \'%,'.$patternForLike.',%\' OR '.$field.' LIKE \''.$patternForLike.',%\' OR '.$field.' LIKE \'%,'.$patternForLike.'\' OR '.$field.'=\''.$pattern.'\')';
                return $where;
        }
 
@@ -550,11 +580,7 @@ class t3lib_DB {
         * @see quoteStr()
         */
        function fullQuoteStr($str, $table)     {
-               if (function_exists('mysql_real_escape_string'))        {
-                       return '\''.mysql_real_escape_string($str, $this->link).'\'';
-               } else {
-                       return '\''.mysql_escape_string($str).'\'';
-               }
+               return '\''.mysql_real_escape_string($str, $this->link).'\'';
        }
 
        /**
@@ -594,11 +620,7 @@ class t3lib_DB {
         * @see quoteStr()
         */
        function quoteStr($str, $table) {
-               if (function_exists('mysql_real_escape_string'))        {
-                       return mysql_real_escape_string($str, $this->link);
-               } else {
-                       return mysql_escape_string($str);
-               }
+               return mysql_real_escape_string($str, $this->link);
        }
 
        /**
@@ -739,16 +761,17 @@ class t3lib_DB {
        /**
         * Executes query
         * mysql() wrapper function
-        * DEPRECATED - use exec_* functions from this class instead!
-        * Usage count/core: 9
+        * Usage count/core: 0
         *
         * @param       string          Database name
         * @param       string          Query to execute
         * @return      pointer         Result pointer / DBAL object
+        * @deprecated since TYPO3 3.6
+        * @see sql_query()
         */
        function sql($db,$query)        {
                $res = mysql_query($query, $this->link);
-               if ($this->debugOutput) $this->debug('sql');
+               if ($this->debugOutput) $this->debug('sql',$query);
                return $res;
        }
 
@@ -762,7 +785,7 @@ class t3lib_DB {
         */
        function sql_query($query)      {
                $res = mysql_query($query, $this->link);
-               if ($this->debugOutput) $this->debug('sql_query');
+               if ($this->debugOutput) $this->debug('sql_query',$query);
                return $res;
        }
 
@@ -778,14 +801,25 @@ class t3lib_DB {
        }
 
        /**
+        * Returns the error number on the last sql() execution
+        * mysql_errno() wrapper function
+        *
+        * @return      int             MySQL error number.
+        */
+       function sql_errno() {
+               return mysql_errno($this->link);
+       }
+
+       /**
         * Returns the number of selected rows.
         * mysql_num_rows() wrapper function
         * Usage count/core: 85
         *
         * @param       pointer         MySQL result pointer (of SELECT query) / DBAL object
-        * @return      integer         Number of resulting rows.
+        * @return      integer         Number of resulting rows
         */
        function sql_num_rows($res)     {
+               $this->debug_check_recordset($res);
                return mysql_num_rows($res);
        }
 
@@ -798,6 +832,7 @@ class t3lib_DB {
         * @return      array           Associative array of result row.
         */
        function sql_fetch_assoc($res)  {
+               $this->debug_check_recordset($res);
                return mysql_fetch_assoc($res);
        }
 
@@ -811,6 +846,7 @@ class t3lib_DB {
         * @return      array           Array with result rows.
         */
        function sql_fetch_row($res)    {
+               $this->debug_check_recordset($res);
                return mysql_fetch_row($res);
        }
 
@@ -823,6 +859,7 @@ class t3lib_DB {
         * @return      boolean         Returns TRUE on success or FALSE on failure.
         */
        function sql_free_result($res)  {
+               $this->debug_check_recordset($res);
                return mysql_free_result($res);
        }
 
@@ -858,6 +895,7 @@ class t3lib_DB {
         * @return      boolean         Returns TRUE on success or FALSE on failure.
         */
        function sql_data_seek($res,$seek)      {
+               $this->debug_check_recordset($res);
                return mysql_data_seek($res,$seek);
        }
 
@@ -871,6 +909,7 @@ class t3lib_DB {
         * @return      string          Returns the name of the specified field index
         */
        function sql_field_type($res,$pointer)  {
+               $this->debug_check_recordset($res);
                return mysql_field_type($res,$pointer);
        }
 
@@ -885,22 +924,51 @@ class t3lib_DB {
         * @return      pointer         Returns a positive MySQL persistent link identifier on success, or FALSE on error.
         */
        function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password)   {
+                       // mysql_error() is tied to an established connection
+                       // if the connection fails we need a different method to get the error message
+               @ini_set('track_errors', 1);
+               @ini_set('html_errors', 0);
+
+                       // check if MySQL extension is loaded
+               if (!extension_loaded('mysql')) {
+                       t3lib_BEfunc::typo3PrintError('Database Error', 'You don\'t seem to have MySQL-support for PHP installed!');
+                       exit;
+               }
+
+                       // Check for client compression
+               $isLocalhost = ($TYPO3_db_host == 'localhost' || $TYPO3_db_host == '127.0.0.1');
                if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect'])  {
-                       $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
+                       if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
+                                       // We use PHP's default value for 4th parameter (new_link), which is false.
+                                       // See PHP sources, for example: file php-5.2.5/ext/mysql/php_mysql.c, function php_mysql_do_connect(), near line 525
+                               $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, false, MYSQL_CLIENT_COMPRESS);
+                       } else {
+                               $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
+                       }
                } else {
-                       $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
+                       if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
+                                       // See comment about 4th parameter in block above
+                               $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, false, MYSQL_CLIENT_COMPRESS);
+                       } else {
+                               $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
+                       }
                }
 
+               $error_msg = $php_errormsg;
+               @ini_restore('track_errors');
+               @ini_restore('html_errors');
+
                if (!$this->link) {
-                       t3lib_div::sysLog('Could not connect to Mysql server '.$TYPO3_db_host.' with user '.$TYPO3_db_username.'.','Core',4);
+                       t3lib_div::sysLog('Could not connect to MySQL server '.$TYPO3_db_host.' with user '.$TYPO3_db_username.': '.$error_msg,'Core',4);
                } else {
-                       $setDBinit = t3lib_div::trimExplode(chr(10), $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']);
+                       $setDBinit = t3lib_div::trimExplode(chr(10), $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'],TRUE);
                        foreach ($setDBinit as $v)      {
                                if (mysql_query($v, $this->link) === FALSE)     {
-                                       t3lib_div::sysLog('Could not initialize DB connection with query "'.$v.'".','Core',3);
+                                       t3lib_div::sysLog('Could not initialize DB connection with query "'.$v.'": '.mysql_error($this->link),'Core',3);
                                }
                        }
                }
+
                return $this->link;
        }
 
@@ -915,7 +983,7 @@ class t3lib_DB {
        function sql_select_db($TYPO3_db)       {
                $ret = @mysql_select_db($TYPO3_db, $this->link);
                if (!$ret) {
-                       t3lib_div::sysLog('Could not select Mysql database '.$TYPO3_db.': '.mysql_error(),'Core',4);
+                       t3lib_div::sysLog('Could not select MySQL database '.$TYPO3_db.': '.mysql_error(),'Core',4);
        }
                return $ret;
        }
@@ -960,16 +1028,20 @@ class t3lib_DB {
         * In a DBAL this method should 1) look up all tables from the DBMS  of the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
         * Usage count/core: 2
         *
-        * @return      array           Tables in an array (tablename is in both key and value)
+        * @return      array           Array with tablenames as key and arrays with status information as value
         */
        function admin_get_tables()     {
                $whichTables = array();
-               $tables_result = mysql_list_tables(TYPO3_db, $this->link);
+
+               $tables_result = mysql_query('SHOW TABLE STATUS FROM `'.TYPO3_db.'`', $this->link);
                if (!mysql_error())     {
                        while ($theTable = mysql_fetch_assoc($tables_result)) {
-                               $whichTables[current($theTable)] = current($theTable);
+                               $whichTables[$theTable['Name']] = $theTable;
                        }
+
+                       $this->sql_free_result($tables_result);
                }
+
                return $whichTables;
        }
 
@@ -984,11 +1056,13 @@ class t3lib_DB {
        function admin_get_fields($tableName)   {
                $output = array();
 
-               $columns_res = mysql_query('SHOW columns FROM '.$tableName, $this->link);
+               $columns_res = mysql_query('SHOW COLUMNS FROM `'.$tableName.'`', $this->link);
                while($fieldRow = mysql_fetch_assoc($columns_res))      {
                        $output[$fieldRow['Field']] = $fieldRow;
                }
 
+               $this->sql_free_result($columns_res);
+
                return $output;
        }
 
@@ -1002,11 +1076,37 @@ class t3lib_DB {
        function admin_get_keys($tableName)     {
                $output = array();
 
-               $keyRes = mysql_query('SHOW keys FROM '.$tableName, $this->link);
+               $keyRes = mysql_query('SHOW KEYS FROM `'.$tableName.'`', $this->link);
                while($keyRow = mysql_fetch_assoc($keyRes))     {
                        $output[] = $keyRow;
                }
 
+               $this->sql_free_result($keyRes);
+
+               return $output;
+       }
+
+       /**
+        * Returns information about the character sets supported by the current DBM
+        * This function is important not only for the Install Tool but probably for DBALs as well since they might need to look up table specific information in order to construct correct queries. In such cases this information should probably be cached for quick delivery.
+        *
+        * This is used by the Install Tool to convert tables tables with non-UTF8 charsets
+        * Use in Install Tool only!
+        *
+        * @return      array           Array with Charset as key and an array of "Charset", "Description", "Default collation", "Maxlen" as values
+        */
+       function admin_get_charsets()   {
+               $output = array();
+
+               $columns_res = mysql_query('SHOW CHARACTER SET', $this->link);
+               if ($columns_res) {
+                       while (($row = mysql_fetch_assoc($columns_res))) {
+                               $output[$row['Charset']] = $row;
+                       }
+
+                       $this->sql_free_result($columns_res);
+               }
+
                return $output;
        }
 
@@ -1019,7 +1119,7 @@ class t3lib_DB {
         */
        function admin_query($query)    {
                $res = mysql_query($query, $this->link);
-               if ($this->debugOutput) $this->debug('admin_query');
+               if ($this->debugOutput) $this->debug('admin_query',$query);
                return $res;
        }
 
@@ -1081,24 +1181,154 @@ class t3lib_DB {
         * Debug function: Outputs error if any
         *
         * @param       string          Function calling debug()
+        * @param       string          Last query if not last built query
         * @return      void
         */
-       function debug($func)   {
+       function debug($func, $query='')        {
 
                $error = $this->sql_error();
-               if ($error)             {
-                       echo t3lib_div::view_array(array(
+               if ($error)     {
+                       debug(array(
                                'caller' => 't3lib_DB::'.$func,
                                'ERROR' => $error,
-                               'lastBuiltQuery' => $this->debug_lastBuiltQuery,
+                               'lastBuiltQuery' => ($query ? $query : $this->debug_lastBuiltQuery),
                                'debug_backtrace' => t3lib_div::debug_trail()
-                       ));
+                       ), 'SQL debug');
+               }
+       }
+
+       /**
+        * Checks if recordset is valid and writes debugging inormation into devLog if not.
+        *
+        * @param       resource        $res    Recordset
+        * @return      boolean <code>false</code> if recordset is not valid
+        */
+       function debug_check_recordset($res) {
+               if (!$res) {
+                       $trace = FALSE;
+                       $msg = 'Invalid database result resource detected';
+                       $trace = debug_backtrace();
+                       array_shift($trace);
+                       $cnt = count($trace);
+                       for ($i=0; $i<$cnt; $i++)       {
+                                       // complete objects are too large for the log
+                               if (isset($trace['object']))    unset($trace['object']);
+                       }
+                       $msg .= ': function t3lib_DB->' . $trace[0]['function'] . ' called from file ' . substr($trace[0]['file'],strlen(PATH_site)+2) . ' in line ' . $trace[0]['line'];
+                       t3lib_div::sysLog($msg.'. Use a devLog extension to get more details.', 'Core/t3lib_db', 3);
+                       // Send to devLog if enabled
+                       if (TYPO3_DLOG) {
+                               $debugLogData = array(
+                                       'SQL Error' => $this->sql_error(),
+                                       'Backtrace' => $trace,
+                               );
+                               if ($this->debug_lastBuiltQuery) {
+                                       $debugLogData = array('SQL Query' => $this->debug_lastBuiltQuery) + $debugLogData;
+                               }
+                               t3lib_div::devLog($msg . '.', 'Core/t3lib_db', 3, $debugLogData);
+                       }
+
+                       return FALSE;
+               }
+               return TRUE;
+       }
+
+       /**
+        * Explain select queries
+        * If $this->explainOutput is set, SELECT queries will be explained here. Only queries with more than one possible result row will be displayed.
+        * The output is either printed as raw HTML output or embedded into the TS admin panel (checkbox must be enabled!)
+        *
+        * TODO: Feature is not DBAL-compliant
+        *
+        * @param       string          SQL query
+        * @param       string          Table(s) from which to select. This is what comes right after "FROM ...". Required value.
+        * @param       integer         Number of resulting rows
+        * @return      boolean         True if explain was run, false otherwise
+        */
+       protected function explain($query,$from_table,$row_count)       {
+
+               if ((int)$this->explainOutput==1 || ((int)$this->explainOutput==2 && t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']))) {
+                       $explainMode = 1;       // raw HTML output
+               } elseif ((int)$this->explainOutput==3 && is_object($GLOBALS['TT'])) {
+                       $explainMode = 2;       // embed the output into the TS admin panel
+               } else {
+                       return false;
                }
+
+               $error = $this->sql_error();
+               $trail = t3lib_div::debug_trail();
+
+               $explain_tables = array();
+               $explain_output = array();
+               $res = $this->sql_query('EXPLAIN '.$query, $this->link);
+               if (is_resource($res)) {
+                       while ($tempRow = $this->sql_fetch_assoc($res)) {
+                               $explain_output[] = $tempRow;
+                               $explain_tables[] = $tempRow['table'];
+                       }
+                       $this->sql_free_result($res);
+               }
+
+               $indices_output = array();
+               if ($explain_output[0]['rows']>1 || t3lib_div::inList('ALL',$explain_output[0]['type'])) {      // Notice: Rows are skipped if there is only one result, or if no conditions are set
+                       $debug = true;  // only enable output if it's really useful
+
+                       foreach ($explain_tables as $table) {
+                               $res = $this->sql_query('SHOW INDEX FROM '.$table, $this->link);
+                               if (is_resource($res)) {
+                                       while ($tempRow = $this->sql_fetch_assoc($res)) {
+                                               $indices_output[] = $tempRow;
+                                       }
+                                       $this->sql_free_result($res);
+                               }
+                       }
+               } else {
+                       $debug = false;
+               }
+
+               if ($debug) {
+                       if ($explainMode==1) {
+                               t3lib_div::debug('QUERY: '.$query);
+                               t3lib_div::debug(array('Debug trail:'=>$trail), 'Row count: '.$row_count);
+
+                               if ($error) {
+                                       t3lib_div::debug($error);
+                               }
+                               if (count($explain_output)) {
+                                       t3lib_div::debug($explain_output);
+                               }
+                               if (count($indices_output)) {
+                                       t3lib_div::debugRows($indices_output);
+                               }
+
+                       } elseif ($explainMode==2) {
+                               $data = array();
+                               $data['query'] = $query;
+                               $data['trail'] = $trail;
+                               $data['row_count'] = $row_count;
+
+                               if ($error) {
+                                       $data['error'] = $error;
+                               }
+                               if (count($explain_output)) {
+                                       $data['explain'] = $explain_output;
+                               }
+                               if (count($indices_output)) {
+                                       $data['indices'] = $indices_output;
+                               }
+                               $GLOBALS['TT']->setTSselectQuery($data);
+                       }
+                       return true;
+               }
+
+               return false;
        }
+
 }
 
 
 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php'])       {
        include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
 }
-?>
+
+?>
\ No newline at end of file