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