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