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