TYPO3 API  SVNRelease
class.t3lib_db.php
Go to the documentation of this file.
00001 <?php
00002 /***************************************************************
00003  *  Copyright notice
00004  *
00005  *  (c) 2004-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
00006  *  All rights reserved
00007  *
00008  *  This script is part of the TYPO3 project. The TYPO3 project is
00009  *  free software; you can redistribute it and/or modify
00010  *  it under the terms of the GNU General Public License as published by
00011  *  the Free Software Foundation; either version 2 of the License, or
00012  *  (at your option) any later version.
00013  *
00014  *  The GNU General Public License can be found at
00015  *  http://www.gnu.org/copyleft/gpl.html.
00016  *  A copy is found in the textfile GPL.txt and important notices to the license
00017  *  from the author is found in LICENSE.txt distributed with these scripts.
00018  *
00019  *
00020  *  This script is distributed in the hope that it will be useful,
00021  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023  *  GNU General Public License for more details.
00024  *
00025  *  This copyright notice MUST APPEAR in all copies of the script!
00026  ***************************************************************/
00027 /**
00028  * Contains the class "t3lib_db" containing functions for building SQL queries
00029  * and mysql wrappers, thus providing a foundational API to all database
00030  * interaction.
00031  * This class is instantiated globally as $TYPO3_DB in TYPO3 scripts.
00032  *
00033  * $Id: class.t3lib_db.php 10547 2011-02-22 20:03:57Z lolli $
00034  *
00035  * @author  Kasper Skårhøj <kasperYYYY@typo3.com>
00036  */
00037 /**
00038  * [CLASS/FUNCTION INDEX of SCRIPT]
00039  *
00040  *
00041  *
00042  *  138: class t3lib_DB
00043  *
00044  *            SECTION: Query execution
00045  *  175:     function exec_INSERTquery($table,$fields_values,$no_quote_fields=FALSE)
00046  *  192:     function exec_UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)
00047  *  206:     function exec_DELETEquery($table,$where)
00048  *  225:     function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
00049  *  250:     function exec_SELECT_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
00050  *  278:     function exec_SELECT_queryArray($queryParts)
00051  *  301:     function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='')
00052  *
00053  *            SECTION: Query building
00054  *  346:     function INSERTquery($table,$fields_values,$no_quote_fields=FALSE)
00055  *  381:     function UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)
00056  *  422:     function DELETEquery($table,$where)
00057  *  451:     function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
00058  *  492:     function listQuery($field, $value, $table)
00059  *  506:     function searchQuery($searchWords,$fields,$table)
00060  *
00061  *            SECTION: Various helper functions
00062  *  552:     function fullQuoteStr($str, $table)
00063  *  569:     function fullQuoteArray($arr, $table, $noQuote=FALSE)
00064  *  596:     function quoteStr($str, $table)
00065  *  612:     function escapeStrForLike($str, $table)
00066  *  625:     function cleanIntArray($arr)
00067  *  641:     function cleanIntList($list)
00068  *  655:     function stripOrderBy($str)
00069  *  669:     function stripGroupBy($str)
00070  *  681:     function splitGroupOrderLimit($str)
00071  *
00072  *            SECTION: MySQL wrapper functions
00073  *  749:     function sql($db,$query)
00074  *  763:     function sql_query($query)
00075  *  776:     function sql_error()
00076  *  788:     function sql_num_rows($res)
00077  *  800:     function sql_fetch_assoc($res)
00078  *  813:     function sql_fetch_row($res)
00079  *  825:     function sql_free_result($res)
00080  *  836:     function sql_insert_id()
00081  *  847:     function sql_affected_rows()
00082  *  860:     function sql_data_seek($res,$seek)
00083  *  873:     function sql_field_type($res,$pointer)
00084  *  887:     function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password)
00085  *  915:     function sql_select_db($TYPO3_db)
00086  *
00087  *            SECTION: SQL admin functions
00088  *  947:     function admin_get_dbs()
00089  *  965:     function admin_get_tables()
00090  *  984:     function admin_get_fields($tableName)
00091  * 1002:     function admin_get_keys($tableName)
00092  * 1020:     function admin_query($query)
00093  *
00094  *            SECTION: Connecting service
00095  * 1048:     function connectDB()
00096  *
00097  *            SECTION: Debugging
00098  * 1086:     function debug($func)
00099  *
00100  * TOTAL FUNCTIONS: 42
00101  * (This index is automatically created/updated by the extension "extdeveval")
00102  *
00103  */
00104 
00105 
00106 /**
00107  * TYPO3 "database wrapper" class (new in 3.6.0)
00108  * This class contains
00109  * - abstraction functions for executing INSERT/UPDATE/DELETE/SELECT queries ("Query execution"; These are REQUIRED for all future connectivity to the database, thus ensuring DBAL compliance!)
00110  * - functions for building SQL queries (INSERT/UPDATE/DELETE/SELECT) ("Query building"); These are transitional functions for building SQL queries in a more automated way. Use these to build queries instead of doing it manually in your code!
00111  * - mysql() wrapper functions; These are transitional functions. By a simple search/replace you should be able to substitute all mysql*() calls with $GLOBALS['TYPO3_DB']->sql*() and your application will work out of the box. YOU CANNOT (legally) use any mysql functions not found as wrapper functions in this class!
00112  * See the Project Coding Guidelines (doc_core_cgl) for more instructions on best-practise
00113  *
00114  * This class is not in itself a complete database abstraction layer but can be extended to be a DBAL (by extensions, see "dbal" for example)
00115  * ALL connectivity to the database in TYPO3 must be done through this class!
00116  * The points of this class are:
00117  * - To direct all database calls through this class so it becomes possible to implement DBAL with extensions.
00118  * - To keep it very easy to use for developers used to MySQL in PHP - and preserve as much performance as possible when TYPO3 is used with MySQL directly...
00119  * - To create an interface for DBAL implemented by extensions; (Eg. making possible escaping characters, clob/blob handling, reserved words handling)
00120  * - Benchmarking the DB bottleneck queries will become much easier; Will make it easier to find optimization possibilities.
00121  *
00122  * USE:
00123  * In all TYPO3 scripts the global variable $TYPO3_DB is an instance of this class. Use that.
00124  * Eg.       $GLOBALS['TYPO3_DB']->sql_fetch_assoc()
00125  *
00126  * @author  Kasper Skårhøj <kasperYYYY@typo3.com>
00127  * @package TYPO3
00128  * @subpackage t3lib
00129  */
00130 class t3lib_DB {
00131 
00132 
00133         // Debug:
00134     var $debugOutput = FALSE; // Set "TRUE" or "1" if you want database errors outputted. Set to "2" if you also want successful database actions outputted.
00135     var $debug_lastBuiltQuery = ''; // Internally: Set to last built query (not necessarily executed...)
00136     var $store_lastBuiltQuery = FALSE; // Set "TRUE" if you want the last built query to be stored in $debug_lastBuiltQuery independent of $this->debugOutput
00137     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.
00138 
00139         // Default link identifier:
00140     var $link = FALSE;
00141 
00142         // Default character set, applies unless character set or collation are explicitely set
00143     var $default_charset = 'utf8';
00144 
00145 
00146     /************************************
00147      *
00148      * Query execution
00149      *
00150      * These functions are the RECOMMENDED DBAL functions for use in your applications
00151      * Using these functions will allow the DBAL to use alternative ways of accessing data (contrary to if a query is returned!)
00152      * They compile a query AND execute it immediately and then return the result
00153      * This principle heightens our ability to create various forms of DBAL of the functions.
00154      * Generally: We want to return a result pointer/object, never queries.
00155      * Also, having the table name together with the actual query execution allows us to direct the request to other databases.
00156      *
00157      **************************************/
00158 
00159     /**
00160      * Creates and executes an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
00161      * Using this function specifically allows us to handle BLOB and CLOB fields depending on DB
00162      * Usage count/core: 47
00163      *
00164      * @param   string      Table name
00165      * @param   array       Field values as key=>value pairs. Values will be escaped internally. Typically you would fill an array like "$insertFields" with 'fieldname'=>'value' and pass it to this function as argument.
00166      * @param   string/array        See fullQuoteArray()
00167      * @return  pointer     MySQL result pointer / DBAL object
00168      */
00169     function exec_INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
00170         $res = mysql_query($this->INSERTquery($table, $fields_values, $no_quote_fields), $this->link);
00171         if ($this->debugOutput) {
00172             $this->debug('exec_INSERTquery');
00173         }
00174         return $res;
00175     }
00176 
00177     /**
00178      * Creates and executes an INSERT SQL-statement for $table with multiple rows.
00179      *
00180      * @param   string      Table name
00181      * @param   array       Field names
00182      * @param   array       Table rows. Each row should be an array with field values mapping to $fields
00183      * @param   string/array        See fullQuoteArray()
00184      * @return  pointer     MySQL result pointer / DBAL object
00185      */
00186     public function exec_INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
00187         $res = mysql_query($this->INSERTmultipleRows($table, $fields, $rows, $no_quote_fields), $this->link);
00188         if ($this->debugOutput) {
00189             $this->debug('exec_INSERTmultipleRows');
00190         }
00191         return $res;
00192     }
00193 
00194     /**
00195      * Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
00196      * Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
00197      * Usage count/core: 50
00198      *
00199      * @param   string      Database tablename
00200      * @param   string      WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
00201      * @param   array       Field values as key=>value pairs. Values will be escaped internally. Typically you would fill an array like "$updateFields" with 'fieldname'=>'value' and pass it to this function as argument.
00202      * @param   string/array        See fullQuoteArray()
00203      * @return  pointer     MySQL result pointer / DBAL object
00204      */
00205     function exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
00206         $res = mysql_query($this->UPDATEquery($table, $where, $fields_values, $no_quote_fields), $this->link);
00207         if ($this->debugOutput) {
00208             $this->debug('exec_UPDATEquery');
00209         }
00210         return $res;
00211     }
00212 
00213     /**
00214      * Creates and executes a DELETE SQL-statement for $table where $where-clause
00215      * Usage count/core: 40
00216      *
00217      * @param   string      Database tablename
00218      * @param   string      WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
00219      * @return  pointer     MySQL result pointer / DBAL object
00220      */
00221     function exec_DELETEquery($table, $where) {
00222         $res = mysql_query($this->DELETEquery($table, $where), $this->link);
00223         if ($this->debugOutput) {
00224             $this->debug('exec_DELETEquery');
00225         }
00226         return $res;
00227     }
00228 
00229     /**
00230      * Creates and executes a SELECT SQL-statement
00231      * Using this function specifically allow us to handle the LIMIT feature independently of DB.
00232      * Usage count/core: 340
00233      *
00234      * @param   string      List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
00235      * @param   string      Table(s) from which to select. This is what comes right after "FROM ...". Required value.
00236      * @param   string      additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
00237      * @param   string      Optional GROUP BY field(s), if none, supply blank string.
00238      * @param   string      Optional ORDER BY field(s), if none, supply blank string.
00239      * @param   string      Optional LIMIT value ([begin,]max), if none, supply blank string.
00240      * @return  pointer     MySQL result pointer / DBAL object
00241      */
00242     function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
00243         $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
00244         $res = mysql_query($query, $this->link);
00245 
00246         if ($this->debugOutput) {
00247             $this->debug('exec_SELECTquery');
00248         }
00249         if ($this->explainOutput) {
00250             $this->explain($query, $from_table, $this->sql_num_rows($res));
00251         }
00252 
00253         return $res;
00254     }
00255 
00256     /**
00257      * Creates and executes a SELECT query, selecting fields ($select) from two/three tables joined
00258      * Use $mm_table together with $local_table or $foreign_table to select over two tables. Or use all three tables to select the full MM-relation.
00259      * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local  / [$mm_table].uid_foreign <--> [$foreign_table].uid
00260      * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $TCA in Inside TYPO3 for more details.
00261      *
00262      * Usage: 12 (spec. ext. sys_action, sys_messages, sys_todos)
00263      *
00264      * @param   string      Field list for SELECT
00265      * @param   string      Tablename, local table
00266      * @param   string      Tablename, relation table
00267      * @param   string      Tablename, foreign table
00268      * @param   string      Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT! You have to prepend 'AND ' to this parameter yourself!
00269      * @param   string      Optional GROUP BY field(s), if none, supply blank string.
00270      * @param   string      Optional ORDER BY field(s), if none, supply blank string.
00271      * @param   string      Optional LIMIT value ([begin,]max), if none, supply blank string.
00272      * @return  pointer     MySQL result pointer / DBAL object
00273      * @see exec_SELECTquery()
00274      */
00275     function exec_SELECT_mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
00276         if ($foreign_table == $local_table) {
00277             $foreign_table_as = $foreign_table . uniqid('_join');
00278         }
00279 
00280         $mmWhere = $local_table ? $local_table . '.uid=' . $mm_table . '.uid_local' : '';
00281         $mmWhere .= ($local_table AND $foreign_table) ? ' AND ' : '';
00282 
00283         $tables = ($local_table ? $local_table . ',' : '') . $mm_table;
00284 
00285         if ($foreign_table) {
00286             $mmWhere .= ($foreign_table_as ? $foreign_table_as : $foreign_table) . '.uid=' . $mm_table . '.uid_foreign';
00287             $tables .= ',' . $foreign_table . ($foreign_table_as ? ' AS ' . $foreign_table_as : '');
00288         }
00289 
00290         return $this->exec_SELECTquery(
00291             $select,
00292             $tables,
00293                 // whereClauseMightContainGroupOrderBy
00294                 $mmWhere . ' ' . $whereClause,
00295             $groupBy,
00296             $orderBy,
00297             $limit
00298         );
00299     }
00300 
00301     /**
00302      * Executes a select based on input query parts array
00303      *
00304      * Usage: 9
00305      *
00306      * @param   array       Query parts array
00307      * @return  pointer     MySQL select result pointer / DBAL object
00308      * @see exec_SELECTquery()
00309      */
00310     function exec_SELECT_queryArray($queryParts) {
00311         return $this->exec_SELECTquery(
00312             $queryParts['SELECT'],
00313             $queryParts['FROM'],
00314             $queryParts['WHERE'],
00315             $queryParts['GROUPBY'],
00316             $queryParts['ORDERBY'],
00317             $queryParts['LIMIT']
00318         );
00319     }
00320 
00321     /**
00322      * Creates and executes a SELECT SQL-statement AND traverse result set and returns array with records in.
00323      *
00324      * @param   string      See exec_SELECTquery()
00325      * @param   string      See exec_SELECTquery()
00326      * @param   string      See exec_SELECTquery()
00327      * @param   string      See exec_SELECTquery()
00328      * @param   string      See exec_SELECTquery()
00329      * @param   string      See exec_SELECTquery()
00330      * @param   string      If set, the result array will carry this field names value as index. Requires that field to be selected of course!
00331      * @return  array       Array of rows.
00332      */
00333     function exec_SELECTgetRows($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', $uidIndexField = '') {
00334         $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
00335         if ($this->debugOutput) {
00336             $this->debug('exec_SELECTquery');
00337         }
00338 
00339         if (!$this->sql_error()) {
00340             $output = array();
00341 
00342             if ($uidIndexField) {
00343                 while ($tempRow = $this->sql_fetch_assoc($res)) {
00344                     $output[$tempRow[$uidIndexField]] = $tempRow;
00345                 }
00346             } else {
00347                 while ($output[] = $this->sql_fetch_assoc($res)) {
00348                     ;
00349                 }
00350                 array_pop($output);
00351             }
00352             $this->sql_free_result($res);
00353         }
00354         return $output;
00355     }
00356 
00357     /**
00358      * Creates and executes a SELECT SQL-statement AND gets a result set and returns an array with a single record in.
00359      * LIMIT is automatically set to 1 and can not be overridden.
00360      *
00361      * @param string $select_fields: List of fields to select from the table.
00362      * @param string $from_table: Table(s) from which to select.
00363      * @param string $where_clause: Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
00364      * @param string $groupBy: Optional GROUP BY field(s), if none, supply blank string.
00365      * @param string $orderBy: Optional ORDER BY field(s), if none, supply blank string.
00366      * @param boolean $numIndex: If set, the result will be fetched with sql_fetch_row, otherwise sql_fetch_assoc will be used.
00367      * @return array Single row or NULL if it fails.
00368      */
00369     public function exec_SELECTgetSingleRow($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $numIndex = FALSE) {
00370         $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, '1');
00371         if ($this->debugOutput) {
00372             $this->debug('exec_SELECTquery');
00373         }
00374 
00375         $output = NULL;
00376         if ($res) {
00377             if ($numIndex) {
00378                 $output = $this->sql_fetch_row($res);
00379             } else {
00380                 $output = $this->sql_fetch_assoc($res);
00381             }
00382             $this->sql_free_result($res);
00383         }
00384         return $output;
00385     }
00386 
00387     /**
00388      * Counts the number of rows in a table.
00389      *
00390      * @param   string      $field: Name of the field to use in the COUNT() expression (e.g. '*')
00391      * @param   string      $table: Name of the table to count rows for
00392      * @param   string      $where: (optional) WHERE statement of the query
00393      * @return  mixed       Number of rows counter (integer) or false if something went wrong (boolean)
00394      */
00395     public function exec_SELECTcountRows($field, $table, $where = '') {
00396         $count = FALSE;
00397         $resultSet = $this->exec_SELECTquery('COUNT(' . $field . ')', $table, $where);
00398         if ($resultSet !== FALSE) {
00399             list($count) = $this->sql_fetch_row($resultSet);
00400             $this->sql_free_result($resultSet);
00401         }
00402         return $count;
00403     }
00404 
00405     /**
00406      * Truncates a table.
00407      *
00408      * @param   string      Database tablename
00409      * @return  mixed       Result from handler
00410      */
00411     public function exec_TRUNCATEquery($table) {
00412         $res = mysql_query($this->TRUNCATEquery($table), $this->link);
00413         if ($this->debugOutput) {
00414             $this->debug('exec_TRUNCATEquery');
00415         }
00416         return $res;
00417     }
00418 
00419 
00420     /**************************************
00421      *
00422      * Query building
00423      *
00424      **************************************/
00425 
00426     /**
00427      * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
00428      * Usage count/core: 4
00429      *
00430      * @param   string      See exec_INSERTquery()
00431      * @param   array       See exec_INSERTquery()
00432      * @param   string/array        See fullQuoteArray()
00433      * @return  string      Full SQL query for INSERT (unless $fields_values does not contain any elements in which case it will be false)
00434      */
00435     function INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
00436 
00437             // Table and fieldnames should be "SQL-injection-safe" when supplied to this
00438             // function (contrary to values in the arrays which may be insecure).
00439         if (is_array($fields_values) && count($fields_values)) {
00440 
00441                 // quote and escape values
00442             $fields_values = $this->fullQuoteArray($fields_values, $table, $no_quote_fields);
00443 
00444                 // Build query:
00445             $query = 'INSERT INTO ' . $table .
00446                     ' (' . implode(',', array_keys($fields_values)) . ') VALUES ' .
00447                     '(' . implode(',', $fields_values) . ')';
00448 
00449                 // Return query:
00450             if ($this->debugOutput || $this->store_lastBuiltQuery) {
00451                 $this->debug_lastBuiltQuery = $query;
00452             }
00453             return $query;
00454         }
00455     }
00456 
00457     /**
00458      * Creates an INSERT SQL-statement for $table with multiple rows.
00459      *
00460      * @param   string      Table name
00461      * @param   array       Field names
00462      * @param   array       Table rows. Each row should be an array with field values mapping to $fields
00463      * @param   string/array        See fullQuoteArray()
00464      * @return  string      Full SQL query for INSERT (unless $rows does not contain any elements in which case it will be false)
00465      */
00466     public function INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
00467             // Table and fieldnames should be "SQL-injection-safe" when supplied to this
00468             // function (contrary to values in the arrays which may be insecure).
00469         if (count($rows)) {
00470                 // Build query:
00471             $query = 'INSERT INTO ' . $table .
00472                     ' (' . implode(', ', $fields) . ') VALUES ';
00473 
00474             $rowSQL = array();
00475             foreach ($rows as $row) {
00476                     // quote and escape values
00477                 $row = $this->fullQuoteArray($row, $table, $no_quote_fields);
00478                 $rowSQL[] = '(' . implode(', ', $row) . ')';
00479             }
00480 
00481             $query .= implode(', ', $rowSQL);
00482 
00483                 // Return query:
00484             if ($this->debugOutput || $this->store_lastBuiltQuery) {
00485                 $this->debug_lastBuiltQuery = $query;
00486             }
00487 
00488             return $query;
00489         }
00490     }
00491 
00492     /**
00493      * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
00494      * Usage count/core: 6
00495      *
00496      * @param   string      See exec_UPDATEquery()
00497      * @param   string      See exec_UPDATEquery()
00498      * @param   array       See exec_UPDATEquery()
00499      * @param   array       See fullQuoteArray()
00500      * @return  string      Full SQL query for UPDATE
00501      */
00502     function UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
00503             // Table and fieldnames should be "SQL-injection-safe" when supplied to this
00504             // function (contrary to values in the arrays which may be insecure).
00505         if (is_string($where)) {
00506             $fields = array();
00507             if (is_array($fields_values) && count($fields_values)) {
00508 
00509                     // quote and escape values
00510                 $nArr = $this->fullQuoteArray($fields_values, $table, $no_quote_fields);
00511 
00512                 foreach ($nArr as $k => $v) {
00513                     $fields[] = $k . '=' . $v;
00514                 }
00515             }
00516 
00517                 // Build query:
00518             $query = 'UPDATE ' . $table . ' SET ' . implode(',', $fields) .
00519                     (strlen($where) > 0 ? ' WHERE ' . $where : '');
00520 
00521             if ($this->debugOutput || $this->store_lastBuiltQuery) {
00522                 $this->debug_lastBuiltQuery = $query;
00523             }
00524             return $query;
00525         } else {
00526             throw new InvalidArgumentException(
00527                 'TYPO3 Fatal Error: "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !',
00528                 1270853880
00529             );
00530         }
00531     }
00532 
00533     /**
00534      * Creates a DELETE SQL-statement for $table where $where-clause
00535      * Usage count/core: 3
00536      *
00537      * @param   string      See exec_DELETEquery()
00538      * @param   string      See exec_DELETEquery()
00539      * @return  string      Full SQL query for DELETE
00540      */
00541     function DELETEquery($table, $where) {
00542         if (is_string($where)) {
00543 
00544                 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
00545             $query = 'DELETE FROM ' . $table .
00546                     (strlen($where) > 0 ? ' WHERE ' . $where : '');
00547 
00548             if ($this->debugOutput || $this->store_lastBuiltQuery) {
00549                 $this->debug_lastBuiltQuery = $query;
00550             }
00551             return $query;
00552         } else {
00553             throw new InvalidArgumentException(
00554                 'TYPO3 Fatal Error: "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !',
00555                 1270853881
00556             );
00557         }
00558     }
00559 
00560     /**
00561      * Creates a SELECT SQL-statement
00562      * Usage count/core: 11
00563      *
00564      * @param   string      See exec_SELECTquery()
00565      * @param   string      See exec_SELECTquery()
00566      * @param   string      See exec_SELECTquery()
00567      * @param   string      See exec_SELECTquery()
00568      * @param   string      See exec_SELECTquery()
00569      * @param   string      See exec_SELECTquery()
00570      * @return  string      Full SQL query for SELECT
00571      */
00572     function SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
00573 
00574             // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
00575             // Build basic query:
00576         $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table .
00577                 (strlen($where_clause) > 0 ? ' WHERE ' . $where_clause : '');
00578 
00579             // Group by:
00580         $query .= (strlen($groupBy) > 0 ? ' GROUP BY ' . $groupBy : '');
00581 
00582             // Order by:
00583         $query .= (strlen($orderBy) > 0 ? ' ORDER BY ' . $orderBy : '');
00584 
00585             // Group by:
00586         $query .= (strlen($limit) > 0 ? ' LIMIT ' . $limit : '');
00587 
00588             // Return query:
00589         if ($this->debugOutput || $this->store_lastBuiltQuery) {
00590             $this->debug_lastBuiltQuery = $query;
00591         }
00592         return $query;
00593     }
00594 
00595     /**
00596      * Creates a SELECT SQL-statement to be used as subquery within another query.
00597      * BEWARE: This method should not be overriden within DBAL to prevent quoting from happening.
00598      *
00599      * @param   string      $select_fields: List of fields to select from the table.
00600      * @param   string      $from_table: Table from which to select.
00601      * @param   string      $where_clause: Conditional WHERE statement
00602      * @return  string      Full SQL query for SELECT
00603      */
00604     public function SELECTsubquery($select_fields, $from_table, $where_clause) {
00605             // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
00606             // Build basic query:
00607         $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table .
00608                 (strlen($where_clause) > 0 ? ' WHERE ' . $where_clause : '');
00609 
00610             // Return query:
00611         if ($this->debugOutput || $this->store_lastBuiltQuery) {
00612             $this->debug_lastBuiltQuery = $query;
00613         }
00614 
00615         return $query;
00616     }
00617 
00618     /**
00619      * Creates a TRUNCATE TABLE SQL-statement
00620      *
00621      * @param   string      See exec_TRUNCATEquery()
00622      * @return  string      Full SQL query for TRUNCATE TABLE
00623      */
00624     public function TRUNCATEquery($table) {
00625             // Table should be "SQL-injection-safe" when supplied to this function
00626             // Build basic query:
00627         $query = 'TRUNCATE TABLE ' . $table;
00628 
00629             // Return query:
00630         if ($this->debugOutput || $this->store_lastBuiltQuery) {
00631             $this->debug_lastBuiltQuery = $query;
00632         }
00633 
00634         return $query;
00635     }
00636 
00637     /**
00638      * Returns a WHERE clause that can find a value ($value) in a list field ($field)
00639      * For instance a record in the database might contain a list of numbers,
00640      * "34,234,5" (with no spaces between). This query would be able to select that
00641      * record based on the value "34", "234" or "5" regardless of their position in
00642      * the list (left, middle or right).
00643      * The value must not contain a comma (,)
00644      * Is nice to look up list-relations to records or files in TYPO3 database tables.
00645      *
00646      * @param   string      Field name
00647      * @param   string      Value to find in list
00648      * @param   string      Table in which we are searching (for DBAL detection of quoteStr() method)
00649      * @return  string      WHERE clause for a query
00650      */
00651     public function listQuery($field, $value, $table) {
00652         $value = (string) $value;
00653         if (strpos(',', $value) !== FALSE) {
00654             throw new InvalidArgumentException('$value must not contain a comma (,) in $this->listQuery() !');
00655         }
00656         $pattern = $this->quoteStr($value, $table);
00657         $where = 'FIND_IN_SET(\'' . $pattern . '\',' . $field . ')';
00658         return $where;
00659     }
00660 
00661     /**
00662      * Returns a WHERE clause which will make an AND search for the words in the $searchWords array in any of the fields in array $fields.
00663      *
00664      * @param   array       Array of search words
00665      * @param   array       Array of fields
00666      * @param   string      Table in which we are searching (for DBAL detection of quoteStr() method)
00667      * @return  string      WHERE clause for search
00668      */
00669     function searchQuery($searchWords, $fields, $table) {
00670         $queryParts = array();
00671 
00672         foreach ($searchWords as $sw) {
00673             $like = ' LIKE \'%' . $this->quoteStr($sw, $table) . '%\'';
00674             $queryParts[] = $table . '.' . implode($like . ' OR ' . $table . '.', $fields) . $like;
00675         }
00676         $query = '(' . implode(') AND (', $queryParts) . ')';
00677         return $query;
00678     }
00679 
00680 
00681     /**************************************
00682      *
00683      * Prepared Query Support
00684      *
00685      **************************************/
00686 
00687     /**
00688      * Creates a SELECT prepared SQL statement.
00689      *
00690      * @param string See exec_SELECTquery()
00691      * @param string See exec_SELECTquery()
00692      * @param string See exec_SELECTquery()
00693      * @param string See exec_SELECTquery()
00694      * @param string See exec_SELECTquery()
00695      * @param string See exec_SELECTquery()
00696      * @param array $input_parameters An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as t3lib_db_PreparedStatement::PARAM_AUTOTYPE.
00697      * @return t3lib_db_PreparedStatement Prepared statement
00698      */
00699     public function prepare_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', array $input_parameters = array()) {
00700         $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
00701         $preparedStatement = t3lib_div::makeInstance('t3lib_db_PreparedStatement', $query, $from_table, array());
00702         /* @var $preparedStatement t3lib_db_PreparedStatement */
00703 
00704             // Bind values to parameters
00705         foreach ($input_parameters as $key => $value) {
00706             $preparedStatement->bindValue($key, $value, t3lib_db_PreparedStatement::PARAM_AUTOTYPE);
00707         }
00708 
00709             // Return prepared statement
00710         return $preparedStatement;
00711     }
00712 
00713     /**
00714      * Creates a SELECT prepared SQL statement based on input query parts array
00715      *
00716      * @param array Query parts array
00717      * @param array $input_parameters An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as t3lib_db_PreparedStatement::PARAM_AUTOTYPE.
00718      * @return t3lib_db_PreparedStatement Prepared statement
00719      */
00720     public function prepare_SELECTqueryArray(array $queryParts, array $input_parameters = array()) {
00721         return $this->prepare_SELECTquery(
00722             $queryParts['SELECT'],
00723             $queryParts['FROM'],
00724             $queryParts['WHERE'],
00725             $queryParts['GROUPBY'],
00726             $queryParts['ORDERBY'],
00727             $queryParts['LIMIT'],
00728             $input_parameters
00729         );
00730     }
00731 
00732     /**
00733      * Executes a prepared query.
00734      * This method may only be called by t3lib_db_PreparedStatement.
00735      *
00736      * @param string $query The query to execute
00737      * @param array $queryComponents The components of the query to execute
00738      * @return pointer MySQL result pointer / DBAL object
00739      * @access private
00740      */
00741     public function exec_PREPAREDquery($query, array $queryComponents) {
00742         $res = mysql_query($query, $this->link);
00743         if ($this->debugOutput) {
00744             $this->debug('stmt_execute', $query);
00745         }
00746         return $res;
00747     }
00748 
00749 
00750     /**************************************
00751      *
00752      * Various helper functions
00753      *
00754      * Functions recommended to be used for
00755      * - escaping values,
00756      * - cleaning lists of values,
00757      * - stripping of excess ORDER BY/GROUP BY keywords
00758      *
00759      **************************************/
00760 
00761     /**
00762      * Escaping and quoting values for SQL statements.
00763      * Usage count/core: 100
00764      *
00765      * @param   string      Input string
00766      * @param   string      Table name for which to quote string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
00767      * @return  string      Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
00768      * @see quoteStr()
00769      */
00770     function fullQuoteStr($str, $table) {
00771         return '\'' . mysql_real_escape_string($str, $this->link) . '\'';
00772     }
00773 
00774     /**
00775      * Will fullquote all values in the one-dimensional array so they are ready to "implode" for an sql query.
00776      *
00777      * @param   array       Array with values (either associative or non-associative array)
00778      * @param   string      Table name for which to quote
00779      * @param   string/array        List/array of keys NOT to quote (eg. SQL functions) - ONLY for associative arrays
00780      * @return  array       The input array with the values quoted
00781      * @see cleanIntArray()
00782      */
00783     function fullQuoteArray($arr, $table, $noQuote = FALSE) {
00784         if (is_string($noQuote)) {
00785             $noQuote = explode(',', $noQuote);
00786             // sanity check
00787         } elseif (!is_array($noQuote)) {
00788             $noQuote = FALSE;
00789         }
00790 
00791         foreach ($arr as $k => $v) {
00792             if ($noQuote === FALSE || !in_array($k, $noQuote)) {
00793                 $arr[$k] = $this->fullQuoteStr($v, $table);
00794             }
00795         }
00796         return $arr;
00797     }
00798 
00799     /**
00800      * Substitution for PHP function "addslashes()"
00801      * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
00802      * NOTICE: You must wrap the output of this function in SINGLE QUOTES to be DBAL compatible. Unless you have to apply the single quotes yourself you should rather use ->fullQuoteStr()!
00803      *
00804      * Usage count/core: 20
00805      *
00806      * @param   string      Input string
00807      * @param   string      Table name for which to quote string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
00808      * @return  string      Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
00809      * @see quoteStr()
00810      */
00811     function quoteStr($str, $table) {
00812         return mysql_real_escape_string($str, $this->link);
00813     }
00814 
00815     /**
00816      * Escaping values for SQL LIKE statements.
00817      *
00818      * @param   string      Input string
00819      * @param   string      Table name for which to escape string. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how to quote the string!).
00820      * @return  string      Output string; % and _ will be escaped with \ (or otherwise based on DBAL handler)
00821      * @see quoteStr()
00822      */
00823     function escapeStrForLike($str, $table) {
00824         return addcslashes($str, '_%');
00825     }
00826 
00827     /**
00828      * Will convert all values in the one-dimensional array to integers.
00829      * Useful when you want to make sure an array contains only integers before imploding them in a select-list.
00830      * Usage count/core: 7
00831      *
00832      * @param   array       Array with values
00833      * @return  array       The input array with all values passed through intval()
00834      * @see cleanIntList()
00835      */
00836     function cleanIntArray($arr) {
00837         foreach ($arr as $k => $v) {
00838             $arr[$k] = intval($arr[$k]);
00839         }
00840         return $arr;
00841     }
00842 
00843     /**
00844      * Will force all entries in the input comma list to integers
00845      * Useful when you want to make sure a commalist of supposed integers really contain only integers; You want to know that when you don't trust content that could go into an SQL statement.
00846      * Usage count/core: 6
00847      *
00848      * @param   string      List of comma-separated values which should be integers
00849      * @return  string      The input list but with every value passed through intval()
00850      * @see cleanIntArray()
00851      */
00852     function cleanIntList($list) {
00853         return implode(',', t3lib_div::intExplode(',', $list));
00854     }
00855 
00856     /**
00857      * Removes the prefix "ORDER BY" from the input string.
00858      * This function is used when you call the exec_SELECTquery() function and want to pass the ORDER BY parameter by can't guarantee that "ORDER BY" is not prefixed.
00859      * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
00860      * Usage count/core: 11
00861      *
00862      * @param   string      eg. "ORDER BY title, uid"
00863      * @return  string      eg. "title, uid"
00864      * @see exec_SELECTquery(), stripGroupBy()
00865      */
00866     function stripOrderBy($str) {
00867         return preg_replace('/^ORDER[[:space:]]+BY[[:space:]]+/i', '', trim($str));
00868     }
00869 
00870     /**
00871      * Removes the prefix "GROUP BY" from the input string.
00872      * This function is used when you call the SELECTquery() function and want to pass the GROUP BY parameter by can't guarantee that "GROUP BY" is not prefixed.
00873      * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
00874      * Usage count/core: 1
00875      *
00876      * @param   string      eg. "GROUP BY title, uid"
00877      * @return  string      eg. "title, uid"
00878      * @see exec_SELECTquery(), stripOrderBy()
00879      */
00880     function stripGroupBy($str) {
00881         return preg_replace('/^GROUP[[:space:]]+BY[[:space:]]+/i', '', trim($str));
00882     }
00883 
00884     /**
00885      * Takes the last part of a query, eg. "... uid=123 GROUP BY title ORDER BY title LIMIT 5,2" and splits each part into a table (WHERE, GROUPBY, ORDERBY, LIMIT)
00886      * Work-around function for use where you know some userdefined end to an SQL clause is supplied and you need to separate these factors.
00887      * Usage count/core: 13
00888      *
00889      * @param   string      Input string
00890      * @return  array
00891      */
00892     function splitGroupOrderLimit($str) {
00893             // Prepending a space to make sure "[[:space:]]+" will find a space there
00894             // for the first element.
00895         $str = ' ' . $str;
00896             // Init output array:
00897         $wgolParts = array(
00898             'WHERE' => '',
00899             'GROUPBY' => '',
00900             'ORDERBY' => '',
00901             'LIMIT' => '',
00902         );
00903 
00904             // Find LIMIT:
00905         $reg = array();
00906         if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
00907             $wgolParts['LIMIT'] = trim($reg[2]);
00908             $str = $reg[1];
00909         }
00910 
00911             // Find ORDER BY:
00912         $reg = array();
00913         if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
00914             $wgolParts['ORDERBY'] = trim($reg[2]);
00915             $str = $reg[1];
00916         }
00917 
00918             // Find GROUP BY:
00919         $reg = array();
00920         if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
00921             $wgolParts['GROUPBY'] = trim($reg[2]);
00922             $str = $reg[1];
00923         }
00924 
00925             // Rest is assumed to be "WHERE" clause:
00926         $wgolParts['WHERE'] = $str;
00927 
00928         return $wgolParts;
00929     }
00930 
00931 
00932     /**************************************
00933      *
00934      * MySQL wrapper functions
00935      * (For use in your applications)
00936      *
00937      **************************************/
00938 
00939     /**
00940      * Executes query
00941      * mysql_query() wrapper function
00942      * Beware: Use of this method should be avoided as it is experimentally supported by DBAL. You should consider
00943      *         using exec_SELECTquery() and similar methods instead.
00944      * Usage count/core: 1
00945      *
00946      * @param   string      Query to execute
00947      * @return  pointer     Result pointer / DBAL object
00948      */
00949     function sql_query($query) {
00950         $res = mysql_query($query, $this->link);
00951         if ($this->debugOutput) {
00952             $this->debug('sql_query', $query);
00953         }
00954         return $res;
00955     }
00956 
00957     /**
00958      * Returns the error status on the last sql() execution
00959      * mysql_error() wrapper function
00960      * Usage count/core: 32
00961      *
00962      * @return  string      MySQL error string.
00963      */
00964     function sql_error() {
00965         return mysql_error($this->link);
00966     }
00967 
00968     /**
00969      * Returns the error number on the last sql() execution
00970      * mysql_errno() wrapper function
00971      *
00972      * @return  int     MySQL error number.
00973      */
00974     function sql_errno() {
00975         return mysql_errno($this->link);
00976     }
00977 
00978     /**
00979      * Returns the number of selected rows.
00980      * mysql_num_rows() wrapper function
00981      * Usage count/core: 85
00982      *
00983      * @param   pointer     MySQL result pointer (of SELECT query) / DBAL object
00984      * @return  integer     Number of resulting rows
00985      */
00986     function sql_num_rows($res) {
00987         if ($this->debug_check_recordset($res)) {
00988             return mysql_num_rows($res);
00989         } else {
00990             return FALSE;
00991         }
00992     }
00993 
00994     /**
00995      * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
00996      * mysql_fetch_assoc() wrapper function
00997      * Usage count/core: 307
00998      *
00999      * @param   pointer     MySQL result pointer (of SELECT query) / DBAL object
01000      * @return  array       Associative array of result row.
01001      */
01002     function sql_fetch_assoc($res) {
01003         if ($this->debug_check_recordset($res)) {
01004             return mysql_fetch_assoc($res);
01005         } else {
01006             return FALSE;
01007         }
01008     }
01009 
01010     /**
01011      * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
01012      * The array contains the values in numerical indices.
01013      * mysql_fetch_row() wrapper function
01014      * Usage count/core: 56
01015      *
01016      * @param   pointer     MySQL result pointer (of SELECT query) / DBAL object
01017      * @return  array       Array with result rows.
01018      */
01019     function sql_fetch_row($res) {
01020         if ($this->debug_check_recordset($res)) {
01021             return mysql_fetch_row($res);
01022         } else {
01023             return FALSE;
01024         }
01025     }
01026 
01027     /**
01028      * Free result memory
01029      * mysql_free_result() wrapper function
01030      * Usage count/core: 3
01031      *
01032      * @param   pointer     MySQL result pointer to free / DBAL object
01033      * @return  boolean     Returns TRUE on success or FALSE on failure.
01034      */
01035     function sql_free_result($res) {
01036         if ($this->debug_check_recordset($res)) {
01037             return mysql_free_result($res);
01038         } else {
01039             return FALSE;
01040         }
01041     }
01042 
01043     /**
01044      * Get the ID generated from the previous INSERT operation
01045      * mysql_insert_id() wrapper function
01046      * Usage count/core: 13
01047      *
01048      * @return  integer     The uid of the last inserted record.
01049      */
01050     function sql_insert_id() {
01051         return mysql_insert_id($this->link);
01052     }
01053 
01054     /**
01055      * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
01056      * mysql_affected_rows() wrapper function
01057      * Usage count/core: 1
01058      *
01059      * @return  integer     Number of rows affected by last query
01060      */
01061     function sql_affected_rows() {
01062         return mysql_affected_rows($this->link);
01063     }
01064 
01065     /**
01066      * Move internal result pointer
01067      * mysql_data_seek() wrapper function
01068      * Usage count/core: 3
01069      *
01070      * @param   pointer     MySQL result pointer (of SELECT query) / DBAL object
01071      * @param   integer     Seek result number.
01072      * @return  boolean     Returns TRUE on success or FALSE on failure.
01073      */
01074     function sql_data_seek($res, $seek) {
01075         if ($this->debug_check_recordset($res)) {
01076             return mysql_data_seek($res, $seek);
01077         } else {
01078             return FALSE;
01079         }
01080     }
01081 
01082     /**
01083      * Get the type of the specified field in a result
01084      * mysql_field_type() wrapper function
01085      * Usage count/core: 2
01086      *
01087      * @param   pointer     MySQL result pointer (of SELECT query) / DBAL object
01088      * @param   integer     Field index.
01089      * @return  string      Returns the name of the specified field index
01090      */
01091     function sql_field_type($res, $pointer) {
01092         if ($this->debug_check_recordset($res)) {
01093             return mysql_field_type($res, $pointer);
01094         } else {
01095             return FALSE;
01096         }
01097     }
01098 
01099     /**
01100      * Open a (persistent) connection to a MySQL server
01101      * mysql_pconnect() wrapper function
01102      * Usage count/core: 12
01103      *
01104      * @param   string      Database host IP/domain
01105      * @param   string      Username to connect with.
01106      * @param   string      Password to connect with.
01107      * @return  pointer     Returns a positive MySQL persistent link identifier on success, or FALSE on error.
01108      */
01109     function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) {
01110             // mysql_error() is tied to an established connection
01111             // if the connection fails we need a different method to get the error message
01112         @ini_set('track_errors', 1);
01113         @ini_set('html_errors', 0);
01114 
01115             // check if MySQL extension is loaded
01116         if (!extension_loaded('mysql')) {
01117             $message = 'Database Error: It seems that MySQL support for PHP is not installed!';
01118             throw new RuntimeException($message, 1271492606);
01119         }
01120 
01121             // Check for client compression
01122         $isLocalhost = ($TYPO3_db_host == 'localhost' || $TYPO3_db_host == '127.0.0.1');
01123         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
01124             if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
01125                     // We use PHP's default value for 4th parameter (new_link), which is false.
01126                     // See PHP sources, for example: file php-5.2.5/ext/mysql/php_mysql.c,
01127                     // function php_mysql_do_connect(), near line 525
01128                 $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, FALSE, MYSQL_CLIENT_COMPRESS);
01129             } else {
01130                 $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
01131             }
01132         } else {
01133             if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
01134                     // See comment about 4th parameter in block above
01135                 $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, MYSQL_CLIENT_COMPRESS);
01136             } else {
01137                 $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
01138             }
01139         }
01140 
01141         $error_msg = $php_errormsg;
01142         @ini_restore('track_errors');
01143         @ini_restore('html_errors');
01144 
01145         if (!$this->link) {
01146             t3lib_div::sysLog('Could not connect to MySQL server ' . $TYPO3_db_host .
01147                     ' with user ' . $TYPO3_db_username . ': ' . $error_msg,
01148                 'Core',
01149                 4
01150             );
01151         } else {
01152             $setDBinit = t3lib_div::trimExplode(LF, str_replace("' . LF . '", LF, $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']), TRUE);
01153             foreach ($setDBinit as $v) {
01154                 if (mysql_query($v, $this->link) === FALSE) {
01155                     t3lib_div::sysLog('Could not initialize DB connection with query "' . $v .
01156                             '": ' . mysql_error($this->link),
01157                         'Core',
01158                         3
01159                     );
01160                 }
01161             }
01162             $this->setSqlMode();
01163         }
01164 
01165         return $this->link;
01166     }
01167 
01168     /**
01169      * Fixes the SQL mode by unsetting NO_BACKSLASH_ESCAPES if found.
01170      *
01171      * @return void
01172      */
01173     protected function setSqlMode() {
01174         $resource = $this->sql_query('SELECT @@SESSION.sql_mode;');
01175         if (is_resource($resource)) {
01176             $result = $this->sql_fetch_row($resource);
01177             if (isset($result[0]) && $result[0] && strpos($result[0], 'NO_BACKSLASH_ESCAPES') !== FALSE) {
01178                 $modes = array_diff(
01179                     t3lib_div::trimExplode(',', $result[0]),
01180                     array('NO_BACKSLASH_ESCAPES')
01181                 );
01182                 $query = 'SET sql_mode=\'' . mysql_real_escape_string(implode(',', $modes)) . '\';';
01183                 $success = $this->sql_query($query);
01184 
01185                 t3lib_div::sysLog(
01186                     'NO_BACKSLASH_ESCAPES could not be removed from SQL mode: ' . $this->sql_error(),
01187                     'Core',
01188                     3
01189                 );
01190             }
01191         }
01192     }
01193 
01194     /**
01195      * Select a MySQL database
01196      * mysql_select_db() wrapper function
01197      * Usage count/core: 8
01198      *
01199      * @param   string      Database to connect to.
01200      * @return  boolean     Returns TRUE on success or FALSE on failure.
01201      */
01202     function sql_select_db($TYPO3_db) {
01203         $ret = @mysql_select_db($TYPO3_db, $this->link);
01204         if (!$ret) {
01205             t3lib_div::sysLog('Could not select MySQL database ' . $TYPO3_db . ': ' .
01206                     mysql_error(),
01207                 'Core',
01208                 4
01209             );
01210         }
01211         return $ret;
01212     }
01213 
01214 
01215     /**************************************
01216      *
01217      * SQL admin functions
01218      * (For use in the Install Tool and Extension Manager)
01219      *
01220      **************************************/
01221 
01222     /**
01223      * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
01224      * This is only used as a service function in the (1-2-3 process) of the Install Tool.
01225      * In any case a lookup should be done in the _DEFAULT handler DBMS then.
01226      * Use in Install Tool only!
01227      * Usage count/core: 1
01228      *
01229      * @return  array       Each entry represents a database name
01230      */
01231     function admin_get_dbs() {
01232         $dbArr = array();
01233         $db_list = mysql_list_dbs($this->link);
01234         while ($row = mysql_fetch_object($db_list)) {
01235             if ($this->sql_select_db($row->Database)) {
01236                 $dbArr[] = $row->Database;
01237             }
01238         }
01239         return $dbArr;
01240     }
01241 
01242     /**
01243      * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
01244      * In a DBAL this method should 1) look up all tables from the DBMS  of
01245      * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
01246      * Usage count/core: 2
01247      *
01248      * @return  array       Array with tablenames as key and arrays with status information as value
01249      */
01250     function admin_get_tables() {
01251         $whichTables = array();
01252 
01253         $tables_result = mysql_query('SHOW TABLE STATUS FROM `' . TYPO3_db . '`', $this->link);
01254         if (!mysql_error()) {
01255             while ($theTable = mysql_fetch_assoc($tables_result)) {
01256                 $whichTables[$theTable['Name']] = $theTable;
01257             }
01258 
01259             $this->sql_free_result($tables_result);
01260         }
01261 
01262         return $whichTables;
01263     }
01264 
01265     /**
01266      * Returns information about each field in the $table (quering the DBMS)
01267      * In a DBAL this should look up the right handler for the table and return compatible information
01268      * This function is important not only for the Install Tool but probably for
01269      * DBALs as well since they might need to look up table specific information
01270      * in order to construct correct queries. In such cases this information should
01271      * probably be cached for quick delivery.
01272      *
01273      * @param   string      Table name
01274      * @return  array       Field information in an associative array with fieldname => field row
01275      */
01276     function admin_get_fields($tableName) {
01277         $output = array();
01278 
01279         $columns_res = mysql_query('SHOW COLUMNS FROM `' . $tableName . '`', $this->link);
01280         while ($fieldRow = mysql_fetch_assoc($columns_res)) {
01281             $output[$fieldRow['Field']] = $fieldRow;
01282         }
01283 
01284         $this->sql_free_result($columns_res);
01285 
01286         return $output;
01287     }
01288 
01289     /**
01290      * Returns information about each index key in the $table (quering the DBMS)
01291      * In a DBAL this should look up the right handler for the table and return compatible information
01292      *
01293      * @param   string      Table name
01294      * @return  array       Key information in a numeric array
01295      */
01296     function admin_get_keys($tableName) {
01297         $output = array();
01298 
01299         $keyRes = mysql_query('SHOW KEYS FROM `' . $tableName . '`', $this->link);
01300         while ($keyRow = mysql_fetch_assoc($keyRes)) {
01301             $output[] = $keyRow;
01302         }
01303 
01304         $this->sql_free_result($keyRes);
01305 
01306         return $output;
01307     }
01308 
01309     /**
01310      * Returns information about the character sets supported by the current DBM
01311      * This function is important not only for the Install Tool but probably for
01312      * DBALs as well since they might need to look up table specific information
01313      * in order to construct correct queries. In such cases this information should
01314      * probably be cached for quick delivery.
01315      *
01316      * This is used by the Install Tool to convert tables tables with non-UTF8 charsets
01317      * Use in Install Tool only!
01318      *
01319      * @return  array       Array with Charset as key and an array of "Charset", "Description", "Default collation", "Maxlen" as values
01320      */
01321     function admin_get_charsets() {
01322         $output = array();
01323 
01324         $columns_res = mysql_query('SHOW CHARACTER SET', $this->link);
01325         if ($columns_res) {
01326             while (($row = mysql_fetch_assoc($columns_res))) {
01327                 $output[$row['Charset']] = $row;
01328             }
01329 
01330             $this->sql_free_result($columns_res);
01331         }
01332 
01333         return $output;
01334     }
01335 
01336     /**
01337      * mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
01338      * Usage count/core: 10
01339      *
01340      * @param   string      Query to execute
01341      * @return  pointer     Result pointer
01342      */
01343     function admin_query($query) {
01344         $res = mysql_query($query, $this->link);
01345         if ($this->debugOutput) {
01346             $this->debug('admin_query', $query);
01347         }
01348         return $res;
01349     }
01350 
01351 
01352     /******************************
01353      *
01354      * Connecting service
01355      *
01356      ******************************/
01357 
01358     /**
01359      * Connects to database for TYPO3 sites:
01360      *
01361      * @param string $host
01362      * @param string $user
01363      * @param string $password
01364      * @param string $db
01365      * @return  void
01366      */
01367     function connectDB($host = TYPO3_db_host, $user = TYPO3_db_username, $password = TYPO3_db_password, $db = TYPO3_db) {
01368         if ($this->sql_pconnect($host, $user, $password)) {
01369             if (!$db) {
01370                 throw new RuntimeException(
01371                     'TYPO3 Fatal Error: No database selected!',
01372                     1270853882
01373                 );
01374             } elseif (!$this->sql_select_db($db)) {
01375                 throw new RuntimeException(
01376                     'TYPO3 Fatal Error: Cannot connect to the current database, "' . $db . '"!',
01377                     1270853883
01378                 );
01379             }
01380         } else {
01381             throw new RuntimeException(
01382                 'TYPO3 Fatal Error: The current username, password or host was not accepted when the connection to the database was attempted to be established!',
01383                 1270853884
01384             );
01385         }
01386     }
01387 
01388     /**
01389      * Checks if database is connected
01390      *
01391      * @return boolean
01392      */
01393     public function isConnected() {
01394         return is_resource($this->link);
01395     }
01396 
01397 
01398     /******************************
01399      *
01400      * Debugging
01401      *
01402      ******************************/
01403 
01404     /**
01405      * Debug function: Outputs error if any
01406      *
01407      * @param   string      Function calling debug()
01408      * @param   string      Last query if not last built query
01409      * @return  void
01410      */
01411     function debug($func, $query = '') {
01412 
01413         $error = $this->sql_error();
01414         if ($error || (int)$this->debugOutput === 2) {
01415             debug(
01416                 array(
01417                     'caller' => 't3lib_DB::' . $func,
01418                     'ERROR' => $error,
01419                     'lastBuiltQuery' => ($query ? $query : $this->debug_lastBuiltQuery),
01420                     'debug_backtrace' => t3lib_utility_Debug::debugTrail(),
01421                 ),
01422                 $func,
01423                     is_object($GLOBALS['error']) && @is_callable(array($GLOBALS['error'], 'debug')) ? '' : 'DB Error'
01424             );
01425         }
01426     }
01427 
01428     /**
01429      * Checks if recordset is valid and writes debugging inormation into devLog if not.
01430      *
01431      * @param   resource    $res    Recordset
01432      * @return  boolean <code>false</code> if recordset is not valid
01433      */
01434     function debug_check_recordset($res) {
01435         if (!$res) {
01436             $trace = FALSE;
01437             $msg = 'Invalid database result resource detected';
01438             $trace = debug_backtrace();
01439             array_shift($trace);
01440             $cnt = count($trace);
01441             for ($i = 0; $i < $cnt; $i++) {
01442                     // complete objects are too large for the log
01443                 if (isset($trace['object'])) {
01444                     unset($trace['object']);
01445                 }
01446             }
01447             $msg .= ': function t3lib_DB->' . $trace[0]['function'] . ' called from file ' .
01448                     substr($trace[0]['file'], strlen(PATH_site) + 2) . ' in line ' .
01449                     $trace[0]['line'];
01450             t3lib_div::sysLog($msg . '. Use a devLog extension to get more details.', 'Core/t3lib_db', 3);
01451                 // Send to devLog if enabled
01452             if (TYPO3_DLOG) {
01453                 $debugLogData = array(
01454                     'SQL Error' => $this->sql_error(),
01455                     'Backtrace' => $trace,
01456                 );
01457                 if ($this->debug_lastBuiltQuery) {
01458                     $debugLogData = array('SQL Query' => $this->debug_lastBuiltQuery) + $debugLogData;
01459                 }
01460                 t3lib_div::devLog($msg . '.', 'Core/t3lib_db', 3, $debugLogData);
01461             }
01462 
01463             return FALSE;
01464         }
01465         return TRUE;
01466     }
01467 
01468     /**
01469      * Explain select queries
01470      * If $this->explainOutput is set, SELECT queries will be explained here. Only queries with more than one possible result row will be displayed.
01471      * The output is either printed as raw HTML output or embedded into the TS admin panel (checkbox must be enabled!)
01472      *
01473      * TODO: Feature is not DBAL-compliant
01474      *
01475      * @param   string      SQL query
01476      * @param   string      Table(s) from which to select. This is what comes right after "FROM ...". Required value.
01477      * @param   integer     Number of resulting rows
01478      * @return  boolean     True if explain was run, false otherwise
01479      */
01480     protected function explain($query, $from_table, $row_count) {
01481 
01482         if ((int) $this->explainOutput == 1 || ((int) $this->explainOutput == 2 &&
01483                 t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']))
01484         ) {
01485                 // raw HTML output
01486             $explainMode = 1;
01487         } elseif ((int) $this->explainOutput == 3 && is_object($GLOBALS['TT'])) {
01488                 // embed the output into the TS admin panel
01489             $explainMode = 2;
01490         } else {
01491             return FALSE;
01492         }
01493 
01494         $error = $this->sql_error();
01495         $trail = t3lib_utility_Debug::debugTrail();
01496 
01497         $explain_tables = array();
01498         $explain_output = array();
01499         $res = $this->sql_query('EXPLAIN ' . $query, $this->link);
01500         if (is_resource($res)) {
01501             while ($tempRow = $this->sql_fetch_assoc($res)) {
01502                 $explain_output[] = $tempRow;
01503                 $explain_tables[] = $tempRow['table'];
01504             }
01505             $this->sql_free_result($res);
01506         }
01507 
01508         $indices_output = array();
01509             // Notice: Rows are skipped if there is only one result, or if no conditions are set
01510         if ($explain_output[0]['rows'] > 1 || t3lib_div::inList('ALL', $explain_output[0]['type'])) {
01511                 // only enable output if it's really useful
01512             $debug = TRUE;
01513 
01514             foreach ($explain_tables as $table) {
01515                 $tableRes = $this->sql_query('SHOW TABLE STATUS LIKE \'' . $table . '\'');
01516                 $isTable = $this->sql_num_rows($tableRes);
01517                 if ($isTable) {
01518                     $res = $this->sql_query('SHOW INDEX FROM ' . $table, $this->link);
01519                     if (is_resource($res)) {
01520                         while ($tempRow = $this->sql_fetch_assoc($res)) {
01521                             $indices_output[] = $tempRow;
01522                         }
01523                         $this->sql_free_result($res);
01524                     }
01525                 }
01526                 $this->sql_free_result($tableRes);
01527             }
01528         } else {
01529             $debug = FALSE;
01530         }
01531 
01532         if ($debug) {
01533             if ($explainMode) {
01534                 $data = array();
01535                 $data['query'] = $query;
01536                 $data['trail'] = $trail;
01537                 $data['row_count'] = $row_count;
01538 
01539                 if ($error) {
01540                     $data['error'] = $error;
01541                 }
01542                 if (count($explain_output)) {
01543                     $data['explain'] = $explain_output;
01544                 }
01545                 if (count($indices_output)) {
01546                     $data['indices'] = $indices_output;
01547                 }
01548 
01549                 if ($explainMode == 1) {
01550                     t3lib_utility_Debug::debug($data, 'Tables: ' . $from_table, 'DB SQL EXPLAIN');
01551                 } elseif ($explainMode == 2) {
01552                     $GLOBALS['TT']->setTSselectQuery($data);
01553                 }
01554             }
01555             return TRUE;
01556         }
01557 
01558         return FALSE;
01559     }
01560 
01561 }
01562 
01563 
01564 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php'])) {
01565     include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
01566 }
01567 
01568 ?>