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