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