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