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