[BUGFIX] Throw correct Exceptions everywhere
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_db.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2004-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains the class "t3lib_db" containing functions for building SQL queries
29 * and mysql wrappers, thus providing a foundational API to all database
30 * interaction.
31 * This class is instantiated globally as $TYPO3_DB in TYPO3 scripts.
32 *
33 * $Id$
34 *
35 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
36 */
37 /**
38 * [CLASS/FUNCTION INDEX of SCRIPT]
39 *
40 *
41 *
42 * 138: class t3lib_DB
43 *
44 * SECTION: Query execution
45 * 175: function exec_INSERTquery($table,$fields_values,$no_quote_fields=FALSE)
46 * 192: function exec_UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)
47 * 206: function exec_DELETEquery($table,$where)
48 * 225: function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
49 * 250: function exec_SELECT_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
50 * 278: function exec_SELECT_queryArray($queryParts)
51 * 301: function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='')
52 *
53 * SECTION: Query building
54 * 346: function INSERTquery($table,$fields_values,$no_quote_fields=FALSE)
55 * 381: function UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)
56 * 422: function DELETEquery($table,$where)
57 * 451: function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
58 * 492: function listQuery($field, $value, $table)
59 * 506: function searchQuery($searchWords,$fields,$table)
60 *
61 * SECTION: Various helper functions
62 * 552: function fullQuoteStr($str, $table)
63 * 569: function fullQuoteArray($arr, $table, $noQuote=FALSE)
64 * 596: function quoteStr($str, $table)
65 * 612: function escapeStrForLike($str, $table)
66 * 625: function cleanIntArray($arr)
67 * 641: function cleanIntList($list)
68 * 655: function stripOrderBy($str)
69 * 669: function stripGroupBy($str)
70 * 681: function splitGroupOrderLimit($str)
71 *
72 * SECTION: MySQL wrapper functions
73 * 749: function sql($db,$query)
74 * 763: function sql_query($query)
75 * 776: function sql_error()
76 * 788: function sql_num_rows($res)
77 * 800: function sql_fetch_assoc($res)
78 * 813: function sql_fetch_row($res)
79 * 825: function sql_free_result($res)
80 * 836: function sql_insert_id()
81 * 847: function sql_affected_rows()
82 * 860: function sql_data_seek($res,$seek)
83 * 873: function sql_field_type($res,$pointer)
84 * 887: function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password)
85 * 915: function sql_select_db($TYPO3_db)
86 *
87 * SECTION: SQL admin functions
88 * 947: function admin_get_dbs()
89 * 965: function admin_get_tables()
90 * 984: function admin_get_fields($tableName)
91 * 1002: function admin_get_keys($tableName)
92 * 1020: function admin_query($query)
93 *
94 * SECTION: Connecting service
95 * 1048: function connectDB()
96 *
97 * SECTION: Debugging
98 * 1086: function debug($func)
99 *
100 * TOTAL FUNCTIONS: 42
101 * (This index is automatically created/updated by the extension "extdeveval")
102 *
103 */
104
105
106 /**
107 * TYPO3 "database wrapper" class (new in 3.6.0)
108 * This class contains
109 * - 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!)
110 * - 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!
111 * - 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!
112 * See the Project Coding Guidelines (doc_core_cgl) for more instructions on best-practise
113 *
114 * 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)
115 * ALL connectivity to the database in TYPO3 must be done through this class!
116 * The points of this class are:
117 * - To direct all database calls through this class so it becomes possible to implement DBAL with extensions.
118 * - 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...
119 * - To create an interface for DBAL implemented by extensions; (Eg. making possible escaping characters, clob/blob handling, reserved words handling)
120 * - Benchmarking the DB bottleneck queries will become much easier; Will make it easier to find optimization possibilities.
121 *
122 * USE:
123 * In all TYPO3 scripts the global variable $TYPO3_DB is an instance of this class. Use that.
124 * Eg. $GLOBALS['TYPO3_DB']->sql_fetch_assoc()
125 *
126 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
127 * @package TYPO3
128 * @subpackage t3lib
129 */
130 class t3lib_DB {
131
132
133 // Debug:
134 var $debugOutput = FALSE; // Set "TRUE" or "1" if you want database errors outputted. Set to "2" if you also want successful database actions outputted.
135 var $debug_lastBuiltQuery = ''; // Internally: Set to last built query (not necessarily executed...)
136 var $store_lastBuiltQuery = FALSE; // Set "TRUE" if you want the last built query to be stored in $debug_lastBuiltQuery independent of $this->debugOutput
137 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.
138
139 // Default link identifier:
140 var $link = FALSE;
141
142 // Default character set, applies unless character set or collation are explicitely set
143 var $default_charset = 'utf8';
144
145 /**
146 * @var t3lib_DB_preProcessQueryHook[]
147 */
148 protected $preProcessHookObjects = array();
149
150 /**
151 * @var t3lib_DB_postProcessQueryHook[]
152 */
153 protected $postProcessHookObjects = array();
154
155
156 /************************************
157 *
158 * Query execution
159 *
160 * These functions are the RECOMMENDED DBAL functions for use in your applications
161 * Using these functions will allow the DBAL to use alternative ways of accessing data (contrary to if a query is returned!)
162 * They compile a query AND execute it immediately and then return the result
163 * This principle heightens our ability to create various forms of DBAL of the functions.
164 * Generally: We want to return a result pointer/object, never queries.
165 * Also, having the table name together with the actual query execution allows us to direct the request to other databases.
166 *
167 **************************************/
168
169 /**
170 * Creates and executes an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
171 * Using this function specifically allows us to handle BLOB and CLOB fields depending on DB
172 * Usage count/core: 47
173 *
174 * @param string Table name
175 * @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.
176 * @param string/array See fullQuoteArray()
177 * @return pointer MySQL result pointer / DBAL object
178 */
179 function exec_INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
180 $res = mysql_query($this->INSERTquery($table, $fields_values, $no_quote_fields), $this->link);
181 if ($this->debugOutput) {
182 $this->debug('exec_INSERTquery');
183 }
184 foreach ($this->postProcessHookObjects as $hookObject) {
185 $hookObject->exec_INSERTquery_postProcessAction($table, $fields_values, $no_quote_fields, $this);
186 }
187 return $res;
188 }
189
190 /**
191 * Creates and executes an INSERT SQL-statement for $table with multiple rows.
192 *
193 * @param string Table name
194 * @param array Field names
195 * @param array Table rows. Each row should be an array with field values mapping to $fields
196 * @param string/array See fullQuoteArray()
197 * @return pointer MySQL result pointer / DBAL object
198 */
199 public function exec_INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
200 $res = mysql_query($this->INSERTmultipleRows($table, $fields, $rows, $no_quote_fields), $this->link);
201 if ($this->debugOutput) {
202 $this->debug('exec_INSERTmultipleRows');
203 }
204 foreach ($this->postProcessHookObjects as $hookObject) {
205 $hookObject->exec_INSERTmultipleRows_postProcessAction($table, $fields, $rows, $no_quote_fields, $this);
206 }
207 return $res;
208 }
209
210 /**
211 * Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
212 * Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
213 * Usage count/core: 50
214 *
215 * @param string Database tablename
216 * @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
217 * @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.
218 * @param string/array See fullQuoteArray()
219 * @return pointer MySQL result pointer / DBAL object
220 */
221 function exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
222 $res = mysql_query($this->UPDATEquery($table, $where, $fields_values, $no_quote_fields), $this->link);
223 if ($this->debugOutput) {
224 $this->debug('exec_UPDATEquery');
225 }
226 foreach ($this->postProcessHookObjects as $hookObject) {
227 $hookObject->exec_UPDATEquery_postProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
228 }
229 return $res;
230 }
231
232 /**
233 * Creates and executes a DELETE SQL-statement for $table where $where-clause
234 * Usage count/core: 40
235 *
236 * @param string Database tablename
237 * @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
238 * @return pointer MySQL result pointer / DBAL object
239 */
240 function exec_DELETEquery($table, $where) {
241 $res = mysql_query($this->DELETEquery($table, $where), $this->link);
242 if ($this->debugOutput) {
243 $this->debug('exec_DELETEquery');
244 }
245 foreach ($this->postProcessHookObjects as $hookObject) {
246 $hookObject->exec_DELETEquery_postProcessAction($table, $where, $this);
247 }
248 return $res;
249 }
250
251 /**
252 * Creates and executes a SELECT SQL-statement
253 * Using this function specifically allow us to handle the LIMIT feature independently of DB.
254 * Usage count/core: 340
255 *
256 * @param string List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
257 * @param string Table(s) from which to select. This is what comes right after "FROM ...". Required value.
258 * @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!
259 * @param string Optional GROUP BY field(s), if none, supply blank string.
260 * @param string Optional ORDER BY field(s), if none, supply blank string.
261 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
262 * @return pointer MySQL result pointer / DBAL object
263 */
264 function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
265 $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
266 $res = mysql_query($query, $this->link);
267
268 if ($this->debugOutput) {
269 $this->debug('exec_SELECTquery');
270 }
271 if ($this->explainOutput) {
272 $this->explain($query, $from_table, $this->sql_num_rows($res));
273 }
274
275 return $res;
276 }
277
278 /**
279 * Creates and executes a SELECT query, selecting fields ($select) from two/three tables joined
280 * 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.
281 * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
282 * 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.
283 *
284 * Usage: 12 (spec. ext. sys_action, sys_messages, sys_todos)
285 *
286 * @param string Field list for SELECT
287 * @param string Tablename, local table
288 * @param string Tablename, relation table
289 * @param string Tablename, foreign table
290 * @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!
291 * @param string Optional GROUP BY field(s), if none, supply blank string.
292 * @param string Optional ORDER BY field(s), if none, supply blank string.
293 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
294 * @return pointer MySQL result pointer / DBAL object
295 * @see exec_SELECTquery()
296 */
297 function exec_SELECT_mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
298 if ($foreign_table == $local_table) {
299 $foreign_table_as = $foreign_table . uniqid('_join');
300 }
301
302 $mmWhere = $local_table ? $local_table . '.uid=' . $mm_table . '.uid_local' : '';
303 $mmWhere .= ($local_table AND $foreign_table) ? ' AND ' : '';
304
305 $tables = ($local_table ? $local_table . ',' : '') . $mm_table;
306
307 if ($foreign_table) {
308 $mmWhere .= ($foreign_table_as ? $foreign_table_as : $foreign_table) . '.uid=' . $mm_table . '.uid_foreign';
309 $tables .= ',' . $foreign_table . ($foreign_table_as ? ' AS ' . $foreign_table_as : '');
310 }
311
312 return $this->exec_SELECTquery(
313 $select,
314 $tables,
315 // whereClauseMightContainGroupOrderBy
316 $mmWhere . ' ' . $whereClause,
317 $groupBy,
318 $orderBy,
319 $limit
320 );
321 }
322
323 /**
324 * Executes a select based on input query parts array
325 *
326 * Usage: 9
327 *
328 * @param array Query parts array
329 * @return pointer MySQL select result pointer / DBAL object
330 * @see exec_SELECTquery()
331 */
332 function exec_SELECT_queryArray($queryParts) {
333 return $this->exec_SELECTquery(
334 $queryParts['SELECT'],
335 $queryParts['FROM'],
336 $queryParts['WHERE'],
337 $queryParts['GROUPBY'],
338 $queryParts['ORDERBY'],
339 $queryParts['LIMIT']
340 );
341 }
342
343 /**
344 * Creates and executes a SELECT SQL-statement AND traverse result set and returns array with records in.
345 *
346 * @param string See exec_SELECTquery()
347 * @param string See exec_SELECTquery()
348 * @param string See exec_SELECTquery()
349 * @param string See exec_SELECTquery()
350 * @param string See exec_SELECTquery()
351 * @param string See exec_SELECTquery()
352 * @param string If set, the result array will carry this field names value as index. Requires that field to be selected of course!
353 * @return array Array of rows.
354 */
355 function exec_SELECTgetRows($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', $uidIndexField = '') {
356 $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
357 if ($this->debugOutput) {
358 $this->debug('exec_SELECTquery');
359 }
360
361 if (!$this->sql_error()) {
362 $output = array();
363
364 if ($uidIndexField) {
365 while ($tempRow = $this->sql_fetch_assoc($res)) {
366 $output[$tempRow[$uidIndexField]] = $tempRow;
367 }
368 } else {
369 while ($output[] = $this->sql_fetch_assoc($res)) {
370 ;
371 }
372 array_pop($output);
373 }
374 $this->sql_free_result($res);
375 }
376 return $output;
377 }
378
379 /**
380 * Creates and executes a SELECT SQL-statement AND gets a result set and returns an array with a single record in.
381 * LIMIT is automatically set to 1 and can not be overridden.
382 *
383 * @param string $select_fields: List of fields to select from the table.
384 * @param string $from_table: Table(s) from which to select.
385 * @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!
386 * @param string $groupBy: Optional GROUP BY field(s), if none, supply blank string.
387 * @param string $orderBy: Optional ORDER BY field(s), if none, supply blank string.
388 * @param boolean $numIndex: If set, the result will be fetched with sql_fetch_row, otherwise sql_fetch_assoc will be used.
389 * @return array Single row or NULL if it fails.
390 */
391 public function exec_SELECTgetSingleRow($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $numIndex = FALSE) {
392 $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, '1');
393 if ($this->debugOutput) {
394 $this->debug('exec_SELECTquery');
395 }
396
397 $output = NULL;
398 if ($res) {
399 if ($numIndex) {
400 $output = $this->sql_fetch_row($res);
401 } else {
402 $output = $this->sql_fetch_assoc($res);
403 }
404 $this->sql_free_result($res);
405 }
406 return $output;
407 }
408
409 /**
410 * Counts the number of rows in a table.
411 *
412 * @param string $field: Name of the field to use in the COUNT() expression (e.g. '*')
413 * @param string $table: Name of the table to count rows for
414 * @param string $where: (optional) WHERE statement of the query
415 * @return mixed Number of rows counter (integer) or false if something went wrong (boolean)
416 */
417 public function exec_SELECTcountRows($field, $table, $where = '') {
418 $count = FALSE;
419 $resultSet = $this->exec_SELECTquery('COUNT(' . $field . ')', $table, $where);
420 if ($resultSet !== FALSE) {
421 list($count) = $this->sql_fetch_row($resultSet);
422 $this->sql_free_result($resultSet);
423 }
424 return $count;
425 }
426
427 /**
428 * Truncates a table.
429 *
430 * @param string Database tablename
431 * @return mixed Result from handler
432 */
433 public function exec_TRUNCATEquery($table) {
434 $res = mysql_query($this->TRUNCATEquery($table), $this->link);
435 if ($this->debugOutput) {
436 $this->debug('exec_TRUNCATEquery');
437 }
438 foreach ($this->postProcessHookObjects as $hookObject) {
439 $hookObject->exec_TRUNCATEquery_postProcessAction($table, $this);
440 }
441 return $res;
442 }
443
444
445 /**************************************
446 *
447 * Query building
448 *
449 **************************************/
450
451 /**
452 * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
453 * Usage count/core: 4
454 *
455 * @param string See exec_INSERTquery()
456 * @param array See exec_INSERTquery()
457 * @param string/array See fullQuoteArray()
458 * @return string Full SQL query for INSERT (unless $fields_values does not contain any elements in which case it will be false)
459 */
460 function INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
461
462 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
463 // function (contrary to values in the arrays which may be insecure).
464 if (is_array($fields_values) && count($fields_values)) {
465 foreach ($this->preProcessHookObjects as $hookObject) {
466 $hookObject->INSERTquery_preProcessAction($table, $fields_values, $no_quote_fields, $this);
467 }
468
469 // quote and escape values
470 $fields_values = $this->fullQuoteArray($fields_values, $table, $no_quote_fields);
471
472 // Build query:
473 $query = 'INSERT INTO ' . $table .
474 ' (' . implode(',', array_keys($fields_values)) . ') VALUES ' .
475 '(' . implode(',', $fields_values) . ')';
476
477 // Return query:
478 if ($this->debugOutput || $this->store_lastBuiltQuery) {
479 $this->debug_lastBuiltQuery = $query;
480 }
481 return $query;
482 }
483 }
484
485 /**
486 * Creates an INSERT SQL-statement for $table with multiple rows.
487 *
488 * @param string Table name
489 * @param array Field names
490 * @param array Table rows. Each row should be an array with field values mapping to $fields
491 * @param string/array See fullQuoteArray()
492 * @return string Full SQL query for INSERT (unless $rows does not contain any elements in which case it will be false)
493 */
494 public function INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
495 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
496 // function (contrary to values in the arrays which may be insecure).
497 if (count($rows)) {
498 foreach ($this->preProcessHookObjects as $hookObject) {
499 $hookObject->INSERTmultipleRows_preProcessAction($table, $fields, $rows, $no_quote_fields, $this);
500 }
501
502 // Build query:
503 $query = 'INSERT INTO ' . $table .
504 ' (' . implode(', ', $fields) . ') VALUES ';
505
506 $rowSQL = array();
507 foreach ($rows as $row) {
508 // quote and escape values
509 $row = $this->fullQuoteArray($row, $table, $no_quote_fields);
510 $rowSQL[] = '(' . implode(', ', $row) . ')';
511 }
512
513 $query .= implode(', ', $rowSQL);
514
515 // Return query:
516 if ($this->debugOutput || $this->store_lastBuiltQuery) {
517 $this->debug_lastBuiltQuery = $query;
518 }
519
520 return $query;
521 }
522 }
523
524 /**
525 * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
526 * Usage count/core: 6
527 *
528 * @param string See exec_UPDATEquery()
529 * @param string See exec_UPDATEquery()
530 * @param array See exec_UPDATEquery()
531 * @param array See fullQuoteArray()
532 * @return string Full SQL query for UPDATE
533 */
534 function UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
535 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
536 // function (contrary to values in the arrays which may be insecure).
537 if (is_string($where)) {
538 foreach ($this->preProcessHookObjects as $hookObject) {
539 $hookObject->UPDATEquery_preProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
540 }
541
542 $fields = array();
543 if (is_array($fields_values) && count($fields_values)) {
544
545 // quote and escape values
546 $nArr = $this->fullQuoteArray($fields_values, $table, $no_quote_fields);
547
548 foreach ($nArr as $k => $v) {
549 $fields[] = $k . '=' . $v;
550 }
551 }
552
553 // Build query:
554 $query = 'UPDATE ' . $table . ' SET ' . implode(',', $fields) .
555 (strlen($where) > 0 ? ' WHERE ' . $where : '');
556
557 if ($this->debugOutput || $this->store_lastBuiltQuery) {
558 $this->debug_lastBuiltQuery = $query;
559 }
560 return $query;
561 } else {
562 throw new InvalidArgumentException(
563 'TYPO3 Fatal Error: "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !',
564 1270853880
565 );
566 }
567 }
568
569 /**
570 * Creates a DELETE SQL-statement for $table where $where-clause
571 * Usage count/core: 3
572 *
573 * @param string See exec_DELETEquery()
574 * @param string See exec_DELETEquery()
575 * @return string Full SQL query for DELETE
576 */
577 function DELETEquery($table, $where) {
578 if (is_string($where)) {
579 foreach ($this->preProcessHookObjects as $hookObject) {
580 $hookObject->DELETEquery_preProcessAction($table, $where, $this);
581 }
582
583 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
584 $query = 'DELETE FROM ' . $table .
585 (strlen($where) > 0 ? ' WHERE ' . $where : '');
586
587 if ($this->debugOutput || $this->store_lastBuiltQuery) {
588 $this->debug_lastBuiltQuery = $query;
589 }
590 return $query;
591 } else {
592 throw new InvalidArgumentException(
593 'TYPO3 Fatal Error: "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !',
594 1270853881
595 );
596 }
597 }
598
599 /**
600 * Creates a SELECT SQL-statement
601 * Usage count/core: 11
602 *
603 * @param string See exec_SELECTquery()
604 * @param string See exec_SELECTquery()
605 * @param string See exec_SELECTquery()
606 * @param string See exec_SELECTquery()
607 * @param string See exec_SELECTquery()
608 * @param string See exec_SELECTquery()
609 * @return string Full SQL query for SELECT
610 */
611 function SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
612
613 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
614 // Build basic query:
615 $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table .
616 (strlen($where_clause) > 0 ? ' WHERE ' . $where_clause : '');
617
618 // Group by:
619 $query .= (strlen($groupBy) > 0 ? ' GROUP BY ' . $groupBy : '');
620
621 // Order by:
622 $query .= (strlen($orderBy) > 0 ? ' ORDER BY ' . $orderBy : '');
623
624 // Group by:
625 $query .= (strlen($limit) > 0 ? ' LIMIT ' . $limit : '');
626
627 // Return query:
628 if ($this->debugOutput || $this->store_lastBuiltQuery) {
629 $this->debug_lastBuiltQuery = $query;
630 }
631 return $query;
632 }
633
634 /**
635 * Creates a SELECT SQL-statement to be used as subquery within another query.
636 * BEWARE: This method should not be overriden within DBAL to prevent quoting from happening.
637 *
638 * @param string $select_fields: List of fields to select from the table.
639 * @param string $from_table: Table from which to select.
640 * @param string $where_clause: Conditional WHERE statement
641 * @return string Full SQL query for SELECT
642 */
643 public function SELECTsubquery($select_fields, $from_table, $where_clause) {
644 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
645 // Build basic query:
646 $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table .
647 (strlen($where_clause) > 0 ? ' WHERE ' . $where_clause : '');
648
649 // Return query:
650 if ($this->debugOutput || $this->store_lastBuiltQuery) {
651 $this->debug_lastBuiltQuery = $query;
652 }
653
654 return $query;
655 }
656
657 /**
658 * Creates a TRUNCATE TABLE SQL-statement
659 *
660 * @param string See exec_TRUNCATEquery()
661 * @return string Full SQL query for TRUNCATE TABLE
662 */
663 public function TRUNCATEquery($table) {
664 foreach ($this->preProcessHookObjects as $hookObject) {
665 $hookObject->TRUNCATEquery_preProcessAction($table, $this);
666 }
667
668 // Table should be "SQL-injection-safe" when supplied to this function
669 // Build basic query:
670 $query = 'TRUNCATE TABLE ' . $table;
671
672 // Return query:
673 if ($this->debugOutput || $this->store_lastBuiltQuery) {
674 $this->debug_lastBuiltQuery = $query;
675 }
676
677 return $query;
678 }
679
680 /**
681 * Returns a WHERE clause that can find a value ($value) in a list field ($field)
682 * For instance a record in the database might contain a list of numbers,
683 * "34,234,5" (with no spaces between). This query would be able to select that
684 * record based on the value "34", "234" or "5" regardless of their position in
685 * the list (left, middle or right).
686 * The value must not contain a comma (,)
687 * Is nice to look up list-relations to records or files in TYPO3 database tables.
688 *
689 * @param string Field name
690 * @param string Value to find in list
691 * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
692 * @return string WHERE clause for a query
693 */
694 public function listQuery($field, $value, $table) {
695 $value = (string) $value;
696 if (strpos(',', $value) !== FALSE) {
697 throw new InvalidArgumentException('$value must not contain a comma (,) in $this->listQuery() !', 1294585862);
698 }
699 $pattern = $this->quoteStr($value, $table);
700 $where = 'FIND_IN_SET(\'' . $pattern . '\',' . $field . ')';
701 return $where;
702 }
703
704 /**
705 * 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.
706 *
707 * @param array Array of search words
708 * @param array Array of fields
709 * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
710 * @return string WHERE clause for search
711 */
712 function searchQuery($searchWords, $fields, $table) {
713 $queryParts = array();
714
715 foreach ($searchWords as $sw) {
716 $like = ' LIKE \'%' . $this->quoteStr($sw, $table) . '%\'';
717 $queryParts[] = $table . '.' . implode($like . ' OR ' . $table . '.', $fields) . $like;
718 }
719 $query = '(' . implode(') AND (', $queryParts) . ')';
720 return $query;
721 }
722
723
724 /**************************************
725 *
726 * Prepared Query Support
727 *
728 **************************************/
729
730 /**
731 * Creates a SELECT prepared SQL statement.
732 *
733 * @param string See exec_SELECTquery()
734 * @param string See exec_SELECTquery()
735 * @param string See exec_SELECTquery()
736 * @param string See exec_SELECTquery()
737 * @param string See exec_SELECTquery()
738 * @param string See exec_SELECTquery()
739 * @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.
740 * @return t3lib_db_PreparedStatement Prepared statement
741 */
742 public function prepare_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', array $input_parameters = array()) {
743 $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
744 $preparedStatement = t3lib_div::makeInstance('t3lib_db_PreparedStatement', $query, $from_table, array());
745 /* @var $preparedStatement t3lib_db_PreparedStatement */
746
747 // Bind values to parameters
748 foreach ($input_parameters as $key => $value) {
749 $preparedStatement->bindValue($key, $value, t3lib_db_PreparedStatement::PARAM_AUTOTYPE);
750 }
751
752 // Return prepared statement
753 return $preparedStatement;
754 }
755
756 /**
757 * Creates a SELECT prepared SQL statement based on input query parts array
758 *
759 * @param array Query parts array
760 * @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.
761 * @return t3lib_db_PreparedStatement Prepared statement
762 */
763 public function prepare_SELECTqueryArray(array $queryParts, array $input_parameters = array()) {
764 return $this->prepare_SELECTquery(
765 $queryParts['SELECT'],
766 $queryParts['FROM'],
767 $queryParts['WHERE'],
768 $queryParts['GROUPBY'],
769 $queryParts['ORDERBY'],
770 $queryParts['LIMIT'],
771 $input_parameters
772 );
773 }
774
775 /**
776 * Executes a prepared query.
777 * This method may only be called by t3lib_db_PreparedStatement.
778 *
779 * @param string $query The query to execute
780 * @param array $queryComponents The components of the query to execute
781 * @return pointer MySQL result pointer / DBAL object
782 * @access private
783 */
784 public function exec_PREPAREDquery($query, array $queryComponents) {
785 $res = mysql_query($query, $this->link);
786 if ($this->debugOutput) {
787 $this->debug('stmt_execute', $query);
788 }
789 return $res;
790 }
791
792
793 /**************************************
794 *
795 * Various helper functions
796 *
797 * Functions recommended to be used for
798 * - escaping values,
799 * - cleaning lists of values,
800 * - stripping of excess ORDER BY/GROUP BY keywords
801 *
802 **************************************/
803
804 /**
805 * Escaping and quoting values for SQL statements.
806 * Usage count/core: 100
807 *
808 * @param string Input string
809 * @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!).
810 * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
811 * @see quoteStr()
812 */
813 function fullQuoteStr($str, $table) {
814 return '\'' . mysql_real_escape_string($str, $this->link) . '\'';
815 }
816
817 /**
818 * Will fullquote all values in the one-dimensional array so they are ready to "implode" for an sql query.
819 *
820 * @param array Array with values (either associative or non-associative array)
821 * @param string Table name for which to quote
822 * @param string/array List/array of keys NOT to quote (eg. SQL functions) - ONLY for associative arrays
823 * @return array The input array with the values quoted
824 * @see cleanIntArray()
825 */
826 function fullQuoteArray($arr, $table, $noQuote = FALSE) {
827 if (is_string($noQuote)) {
828 $noQuote = explode(',', $noQuote);
829 // sanity check
830 } elseif (!is_array($noQuote)) {
831 $noQuote = FALSE;
832 }
833
834 foreach ($arr as $k => $v) {
835 if ($noQuote === FALSE || !in_array($k, $noQuote)) {
836 $arr[$k] = $this->fullQuoteStr($v, $table);
837 }
838 }
839 return $arr;
840 }
841
842 /**
843 * Substitution for PHP function "addslashes()"
844 * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
845 * 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()!
846 *
847 * Usage count/core: 20
848 *
849 * @param string Input string
850 * @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!).
851 * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
852 * @see quoteStr()
853 */
854 function quoteStr($str, $table) {
855 return mysql_real_escape_string($str, $this->link);
856 }
857
858 /**
859 * Escaping values for SQL LIKE statements.
860 *
861 * @param string Input string
862 * @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!).
863 * @return string Output string; % and _ will be escaped with \ (or otherwise based on DBAL handler)
864 * @see quoteStr()
865 */
866 function escapeStrForLike($str, $table) {
867 return addcslashes($str, '_%');
868 }
869
870 /**
871 * Will convert all values in the one-dimensional array to integers.
872 * Useful when you want to make sure an array contains only integers before imploding them in a select-list.
873 * Usage count/core: 7
874 *
875 * @param array Array with values
876 * @return array The input array with all values passed through intval()
877 * @see cleanIntList()
878 */
879 function cleanIntArray($arr) {
880 foreach ($arr as $k => $v) {
881 $arr[$k] = intval($arr[$k]);
882 }
883 return $arr;
884 }
885
886 /**
887 * Will force all entries in the input comma list to integers
888 * 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.
889 * Usage count/core: 6
890 *
891 * @param string List of comma-separated values which should be integers
892 * @return string The input list but with every value passed through intval()
893 * @see cleanIntArray()
894 */
895 function cleanIntList($list) {
896 return implode(',', t3lib_div::intExplode(',', $list));
897 }
898
899 /**
900 * Removes the prefix "ORDER BY" from the input string.
901 * 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.
902 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
903 * Usage count/core: 11
904 *
905 * @param string eg. "ORDER BY title, uid"
906 * @return string eg. "title, uid"
907 * @see exec_SELECTquery(), stripGroupBy()
908 */
909 function stripOrderBy($str) {
910 return preg_replace('/^ORDER[[:space:]]+BY[[:space:]]+/i', '', trim($str));
911 }
912
913 /**
914 * Removes the prefix "GROUP BY" from the input string.
915 * 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.
916 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
917 * Usage count/core: 1
918 *
919 * @param string eg. "GROUP BY title, uid"
920 * @return string eg. "title, uid"
921 * @see exec_SELECTquery(), stripOrderBy()
922 */
923 function stripGroupBy($str) {
924 return preg_replace('/^GROUP[[:space:]]+BY[[:space:]]+/i', '', trim($str));
925 }
926
927 /**
928 * 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)
929 * Work-around function for use where you know some userdefined end to an SQL clause is supplied and you need to separate these factors.
930 * Usage count/core: 13
931 *
932 * @param string Input string
933 * @return array
934 */
935 function splitGroupOrderLimit($str) {
936 // Prepending a space to make sure "[[:space:]]+" will find a space there
937 // for the first element.
938 $str = ' ' . $str;
939 // Init output array:
940 $wgolParts = array(
941 'WHERE' => '',
942 'GROUPBY' => '',
943 'ORDERBY' => '',
944 'LIMIT' => '',
945 );
946
947 // Find LIMIT:
948 $reg = array();
949 if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
950 $wgolParts['LIMIT'] = trim($reg[2]);
951 $str = $reg[1];
952 }
953
954 // Find ORDER BY:
955 $reg = array();
956 if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
957 $wgolParts['ORDERBY'] = trim($reg[2]);
958 $str = $reg[1];
959 }
960
961 // Find GROUP BY:
962 $reg = array();
963 if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
964 $wgolParts['GROUPBY'] = trim($reg[2]);
965 $str = $reg[1];
966 }
967
968 // Rest is assumed to be "WHERE" clause:
969 $wgolParts['WHERE'] = $str;
970
971 return $wgolParts;
972 }
973
974
975 /**************************************
976 *
977 * MySQL wrapper functions
978 * (For use in your applications)
979 *
980 **************************************/
981
982 /**
983 * Executes query
984 * mysql_query() wrapper function
985 * Beware: Use of this method should be avoided as it is experimentally supported by DBAL. You should consider
986 * using exec_SELECTquery() and similar methods instead.
987 * Usage count/core: 1
988 *
989 * @param string Query to execute
990 * @return pointer Result pointer / DBAL object
991 */
992 function sql_query($query) {
993 $res = mysql_query($query, $this->link);
994 if ($this->debugOutput) {
995 $this->debug('sql_query', $query);
996 }
997 return $res;
998 }
999
1000 /**
1001 * Returns the error status on the last sql() execution
1002 * mysql_error() wrapper function
1003 * Usage count/core: 32
1004 *
1005 * @return string MySQL error string.
1006 */
1007 function sql_error() {
1008 return mysql_error($this->link);
1009 }
1010
1011 /**
1012 * Returns the error number on the last sql() execution
1013 * mysql_errno() wrapper function
1014 *
1015 * @return int MySQL error number.
1016 */
1017 function sql_errno() {
1018 return mysql_errno($this->link);
1019 }
1020
1021 /**
1022 * Returns the number of selected rows.
1023 * mysql_num_rows() wrapper function
1024 * Usage count/core: 85
1025 *
1026 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1027 * @return integer Number of resulting rows
1028 */
1029 function sql_num_rows($res) {
1030 if ($this->debug_check_recordset($res)) {
1031 return mysql_num_rows($res);
1032 } else {
1033 return FALSE;
1034 }
1035 }
1036
1037 /**
1038 * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
1039 * mysql_fetch_assoc() wrapper function
1040 * Usage count/core: 307
1041 *
1042 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1043 * @return array Associative array of result row.
1044 */
1045 function sql_fetch_assoc($res) {
1046 if ($this->debug_check_recordset($res)) {
1047 return mysql_fetch_assoc($res);
1048 } else {
1049 return FALSE;
1050 }
1051 }
1052
1053 /**
1054 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
1055 * The array contains the values in numerical indices.
1056 * mysql_fetch_row() wrapper function
1057 * Usage count/core: 56
1058 *
1059 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1060 * @return array Array with result rows.
1061 */
1062 function sql_fetch_row($res) {
1063 if ($this->debug_check_recordset($res)) {
1064 return mysql_fetch_row($res);
1065 } else {
1066 return FALSE;
1067 }
1068 }
1069
1070 /**
1071 * Free result memory
1072 * mysql_free_result() wrapper function
1073 * Usage count/core: 3
1074 *
1075 * @param pointer MySQL result pointer to free / DBAL object
1076 * @return boolean Returns TRUE on success or FALSE on failure.
1077 */
1078 function sql_free_result($res) {
1079 if ($this->debug_check_recordset($res)) {
1080 return mysql_free_result($res);
1081 } else {
1082 return FALSE;
1083 }
1084 }
1085
1086 /**
1087 * Get the ID generated from the previous INSERT operation
1088 * mysql_insert_id() wrapper function
1089 * Usage count/core: 13
1090 *
1091 * @return integer The uid of the last inserted record.
1092 */
1093 function sql_insert_id() {
1094 return mysql_insert_id($this->link);
1095 }
1096
1097 /**
1098 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
1099 * mysql_affected_rows() wrapper function
1100 * Usage count/core: 1
1101 *
1102 * @return integer Number of rows affected by last query
1103 */
1104 function sql_affected_rows() {
1105 return mysql_affected_rows($this->link);
1106 }
1107
1108 /**
1109 * Move internal result pointer
1110 * mysql_data_seek() wrapper function
1111 * Usage count/core: 3
1112 *
1113 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1114 * @param integer Seek result number.
1115 * @return boolean Returns TRUE on success or FALSE on failure.
1116 */
1117 function sql_data_seek($res, $seek) {
1118 if ($this->debug_check_recordset($res)) {
1119 return mysql_data_seek($res, $seek);
1120 } else {
1121 return FALSE;
1122 }
1123 }
1124
1125 /**
1126 * Get the type of the specified field in a result
1127 * mysql_field_type() wrapper function
1128 * Usage count/core: 2
1129 *
1130 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1131 * @param integer Field index.
1132 * @return string Returns the name of the specified field index
1133 */
1134 function sql_field_type($res, $pointer) {
1135 if ($this->debug_check_recordset($res)) {
1136 return mysql_field_type($res, $pointer);
1137 } else {
1138 return FALSE;
1139 }
1140 }
1141
1142 /**
1143 * Open a (persistent) connection to a MySQL server
1144 * mysql_pconnect() wrapper function
1145 * Usage count/core: 12
1146 *
1147 * @param string Database host IP/domain
1148 * @param string Username to connect with.
1149 * @param string Password to connect with.
1150 * @return pointer Returns a positive MySQL persistent link identifier on success, or FALSE on error.
1151 */
1152 function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) {
1153 // mysql_error() is tied to an established connection
1154 // if the connection fails we need a different method to get the error message
1155 @ini_set('track_errors', 1);
1156 @ini_set('html_errors', 0);
1157
1158 // check if MySQL extension is loaded
1159 if (!extension_loaded('mysql')) {
1160 $message = 'Database Error: It seems that MySQL support for PHP is not installed!';
1161 throw new RuntimeException($message, 1271492606);
1162 }
1163
1164 // Check for client compression
1165 $isLocalhost = ($TYPO3_db_host == 'localhost' || $TYPO3_db_host == '127.0.0.1');
1166 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
1167 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
1168 // We use PHP's default value for 4th parameter (new_link), which is false.
1169 // See PHP sources, for example: file php-5.2.5/ext/mysql/php_mysql.c,
1170 // function php_mysql_do_connect(), near line 525
1171 $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, FALSE, MYSQL_CLIENT_COMPRESS);
1172 } else {
1173 $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
1174 }
1175 } else {
1176 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
1177 // See comment about 4th parameter in block above
1178 $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, MYSQL_CLIENT_COMPRESS);
1179 } else {
1180 $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
1181 }
1182 }
1183
1184 $error_msg = $php_errormsg;
1185 @ini_restore('track_errors');
1186 @ini_restore('html_errors');
1187
1188 if (!$this->link) {
1189 t3lib_div::sysLog('Could not connect to MySQL server ' . $TYPO3_db_host .
1190 ' with user ' . $TYPO3_db_username . ': ' . $error_msg,
1191 'Core',
1192 4
1193 );
1194 } else {
1195 $setDBinit = t3lib_div::trimExplode(LF, str_replace("' . LF . '", LF, $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']), TRUE);
1196 foreach ($setDBinit as $v) {
1197 if (mysql_query($v, $this->link) === FALSE) {
1198 t3lib_div::sysLog('Could not initialize DB connection with query "' . $v .
1199 '": ' . mysql_error($this->link),
1200 'Core',
1201 3
1202 );
1203 }
1204 }
1205 $this->setSqlMode();
1206 }
1207
1208 return $this->link;
1209 }
1210
1211 /**
1212 * Fixes the SQL mode by unsetting NO_BACKSLASH_ESCAPES if found.
1213 *
1214 * @return void
1215 */
1216 protected function setSqlMode() {
1217 $resource = $this->sql_query('SELECT @@SESSION.sql_mode;');
1218 if (is_resource($resource)) {
1219 $result = $this->sql_fetch_row($resource);
1220 if (isset($result[0]) && $result[0] && strpos($result[0], 'NO_BACKSLASH_ESCAPES') !== FALSE) {
1221 $modes = array_diff(
1222 t3lib_div::trimExplode(',', $result[0]),
1223 array('NO_BACKSLASH_ESCAPES')
1224 );
1225 $query = 'SET sql_mode=\'' . mysql_real_escape_string(implode(',', $modes)) . '\';';
1226 $success = $this->sql_query($query);
1227
1228 t3lib_div::sysLog(
1229 'NO_BACKSLASH_ESCAPES could not be removed from SQL mode: ' . $this->sql_error(),
1230 'Core',
1231 3
1232 );
1233 }
1234 }
1235 }
1236
1237 /**
1238 * Select a MySQL database
1239 * mysql_select_db() wrapper function
1240 * Usage count/core: 8
1241 *
1242 * @param string Database to connect to.
1243 * @return boolean Returns TRUE on success or FALSE on failure.
1244 */
1245 function sql_select_db($TYPO3_db) {
1246 $ret = @mysql_select_db($TYPO3_db, $this->link);
1247 if (!$ret) {
1248 t3lib_div::sysLog('Could not select MySQL database ' . $TYPO3_db . ': ' .
1249 mysql_error(),
1250 'Core',
1251 4
1252 );
1253 }
1254 return $ret;
1255 }
1256
1257
1258 /**************************************
1259 *
1260 * SQL admin functions
1261 * (For use in the Install Tool and Extension Manager)
1262 *
1263 **************************************/
1264
1265 /**
1266 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
1267 * This is only used as a service function in the (1-2-3 process) of the Install Tool.
1268 * In any case a lookup should be done in the _DEFAULT handler DBMS then.
1269 * Use in Install Tool only!
1270 * Usage count/core: 1
1271 *
1272 * @return array Each entry represents a database name
1273 */
1274 function admin_get_dbs() {
1275 $dbArr = array();
1276 $db_list = mysql_list_dbs($this->link);
1277 while ($row = mysql_fetch_object($db_list)) {
1278 if ($this->sql_select_db($row->Database)) {
1279 $dbArr[] = $row->Database;
1280 }
1281 }
1282 return $dbArr;
1283 }
1284
1285 /**
1286 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
1287 * In a DBAL this method should 1) look up all tables from the DBMS of
1288 * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
1289 * Usage count/core: 2
1290 *
1291 * @return array Array with tablenames as key and arrays with status information as value
1292 */
1293 function admin_get_tables() {
1294 $whichTables = array();
1295
1296 $tables_result = mysql_query('SHOW TABLE STATUS FROM `' . TYPO3_db . '`', $this->link);
1297 if (!mysql_error()) {
1298 while ($theTable = mysql_fetch_assoc($tables_result)) {
1299 $whichTables[$theTable['Name']] = $theTable;
1300 }
1301
1302 $this->sql_free_result($tables_result);
1303 }
1304
1305 return $whichTables;
1306 }
1307
1308 /**
1309 * Returns information about each field in the $table (quering the DBMS)
1310 * In a DBAL this should look up the right handler for the table and return compatible information
1311 * This function is important not only for the Install Tool but probably for
1312 * DBALs as well since they might need to look up table specific information
1313 * in order to construct correct queries. In such cases this information should
1314 * probably be cached for quick delivery.
1315 *
1316 * @param string Table name
1317 * @return array Field information in an associative array with fieldname => field row
1318 */
1319 function admin_get_fields($tableName) {
1320 $output = array();
1321
1322 $columns_res = mysql_query('SHOW COLUMNS FROM `' . $tableName . '`', $this->link);
1323 while ($fieldRow = mysql_fetch_assoc($columns_res)) {
1324 $output[$fieldRow['Field']] = $fieldRow;
1325 }
1326
1327 $this->sql_free_result($columns_res);
1328
1329 return $output;
1330 }
1331
1332 /**
1333 * Returns information about each index key in the $table (quering the DBMS)
1334 * In a DBAL this should look up the right handler for the table and return compatible information
1335 *
1336 * @param string Table name
1337 * @return array Key information in a numeric array
1338 */
1339 function admin_get_keys($tableName) {
1340 $output = array();
1341
1342 $keyRes = mysql_query('SHOW KEYS FROM `' . $tableName . '`', $this->link);
1343 while ($keyRow = mysql_fetch_assoc($keyRes)) {
1344 $output[] = $keyRow;
1345 }
1346
1347 $this->sql_free_result($keyRes);
1348
1349 return $output;
1350 }
1351
1352 /**
1353 * Returns information about the character sets supported by the current DBM
1354 * This function is important not only for the Install Tool but probably for
1355 * DBALs as well since they might need to look up table specific information
1356 * in order to construct correct queries. In such cases this information should
1357 * probably be cached for quick delivery.
1358 *
1359 * This is used by the Install Tool to convert tables tables with non-UTF8 charsets
1360 * Use in Install Tool only!
1361 *
1362 * @return array Array with Charset as key and an array of "Charset", "Description", "Default collation", "Maxlen" as values
1363 */
1364 function admin_get_charsets() {
1365 $output = array();
1366
1367 $columns_res = mysql_query('SHOW CHARACTER SET', $this->link);
1368 if ($columns_res) {
1369 while (($row = mysql_fetch_assoc($columns_res))) {
1370 $output[$row['Charset']] = $row;
1371 }
1372
1373 $this->sql_free_result($columns_res);
1374 }
1375
1376 return $output;
1377 }
1378
1379 /**
1380 * mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
1381 * Usage count/core: 10
1382 *
1383 * @param string Query to execute
1384 * @return pointer Result pointer
1385 */
1386 function admin_query($query) {
1387 $res = mysql_query($query, $this->link);
1388 if ($this->debugOutput) {
1389 $this->debug('admin_query', $query);
1390 }
1391 return $res;
1392 }
1393
1394
1395 /******************************
1396 *
1397 * Connecting service
1398 *
1399 ******************************/
1400
1401 /**
1402 * Connects to database for TYPO3 sites:
1403 *
1404 * @param string $host
1405 * @param string $user
1406 * @param string $password
1407 * @param string $db
1408 * @return void
1409 */
1410 function connectDB($host = TYPO3_db_host, $user = TYPO3_db_username, $password = TYPO3_db_password, $db = TYPO3_db) {
1411 if ($this->sql_pconnect($host, $user, $password)) {
1412 if (!$db) {
1413 throw new RuntimeException(
1414 'TYPO3 Fatal Error: No database selected!',
1415 1270853882
1416 );
1417 } elseif (!$this->sql_select_db($db)) {
1418 throw new RuntimeException(
1419 'TYPO3 Fatal Error: Cannot connect to the current database, "' . $db . '"!',
1420 1270853883
1421 );
1422 }
1423 } else {
1424 throw new RuntimeException(
1425 'TYPO3 Fatal Error: The current username, password or host was not accepted when the connection to the database was attempted to be established!',
1426 1270853884
1427 );
1428 }
1429
1430 // Prepare user defined objects (if any) for hooks which extend query methods
1431 $this->preProcessHookObjects = array();
1432 $this->postProcessHookObjects = array();
1433 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_db.php']['queryProcessors'])) {
1434 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_db.php']['queryProcessors'] as $classRef) {
1435 $hookObject = t3lib_div::getUserObj($classRef);
1436
1437 if (!($hookObject instanceof t3lib_DB_preProcessQueryHook || $hookObject instanceof t3lib_DB_postProcessQueryHook)) {
1438 throw new UnexpectedValueException('$hookObject must either implement interface t3lib_DB_preProcessQueryHook or interface t3lib_DB_postProcessQueryHook', 1299158548);
1439 }
1440 if ($hookObject instanceof t3lib_DB_preProcessQueryHook) {
1441 $this->preProcessHookObjects[] = $hookObject;
1442 }
1443 if ($hookObject instanceof t3lib_DB_postProcessQueryHook) {
1444 $this->postProcessHookObjects[] = $hookObject;
1445 }
1446 }
1447 }
1448 }
1449
1450 /**
1451 * Checks if database is connected
1452 *
1453 * @return boolean
1454 */
1455 public function isConnected() {
1456 return is_resource($this->link);
1457 }
1458
1459
1460 /******************************
1461 *
1462 * Debugging
1463 *
1464 ******************************/
1465
1466 /**
1467 * Debug function: Outputs error if any
1468 *
1469 * @param string Function calling debug()
1470 * @param string Last query if not last built query
1471 * @return void
1472 */
1473 function debug($func, $query = '') {
1474
1475 $error = $this->sql_error();
1476 if ($error || (int)$this->debugOutput === 2) {
1477 debug(
1478 array(
1479 'caller' => 't3lib_DB::' . $func,
1480 'ERROR' => $error,
1481 'lastBuiltQuery' => ($query ? $query : $this->debug_lastBuiltQuery),
1482 'debug_backtrace' => t3lib_utility_Debug::debugTrail(),
1483 ),
1484 $func,
1485 is_object($GLOBALS['error']) && @is_callable(array($GLOBALS['error'], 'debug')) ? '' : 'DB Error'
1486 );
1487 }
1488 }
1489
1490 /**
1491 * Checks if recordset is valid and writes debugging inormation into devLog if not.
1492 *
1493 * @param resource $res Recordset
1494 * @return boolean <code>false</code> if recordset is not valid
1495 */
1496 function debug_check_recordset($res) {
1497 if (!$res) {
1498 $trace = FALSE;
1499 $msg = 'Invalid database result resource detected';
1500 $trace = debug_backtrace();
1501 array_shift($trace);
1502 $cnt = count($trace);
1503 for ($i = 0; $i < $cnt; $i++) {
1504 // complete objects are too large for the log
1505 if (isset($trace['object'])) {
1506 unset($trace['object']);
1507 }
1508 }
1509 $msg .= ': function t3lib_DB->' . $trace[0]['function'] . ' called from file ' .
1510 substr($trace[0]['file'], strlen(PATH_site) + 2) . ' in line ' .
1511 $trace[0]['line'];
1512 t3lib_div::sysLog($msg . '. Use a devLog extension to get more details.', 'Core/t3lib_db', 3);
1513 // Send to devLog if enabled
1514 if (TYPO3_DLOG) {
1515 $debugLogData = array(
1516 'SQL Error' => $this->sql_error(),
1517 'Backtrace' => $trace,
1518 );
1519 if ($this->debug_lastBuiltQuery) {
1520 $debugLogData = array('SQL Query' => $this->debug_lastBuiltQuery) + $debugLogData;
1521 }
1522 t3lib_div::devLog($msg . '.', 'Core/t3lib_db', 3, $debugLogData);
1523 }
1524
1525 return FALSE;
1526 }
1527 return TRUE;
1528 }
1529
1530 /**
1531 * Explain select queries
1532 * If $this->explainOutput is set, SELECT queries will be explained here. Only queries with more than one possible result row will be displayed.
1533 * The output is either printed as raw HTML output or embedded into the TS admin panel (checkbox must be enabled!)
1534 *
1535 * TODO: Feature is not DBAL-compliant
1536 *
1537 * @param string SQL query
1538 * @param string Table(s) from which to select. This is what comes right after "FROM ...". Required value.
1539 * @param integer Number of resulting rows
1540 * @return boolean True if explain was run, false otherwise
1541 */
1542 protected function explain($query, $from_table, $row_count) {
1543
1544 if ((int) $this->explainOutput == 1 || ((int) $this->explainOutput == 2 &&
1545 t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']))
1546 ) {
1547 // raw HTML output
1548 $explainMode = 1;
1549 } elseif ((int) $this->explainOutput == 3 && is_object($GLOBALS['TT'])) {
1550 // embed the output into the TS admin panel
1551 $explainMode = 2;
1552 } else {
1553 return FALSE;
1554 }
1555
1556 $error = $this->sql_error();
1557 $trail = t3lib_utility_Debug::debugTrail();
1558
1559 $explain_tables = array();
1560 $explain_output = array();
1561 $res = $this->sql_query('EXPLAIN ' . $query, $this->link);
1562 if (is_resource($res)) {
1563 while ($tempRow = $this->sql_fetch_assoc($res)) {
1564 $explain_output[] = $tempRow;
1565 $explain_tables[] = $tempRow['table'];
1566 }
1567 $this->sql_free_result($res);
1568 }
1569
1570 $indices_output = array();
1571 // Notice: Rows are skipped if there is only one result, or if no conditions are set
1572 if ($explain_output[0]['rows'] > 1 || t3lib_div::inList('ALL', $explain_output[0]['type'])) {
1573 // only enable output if it's really useful
1574 $debug = TRUE;
1575
1576 foreach ($explain_tables as $table) {
1577 $tableRes = $this->sql_query('SHOW TABLE STATUS LIKE \'' . $table . '\'');
1578 $isTable = $this->sql_num_rows($tableRes);
1579 if ($isTable) {
1580 $res = $this->sql_query('SHOW INDEX FROM ' . $table, $this->link);
1581 if (is_resource($res)) {
1582 while ($tempRow = $this->sql_fetch_assoc($res)) {
1583 $indices_output[] = $tempRow;
1584 }
1585 $this->sql_free_result($res);
1586 }
1587 }
1588 $this->sql_free_result($tableRes);
1589 }
1590 } else {
1591 $debug = FALSE;
1592 }
1593
1594 if ($debug) {
1595 if ($explainMode) {
1596 $data = array();
1597 $data['query'] = $query;
1598 $data['trail'] = $trail;
1599 $data['row_count'] = $row_count;
1600
1601 if ($error) {
1602 $data['error'] = $error;
1603 }
1604 if (count($explain_output)) {
1605 $data['explain'] = $explain_output;
1606 }
1607 if (count($indices_output)) {
1608 $data['indices'] = $indices_output;
1609 }
1610
1611 if ($explainMode == 1) {
1612 t3lib_utility_Debug::debug($data, 'Tables: ' . $from_table, 'DB SQL EXPLAIN');
1613 } elseif ($explainMode == 2) {
1614 $GLOBALS['TT']->setTSselectQuery($data);
1615 }
1616 }
1617 return TRUE;
1618 }
1619
1620 return FALSE;
1621 }
1622
1623 }
1624
1625
1626 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php'])) {
1627 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
1628 }
1629
1630 ?>