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