* Cleanup: Changed all occurences of "depreciated" => "deprecated"
[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 $mmWhere = $local_table ? $local_table.'.uid='.$mm_table.'.uid_local' : '';
245 $mmWhere.= ($local_table AND $foreign_table) ? ' AND ' : '';
246 $mmWhere.= $foreign_table ? $foreign_table.'.uid='.$mm_table.'.uid_foreign' : '';
247 return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
248 $select,
249 ($local_table ? $local_table.',' : '').$mm_table.($foreign_table ? ','.$foreign_table : ''),
250 $mmWhere.' '.$whereClause, // whereClauseMightContainGroupOrderBy
251 $groupBy,
252 $orderBy,
253 $limit
254 );
255 }
256
257 /**
258 * Executes a select based on input query parts array
259 *
260 * Usage: 9
261 *
262 * @param array Query parts array
263 * @return pointer MySQL select result pointer / DBAL object
264 * @see exec_SELECTquery()
265 */
266 function exec_SELECT_queryArray($queryParts) {
267 return $this->exec_SELECTquery(
268 $queryParts['SELECT'],
269 $queryParts['FROM'],
270 $queryParts['WHERE'],
271 $queryParts['GROUPBY'],
272 $queryParts['ORDERBY'],
273 $queryParts['LIMIT']
274 );
275 }
276
277 /**
278 * Creates and executes a SELECT SQL-statement AND traverse result set and returns array with records in.
279 *
280 * @param string See exec_SELECTquery()
281 * @param string See exec_SELECTquery()
282 * @param string See exec_SELECTquery()
283 * @param string See exec_SELECTquery()
284 * @param string See exec_SELECTquery()
285 * @param string See exec_SELECTquery()
286 * @param string If set, the result array will carry this field names value as index. Requires that field to be selected of course!
287 * @return array Array of rows.
288 */
289 function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='') {
290 $res = $this->exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy,$orderBy,$limit);
291 if ($this->debugOutput) $this->debug('exec_SELECTquery');
292
293 unset($output);
294 if (!$this->sql_error()) {
295 $output = array();
296
297 if ($uidIndexField) {
298 while($tempRow = $this->sql_fetch_assoc($res)) {
299 $output[$tempRow[$uidIndexField]] = $tempRow;
300 }
301 } else {
302 while($output[] = $this->sql_fetch_assoc($res));
303 array_pop($output);
304 }
305 }
306 return $output;
307 }
308
309
310
311
312
313
314
315
316
317
318
319 /**************************************
320 *
321 * Query building
322 *
323 **************************************/
324
325 /**
326 * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
327 * Usage count/core: 4
328 *
329 * @param string See exec_INSERTquery()
330 * @param array See exec_INSERTquery()
331 * @return string Full SQL query for INSERT (unless $fields_values does not contain any elements in which case it will be false)
332 * @deprecated use exec_INSERTquery() instead if possible!
333 */
334 function INSERTquery($table,$fields_values) {
335
336 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
337 if (is_array($fields_values) && count($fields_values)) {
338
339 // Add slashes old-school:
340 foreach($fields_values as $k => $v) {
341 $fields_values[$k] = $this->fullQuoteStr($fields_values[$k], $table);
342 }
343
344 // Build query:
345 $query = 'INSERT INTO '.$table.'
346 (
347 '.implode(',
348 ',array_keys($fields_values)).'
349 ) VALUES (
350 '.implode(',
351 ',$fields_values).'
352 )';
353
354 // Return query:
355 if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
356 return $query;
357 }
358 }
359
360 /**
361 * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
362 * Usage count/core: 6
363 *
364 * @param string See exec_UPDATEquery()
365 * @param string See exec_UPDATEquery()
366 * @param array See exec_UPDATEquery()
367 * @return string Full SQL query for UPDATE (unless $fields_values does not contain any elements in which case it will be false)
368 * @deprecated use exec_UPDATEquery() instead if possible!
369 */
370 function UPDATEquery($table,$where,$fields_values) {
371
372 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function (contrary to values in the arrays which may be insecure).
373 if (is_string($where)) {
374 if (is_array($fields_values) && count($fields_values)) {
375
376 // Add slashes old-school:
377 $nArr = array();
378 foreach($fields_values as $k => $v) {
379 $nArr[] = $k.'='.$this->fullQuoteStr($v, $table);
380 }
381
382 // Build query:
383 $query = 'UPDATE '.$table.'
384 SET
385 '.implode(',
386 ',$nArr).
387 (strlen($where)>0 ? '
388 WHERE
389 '.$where : '');
390
391 // Return query:
392 if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
393 return $query;
394 }
395 } else {
396 die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !');
397 }
398 }
399
400 /**
401 * Creates a DELETE SQL-statement for $table where $where-clause
402 * Usage count/core: 3
403 *
404 * @param string See exec_DELETEquery()
405 * @param string See exec_DELETEquery()
406 * @return string Full SQL query for DELETE
407 * @deprecated use exec_DELETEquery() instead if possible!
408 */
409 function DELETEquery($table,$where) {
410 if (is_string($where)) {
411
412 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
413 $query = 'DELETE FROM '.$table.
414 (strlen($where)>0 ? '
415 WHERE
416 '.$where : '');
417
418 if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
419 return $query;
420 } else {
421 die('<strong>TYPO3 Fatal Error:</strong> "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !');
422 }
423 }
424
425 /**
426 * Creates a SELECT SQL-statement
427 * Usage count/core: 11
428 *
429 * @param string See exec_SELECTquery()
430 * @param string See exec_SELECTquery()
431 * @param string See exec_SELECTquery()
432 * @param string See exec_SELECTquery()
433 * @param string See exec_SELECTquery()
434 * @param string See exec_SELECTquery()
435 * @return string Full SQL query for SELECT
436 * @deprecated use exec_SELECTquery() instead if possible!
437 */
438 function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='') {
439
440 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
441 // Build basic query:
442 $query = 'SELECT '.$select_fields.'
443 FROM '.$from_table.
444 (strlen($where_clause)>0 ? '
445 WHERE
446 '.$where_clause : '');
447
448 // Group by:
449 if (strlen($groupBy)>0) {
450 $query.= '
451 GROUP BY '.$groupBy;
452 }
453 // Order by:
454 if (strlen($orderBy)>0) {
455 $query.= '
456 ORDER BY '.$orderBy;
457 }
458 // Group by:
459 if (strlen($limit)>0) {
460 $query.= '
461 LIMIT '.$limit;
462 }
463
464 // Return query:
465 if ($this->debugOutput || $this->store_lastBuiltQuery) $this->debug_lastBuiltQuery = $query;
466 return $query;
467 }
468
469 /**
470 * Returns a WHERE clause that can find a value ($value) in a list field ($field)
471 * 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).
472 * Is nice to look up list-relations to records or files in TYPO3 database tables.
473 *
474 * @param string Field name
475 * @param string Value to find in list
476 * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
477 * @return string WHERE clause for a query
478 */
479 function listQuery($field, $value, $table) {
480 $command = $this->quoteStr($value, $table);
481 $where = '('.$field.' LIKE \'%,'.$command.',%\' OR '.$field.' LIKE \''.$command.',%\' OR '.$field.' LIKE \'%,'.$command.'\' OR '.$field.'=\''.$command.'\')';
482 return $where;
483 }
484
485 /**
486 * 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.
487 *
488 * @param array Array of search words
489 * @param array Array of fields
490 * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
491 * @return string WHERE clause for search
492 */
493 function searchQuery($searchWords,$fields,$table) {
494 $queryParts = array();
495
496 foreach($searchWords as $sw) {
497 $like=' LIKE \'%'.$this->quoteStr($sw, $table).'%\'';
498 $queryParts[] = $table.'.'.implode($like.' OR '.$table.'.',$fields).$like;
499 }
500 $query = '('.implode(') AND (',$queryParts).')';
501 return $query ;
502 }
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519 /**************************************
520 *
521 * Various helper functions
522 *
523 * Functions recommended to be used for
524 * - escaping values,
525 * - cleaning lists of values,
526 * - stripping of excess ORDER BY/GROUP BY keywords
527 *
528 **************************************/
529
530 /**
531 * Escaping and quoting values for SQL statements.
532 * Usage count/core: 100
533 *
534 * @param string Input string
535 * @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!).
536 * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
537 * @see quoteStr()
538 */
539 function fullQuoteStr($str, $table) {
540 return '\''.mysql_real_escape_string($str, $this->link).'\'';
541 }
542
543 /**
544 * Will fullquote all values in the one-dimentional array so they are ready to "implode" for an sql query.
545 *
546 * @param array Array with values
547 * @param string Table name for which to quote.
548 * @return array The input array with all values passed through intval()
549 * @see cleanIntArray()
550 */
551 function fullQuoteArray($arr, $table) {
552 foreach($arr as $k => $v) {
553 $arr[$k] = $this->fullQuoteStr($arr[$k], $table);
554 }
555 return $arr;
556 }
557
558 /**
559 * Substitution for PHP function "addslashes()"
560 * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
561 * 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()!
562 *
563 * Usage count/core: 20
564 *
565 * @param string Input string
566 * @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!).
567 * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
568 * @see quoteStr()
569 */
570 function quoteStr($str, $table) {
571 return mysql_real_escape_string($str, $this->link);
572 }
573
574 /**
575 * Will convert all values in the one-dimentional array to integers.
576 * Useful when you want to make sure an array contains only integers before imploding them in a select-list.
577 * Usage count/core: 7
578 *
579 * @param array Array with values
580 * @return array The input array with all values passed through intval()
581 * @see cleanIntList()
582 */
583 function cleanIntArray($arr) {
584 foreach($arr as $k => $v) {
585 $arr[$k] = intval($arr[$k]);
586 }
587 return $arr;
588 }
589
590 /**
591 * Will force all entries in the input comma list to integers
592 * 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.
593 * Usage count/core: 6
594 *
595 * @param string List of comma-separated values which should be integers
596 * @return string The input list but with every value passed through intval()
597 * @see cleanIntArray()
598 */
599 function cleanIntList($list) {
600 return implode(',',t3lib_div::intExplode(',',$list));
601 }
602
603 /**
604 * Removes the prefix "ORDER BY" from the input string.
605 * 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.
606 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
607 * Usage count/core: 11
608 *
609 * @param string eg. "ORDER BY title, uid"
610 * @return string eg. "title, uid"
611 * @see exec_SELECTquery(), stripGroupBy()
612 */
613 function stripOrderBy($str) {
614 return preg_replace('/^ORDER[[:space:]]+BY[[:space:]]+/i','',trim($str));
615 }
616
617 /**
618 * Removes the prefix "GROUP BY" from the input string.
619 * 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.
620 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
621 * Usage count/core: 1
622 *
623 * @param string eg. "GROUP BY title, uid"
624 * @return string eg. "title, uid"
625 * @see exec_SELECTquery(), stripOrderBy()
626 */
627 function stripGroupBy($str) {
628 return preg_replace('/^GROUP[[:space:]]+BY[[:space:]]+/i','',trim($str));
629 }
630
631 /**
632 * 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)
633 * Work-around function for use where you know some userdefined end to an SQL clause is supplied and you need to separate these factors.
634 * Usage count/core: 13
635 *
636 * @param string Input string
637 * @return array
638 */
639 function splitGroupOrderLimit($str) {
640 $str = ' '.$str; // Prepending a space to make sure "[[:space:]]+" will find a space there for the first element.
641 // Init output array:
642 $wgolParts = array(
643 'WHERE' => '',
644 'GROUPBY' => '',
645 'ORDERBY' => '',
646 'LIMIT' => ''
647 );
648
649 // Find LIMIT:
650 if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
651 $wgolParts['LIMIT'] = trim($reg[2]);
652 $str = $reg[1];
653 }
654
655 // Find ORDER BY:
656 if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
657 $wgolParts['ORDERBY'] = trim($reg[2]);
658 $str = $reg[1];
659 }
660
661 // Find GROUP BY:
662 if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i',$str,$reg)) {
663 $wgolParts['GROUPBY'] = trim($reg[2]);
664 $str = $reg[1];
665 }
666
667 // Rest is assumed to be "WHERE" clause:
668 $wgolParts['WHERE'] = $str;
669
670 return $wgolParts;
671 }
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687 /**************************************
688 *
689 * MySQL wrapper functions
690 * (For use in your applications)
691 *
692 **************************************/
693
694 /**
695 * Executes query
696 * mysql() wrapper function
697 * DEPRECATED - use exec_* functions from this class instead!
698 * Usage count/core: 9
699 *
700 * @param string Database name
701 * @param string Query to execute
702 * @return pointer Result pointer / DBAL object
703 */
704 function sql($db,$query) {
705 $res = mysql_query($query, $this->link);
706 if ($this->debugOutput) $this->debug('sql');
707 return $res;
708 }
709
710 /**
711 * Executes query
712 * mysql_query() wrapper function
713 * Usage count/core: 1
714 *
715 * @param string Query to execute
716 * @return pointer Result pointer / DBAL object
717 */
718 function sql_query($query) {
719 $res = mysql_query($query, $this->link);
720 if ($this->debugOutput) $this->debug('sql_query');
721 return $res;
722 }
723
724 /**
725 * Returns the error status on the last sql() execution
726 * mysql_error() wrapper function
727 * Usage count/core: 32
728 *
729 * @return string MySQL error string.
730 */
731 function sql_error() {
732 return mysql_error($this->link);
733 }
734
735 /**
736 * Returns the number of selected rows.
737 * mysql_num_rows() wrapper function
738 * Usage count/core: 85
739 *
740 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
741 * @return integer Number of resulting rows.
742 */
743 function sql_num_rows($res) {
744 return mysql_num_rows($res);
745 }
746
747 /**
748 * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
749 * mysql_fetch_assoc() wrapper function
750 * Usage count/core: 307
751 *
752 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
753 * @return array Associative array of result row.
754 */
755 function sql_fetch_assoc($res) {
756 return mysql_fetch_assoc($res);
757 }
758
759 /**
760 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
761 * The array contains the values in numerical indices.
762 * mysql_fetch_row() wrapper function
763 * Usage count/core: 56
764 *
765 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
766 * @return array Array with result rows.
767 */
768 function sql_fetch_row($res) {
769 return mysql_fetch_row($res);
770 }
771
772 /**
773 * Free result memory
774 * mysql_free_result() wrapper function
775 * Usage count/core: 3
776 *
777 * @param pointer MySQL result pointer to free / DBAL object
778 * @return boolean Returns TRUE on success or FALSE on failure.
779 */
780 function sql_free_result($res) {
781 return mysql_free_result($res);
782 }
783
784 /**
785 * Get the ID generated from the previous INSERT operation
786 * mysql_insert_id() wrapper function
787 * Usage count/core: 13
788 *
789 * @return integer The uid of the last inserted record.
790 */
791 function sql_insert_id() {
792 return mysql_insert_id($this->link);
793 }
794
795 /**
796 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
797 * mysql_affected_rows() wrapper function
798 * Usage count/core: 1
799 *
800 * @return integer Number of rows affected by last query
801 */
802 function sql_affected_rows() {
803 return mysql_affected_rows($this->link);
804 }
805
806 /**
807 * Move internal result pointer
808 * mysql_data_seek() wrapper function
809 * Usage count/core: 3
810 *
811 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
812 * @param integer Seek result number.
813 * @return boolean Returns TRUE on success or FALSE on failure.
814 */
815 function sql_data_seek($res,$seek) {
816 return mysql_data_seek($res,$seek);
817 }
818
819 /**
820 * Get the type of the specified field in a result
821 * mysql_field_type() wrapper function
822 * Usage count/core: 2
823 *
824 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
825 * @param integer Field index.
826 * @return string Returns the name of the specified field index
827 */
828 function sql_field_type($res,$pointer) {
829 return mysql_field_type($res,$pointer);
830 }
831
832 /**
833 * Open a (persistent) connection to a MySQL server
834 * mysql_pconnect() wrapper function
835 * Usage count/core: 12
836 *
837 * @param string Database host IP/domain
838 * @param string Username to connect with.
839 * @param string Password to connect with.
840 * @return pointer Returns a positive MySQL persistent link identifier on success, or FALSE on error.
841 */
842 function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) {
843 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
844 $this->link = mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
845 } else {
846 $this->link = mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
847 }
848 return $this->link;
849 }
850
851 /**
852 * Select a MySQL database
853 * mysql_select_db() wrapper function
854 * Usage count/core: 8
855 *
856 * @param string Database to connect to.
857 * @return boolean Returns TRUE on success or FALSE on failure.
858 */
859 function sql_select_db($TYPO3_db) {
860 return mysql_select_db($TYPO3_db, $this->link);
861 }
862
863
864
865
866
867
868
869
870
871
872 /**************************************
873 *
874 * SQL admin functions
875 * (For use in the Install Tool and Extension Manager)
876 *
877 **************************************/
878
879 /**
880 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
881 * 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.
882 * Use in Install Tool only!
883 * Usage count/core: 1
884 *
885 * @return array Each entry represents a database name
886 */
887 function admin_get_dbs() {
888 $dbArr = array();
889 $db_list = mysql_list_dbs($this->link);
890 while ($row = mysql_fetch_object($db_list)) {
891 if ($this->sql_select_db($row->Database)) {
892 $dbArr[] = $row->Database;
893 }
894 }
895 return $dbArr;
896 }
897
898 /**
899 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
900 * 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
901 * Usage count/core: 2
902 *
903 * @return array Tables in an array (tablename is in both key and value)
904 */
905 function admin_get_tables() {
906 $whichTables = array();
907 $tables_result = mysql_list_tables(TYPO3_db, $this->link);
908 if (!mysql_error()) {
909 while ($theTable = mysql_fetch_assoc($tables_result)) {
910 $whichTables[current($theTable)] = current($theTable);
911 }
912 }
913 return $whichTables;
914 }
915
916 /**
917 * Returns information about each field in the $table (quering the DBMS)
918 * In a DBAL this should look up the right handler for the table and return compatible information
919 * 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.
920 *
921 * @param string Table name
922 * @return array Field information in an associative array with fieldname => field row
923 */
924 function admin_get_fields($tableName) {
925 $output = array();
926
927 $columns_res = mysql_query('SHOW columns FROM '.$tableName, $this->link);
928 while($fieldRow = mysql_fetch_assoc($columns_res)) {
929 $output[$fieldRow['Field']] = $fieldRow;
930 }
931
932 return $output;
933 }
934
935 /**
936 * Returns information about each index key in the $table (quering the DBMS)
937 * In a DBAL this should look up the right handler for the table and return compatible information
938 *
939 * @param string Table name
940 * @return array Key information in a numeric array
941 */
942 function admin_get_keys($tableName) {
943 $output = array();
944
945 $keyRes = mysql_query('SHOW keys FROM '.$tableName, $this->link);
946 while($keyRow = mysql_fetch_assoc($keyRes)) {
947 $output[] = $keyRow;
948 }
949
950 return $output;
951 }
952
953 /**
954 * mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
955 * Usage count/core: 10
956 *
957 * @param string Query to execute
958 * @return pointer Result pointer
959 */
960 function admin_query($query) {
961 $res = mysql_query($query, $this->link);
962 if ($this->debugOutput) $this->debug('admin_query');
963 return $res;
964 }
965
966
967
968
969
970
971
972
973
974
975 /******************************
976 *
977 * Debugging
978 *
979 ******************************/
980
981 /**
982 * Debug function: Outputs error if any
983 *
984 * @param string Function calling debug()
985 * @return void
986 */
987 function debug($func) {
988
989 $error = $this->sql_error();
990 if ($error) {
991 echo t3lib_div::view_array(array(
992 'caller' => 't3lib_DB::'.$func,
993 'ERROR' => $error,
994 'lastBuiltQuery' => $this->debug_lastBuiltQuery,
995 'debug_backtrace' => t3lib_div::debug_trail()
996 ));
997 }
998 }
999 }
1000
1001
1002 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']) {
1003 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
1004 }
1005 ?>