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