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