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