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