Fixed bug #16574: PHP notices from XCLASS inclusions
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_db.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2004-2010 Kasper Skårhøj (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
29 * and mysql wrappers, thus providing a foundational API to all database
30 * interaction.
31 * This class is instantiated globally as $TYPO3_DB in TYPO3 scripts.
32 *
33 * $Id$
34 *
35 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
36 */
37 /**
38 * [CLASS/FUNCTION INDEX of SCRIPT]
39 *
40 *
41 *
42 * 138: class t3lib_DB
43 *
44 * SECTION: Query execution
45 * 175: function exec_INSERTquery($table,$fields_values,$no_quote_fields=FALSE)
46 * 192: function exec_UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)
47 * 206: function exec_DELETEquery($table,$where)
48 * 225: function exec_SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
49 * 250: function exec_SELECT_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
50 * 278: function exec_SELECT_queryArray($queryParts)
51 * 301: function exec_SELECTgetRows($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='',$uidIndexField='')
52 *
53 * SECTION: Query building
54 * 346: function INSERTquery($table,$fields_values,$no_quote_fields=FALSE)
55 * 381: function UPDATEquery($table,$where,$fields_values,$no_quote_fields=FALSE)
56 * 422: function DELETEquery($table,$where)
57 * 451: function SELECTquery($select_fields,$from_table,$where_clause,$groupBy='',$orderBy='',$limit='')
58 * 492: function listQuery($field, $value, $table)
59 * 506: function searchQuery($searchWords,$fields,$table)
60 *
61 * SECTION: Various helper functions
62 * 552: function fullQuoteStr($str, $table)
63 * 569: function fullQuoteArray($arr, $table, $noQuote=FALSE)
64 * 596: function quoteStr($str, $table)
65 * 612: function escapeStrForLike($str, $table)
66 * 625: function cleanIntArray($arr)
67 * 641: function cleanIntList($list)
68 * 655: function stripOrderBy($str)
69 * 669: function stripGroupBy($str)
70 * 681: function splitGroupOrderLimit($str)
71 *
72 * SECTION: MySQL wrapper functions
73 * 749: function sql($db,$query)
74 * 763: function sql_query($query)
75 * 776: function sql_error()
76 * 788: function sql_num_rows($res)
77 * 800: function sql_fetch_assoc($res)
78 * 813: function sql_fetch_row($res)
79 * 825: function sql_free_result($res)
80 * 836: function sql_insert_id()
81 * 847: function sql_affected_rows()
82 * 860: function sql_data_seek($res,$seek)
83 * 873: function sql_field_type($res,$pointer)
84 * 887: function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password)
85 * 915: function sql_select_db($TYPO3_db)
86 *
87 * SECTION: SQL admin functions
88 * 947: function admin_get_dbs()
89 * 965: function admin_get_tables()
90 * 984: function admin_get_fields($tableName)
91 * 1002: function admin_get_keys($tableName)
92 * 1020: function admin_query($query)
93 *
94 * SECTION: Connecting service
95 * 1048: function connectDB()
96 *
97 * SECTION: Debugging
98 * 1086: function debug($func)
99 *
100 * TOTAL FUNCTIONS: 42
101 * (This index is automatically created/updated by the extension "extdeveval")
102 *
103 */
104
105
106 /**
107 * TYPO3 "database wrapper" class (new in 3.6.0)
108 * This class contains
109 * - 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!)
110 * - 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!
111 * - 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!
112 * See the Project Coding Guidelines (doc_core_cgl) for more instructions on best-practise
113 *
114 * 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)
115 * ALL connectivity to the database in TYPO3 must be done through this class!
116 * The points of this class are:
117 * - To direct all database calls through this class so it becomes possible to implement DBAL with extensions.
118 * - 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...
119 * - To create an interface for DBAL implemented by extensions; (Eg. making possible escaping characters, clob/blob handling, reserved words handling)
120 * - Benchmarking the DB bottleneck queries will become much easier; Will make it easier to find optimization possibilities.
121 *
122 * USE:
123 * In all TYPO3 scripts the global variable $TYPO3_DB is an instance of this class. Use that.
124 * Eg. $GLOBALS['TYPO3_DB']->sql_fetch_assoc()
125 *
126 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
127 * @package TYPO3
128 * @subpackage t3lib
129 */
130 class t3lib_DB {
131
132
133 // Debug:
134 var $debugOutput = FALSE; // Set "TRUE" if you want database errors outputted.
135 var $debug_lastBuiltQuery = ''; // Internally: Set to last built query (not necessarily executed...)
136 var $store_lastBuiltQuery = FALSE; // Set "TRUE" if you want the last built query to be stored in $debug_lastBuiltQuery independent of $this->debugOutput
137 var $explainOutput = 0; // Set this to 1 to get queries explained (devIPmask must match). Set the value to 2 to the same but disregarding the devIPmask. There is an alternative option to enable explain output in the admin panel under "TypoScript", which will produce much nicer output, but only works in FE.
138
139 // Default link identifier:
140 var $link = FALSE;
141
142 // Default character set, applies unless character set or collation are explicitely set
143 var $default_charset = 'utf8';
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 * @param string/array See fullQuoteArray()
167 * @return pointer MySQL result pointer / DBAL object
168 */
169 function exec_INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
170 $res = mysql_query($this->INSERTquery($table, $fields_values, $no_quote_fields), $this->link);
171 if ($this->debugOutput) {
172 $this->debug('exec_INSERTquery');
173 }
174 return $res;
175 }
176
177 /**
178 * Creates and executes an INSERT SQL-statement for $table with multiple rows.
179 *
180 * @param string Table name
181 * @param array Field names
182 * @param array Table rows. Each row should be an array with field values mapping to $fields
183 * @param string/array See fullQuoteArray()
184 * @return pointer MySQL result pointer / DBAL object
185 */
186 public function exec_INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
187 $res = mysql_query($this->INSERTmultipleRows($table, $fields, $rows, $no_quote_fields), $this->link);
188 if ($this->debugOutput) {
189 $this->debug('exec_INSERTmultipleRows');
190 }
191 return $res;
192 }
193
194 /**
195 * Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
196 * Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
197 * Usage count/core: 50
198 *
199 * @param string Database tablename
200 * @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
201 * @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.
202 * @param string/array See fullQuoteArray()
203 * @return pointer MySQL result pointer / DBAL object
204 */
205 function exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
206 $res = mysql_query($this->UPDATEquery($table, $where, $fields_values, $no_quote_fields), $this->link);
207 if ($this->debugOutput) {
208 $this->debug('exec_UPDATEquery');
209 }
210 return $res;
211 }
212
213 /**
214 * Creates and executes a DELETE SQL-statement for $table where $where-clause
215 * Usage count/core: 40
216 *
217 * @param string Database tablename
218 * @param string WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
219 * @return pointer MySQL result pointer / DBAL object
220 */
221 function exec_DELETEquery($table, $where) {
222 $res = mysql_query($this->DELETEquery($table, $where), $this->link);
223 if ($this->debugOutput) {
224 $this->debug('exec_DELETEquery');
225 }
226 return $res;
227 }
228
229 /**
230 * Creates and executes a SELECT SQL-statement
231 * Using this function specifically allow us to handle the LIMIT feature independently of DB.
232 * Usage count/core: 340
233 *
234 * @param string List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
235 * @param string Table(s) from which to select. This is what comes right after "FROM ...". Required value.
236 * @param string Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself! DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
237 * @param string Optional GROUP BY field(s), if none, supply blank string.
238 * @param string Optional ORDER BY field(s), if none, supply blank string.
239 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
240 * @return pointer MySQL result pointer / DBAL object
241 */
242 function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
243 $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
244 $res = mysql_query($query, $this->link);
245
246 if ($this->debugOutput) {
247 $this->debug('exec_SELECTquery');
248 }
249 if ($this->explainOutput) {
250 $this->explain($query, $from_table, $this->sql_num_rows($res));
251 }
252
253 return $res;
254 }
255
256 /**
257 * Creates and executes a SELECT query, selecting fields ($select) from two/three tables joined
258 * 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.
259 * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
260 * 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.
261 *
262 * Usage: 12 (spec. ext. sys_action, sys_messages, sys_todos)
263 *
264 * @param string Field list for SELECT
265 * @param string Tablename, local table
266 * @param string Tablename, relation table
267 * @param string Tablename, foreign table
268 * @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! You have to prepend 'AND ' to this parameter yourself!
269 * @param string Optional GROUP BY field(s), if none, supply blank string.
270 * @param string Optional ORDER BY field(s), if none, supply blank string.
271 * @param string Optional LIMIT value ([begin,]max), if none, supply blank string.
272 * @return pointer MySQL result pointer / DBAL object
273 * @see exec_SELECTquery()
274 */
275 function exec_SELECT_mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
276 if ($foreign_table == $local_table) {
277 $foreign_table_as = $foreign_table . uniqid('_join');
278 }
279
280 $mmWhere = $local_table ? $local_table . '.uid=' . $mm_table . '.uid_local' : '';
281 $mmWhere .= ($local_table AND $foreign_table) ? ' AND ' : '';
282
283 $tables = ($local_table ? $local_table . ',' : '') . $mm_table;
284
285 if ($foreign_table) {
286 $mmWhere .= ($foreign_table_as ? $foreign_table_as : $foreign_table) . '.uid=' . $mm_table . '.uid_foreign';
287 $tables .= ',' . $foreign_table . ($foreign_table_as ? ' AS ' . $foreign_table_as : '');
288 }
289
290 return $this->exec_SELECTquery(
291 $select,
292 $tables,
293 // whereClauseMightContainGroupOrderBy
294 $mmWhere . ' ' . $whereClause,
295 $groupBy,
296 $orderBy,
297 $limit
298 );
299 }
300
301 /**
302 * Executes a select based on input query parts array
303 *
304 * Usage: 9
305 *
306 * @param array Query parts array
307 * @return pointer MySQL select result pointer / DBAL object
308 * @see exec_SELECTquery()
309 */
310 function exec_SELECT_queryArray($queryParts) {
311 return $this->exec_SELECTquery(
312 $queryParts['SELECT'],
313 $queryParts['FROM'],
314 $queryParts['WHERE'],
315 $queryParts['GROUPBY'],
316 $queryParts['ORDERBY'],
317 $queryParts['LIMIT']
318 );
319 }
320
321 /**
322 * Creates and executes a SELECT SQL-statement AND traverse result set and returns array with records in.
323 *
324 * @param string See exec_SELECTquery()
325 * @param string See exec_SELECTquery()
326 * @param string See exec_SELECTquery()
327 * @param string See exec_SELECTquery()
328 * @param string See exec_SELECTquery()
329 * @param string See exec_SELECTquery()
330 * @param string If set, the result array will carry this field names value as index. Requires that field to be selected of course!
331 * @return array Array of rows.
332 */
333 function exec_SELECTgetRows($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', $uidIndexField = '') {
334 $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
335 if ($this->debugOutput) {
336 $this->debug('exec_SELECTquery');
337 }
338
339 if (!$this->sql_error()) {
340 $output = array();
341
342 if ($uidIndexField) {
343 while ($tempRow = $this->sql_fetch_assoc($res)) {
344 $output[$tempRow[$uidIndexField]] = $tempRow;
345 }
346 } else {
347 while ($output[] = $this->sql_fetch_assoc($res)) {
348 ;
349 }
350 array_pop($output);
351 }
352 $this->sql_free_result($res);
353 }
354 return $output;
355 }
356
357 /**
358 * Creates and executes a SELECT SQL-statement AND gets a result set and returns an array with a single record in.
359 * LIMIT is automatically set to 1 and can not be overridden.
360 *
361 * @param string $select_fields: List of fields to select from the table.
362 * @param string $from_table: Table(s) from which to select.
363 * @param string $where_clause: Optional additional WHERE clauses put in the end of the query. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
364 * @param string $groupBy: Optional GROUP BY field(s), if none, supply blank string.
365 * @param string $orderBy: Optional ORDER BY field(s), if none, supply blank string.
366 * @param boolean $numIndex: If set, the result will be fetched with sql_fetch_row, otherwise sql_fetch_assoc will be used.
367 * @return array Single row or NULL if it fails.
368 */
369 public function exec_SELECTgetSingleRow($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $numIndex = FALSE) {
370 $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, '1');
371 if ($this->debugOutput) {
372 $this->debug('exec_SELECTquery');
373 }
374
375 $output = NULL;
376 if ($res) {
377 if ($numIndex) {
378 $output = $this->sql_fetch_row($res);
379 } else {
380 $output = $this->sql_fetch_assoc($res);
381 }
382 $this->sql_free_result($res);
383 }
384 return $output;
385 }
386
387 /**
388 * Counts the number of rows in a table.
389 *
390 * @param string $field: Name of the field to use in the COUNT() expression (e.g. '*')
391 * @param string $table: Name of the table to count rows for
392 * @param string $where: (optional) WHERE statement of the query
393 * @return mixed Number of rows counter (integer) or false if something went wrong (boolean)
394 */
395 public function exec_SELECTcountRows($field, $table, $where = '') {
396 $count = FALSE;
397 $resultSet = $this->exec_SELECTquery('COUNT(' . $field . ')', $table, $where);
398 if ($resultSet !== FALSE) {
399 list($count) = $this->sql_fetch_row($resultSet);
400 $this->sql_free_result($resultSet);
401 }
402 return $count;
403 }
404
405 /**
406 * Truncates a table.
407 *
408 * @param string Database tablename
409 * @return mixed Result from handler
410 */
411 public function exec_TRUNCATEquery($table) {
412 $res = mysql_query($this->TRUNCATEquery($table), $this->link);
413 if ($this->debugOutput) {
414 $this->debug('exec_TRUNCATEquery');
415 }
416 return $res;
417 }
418
419
420 /**************************************
421 *
422 * Query building
423 *
424 **************************************/
425
426 /**
427 * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
428 * Usage count/core: 4
429 *
430 * @param string See exec_INSERTquery()
431 * @param array See exec_INSERTquery()
432 * @param string/array See fullQuoteArray()
433 * @return string Full SQL query for INSERT (unless $fields_values does not contain any elements in which case it will be false)
434 */
435 function INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
436
437 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
438 // function (contrary to values in the arrays which may be insecure).
439 if (is_array($fields_values) && count($fields_values)) {
440
441 // quote and escape values
442 $fields_values = $this->fullQuoteArray($fields_values, $table, $no_quote_fields);
443
444 // Build query:
445 $query = 'INSERT INTO ' . $table .
446 ' (' . implode(',', array_keys($fields_values)) . ') VALUES ' .
447 '(' . implode(',', $fields_values) . ')';
448
449 // Return query:
450 if ($this->debugOutput || $this->store_lastBuiltQuery) {
451 $this->debug_lastBuiltQuery = $query;
452 }
453 return $query;
454 }
455 }
456
457 /**
458 * Creates an INSERT SQL-statement for $table with multiple rows.
459 *
460 * @param string Table name
461 * @param array Field names
462 * @param array Table rows. Each row should be an array with field values mapping to $fields
463 * @param string/array See fullQuoteArray()
464 * @return string Full SQL query for INSERT (unless $rows does not contain any elements in which case it will be false)
465 */
466 public function INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
467 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
468 // function (contrary to values in the arrays which may be insecure).
469 if (count($rows)) {
470 // Build query:
471 $query = 'INSERT INTO ' . $table .
472 ' (' . implode(', ', $fields) . ') VALUES ';
473
474 $rowSQL = array();
475 foreach ($rows as $row) {
476 // quote and escape values
477 $row = $this->fullQuoteArray($row, $table, $no_quote_fields);
478 $rowSQL[] = '(' . implode(', ', $row) . ')';
479 }
480
481 $query .= implode(', ', $rowSQL);
482
483 // Return query:
484 if ($this->debugOutput || $this->store_lastBuiltQuery) {
485 $this->debug_lastBuiltQuery = $query;
486 }
487
488 return $query;
489 }
490 }
491
492 /**
493 * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
494 * Usage count/core: 6
495 *
496 * @param string See exec_UPDATEquery()
497 * @param string See exec_UPDATEquery()
498 * @param array See exec_UPDATEquery()
499 * @param array See fullQuoteArray()
500 * @return string Full SQL query for UPDATE
501 */
502 function UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
503 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
504 // function (contrary to values in the arrays which may be insecure).
505 if (is_string($where)) {
506 $fields = array();
507 if (is_array($fields_values) && count($fields_values)) {
508
509 // quote and escape values
510 $nArr = $this->fullQuoteArray($fields_values, $table, $no_quote_fields);
511
512 foreach ($nArr as $k => $v) {
513 $fields[] = $k . '=' . $v;
514 }
515 }
516
517 // Build query:
518 $query = 'UPDATE ' . $table . ' SET ' . implode(',', $fields) .
519 (strlen($where) > 0 ? ' WHERE ' . $where : '');
520
521 if ($this->debugOutput || $this->store_lastBuiltQuery) {
522 $this->debug_lastBuiltQuery = $query;
523 }
524 return $query;
525 } else {
526 throw new InvalidArgumentException(
527 'TYPO3 Fatal Error: "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !',
528 1270853880
529 );
530 }
531 }
532
533 /**
534 * Creates a DELETE SQL-statement for $table where $where-clause
535 * Usage count/core: 3
536 *
537 * @param string See exec_DELETEquery()
538 * @param string See exec_DELETEquery()
539 * @return string Full SQL query for DELETE
540 */
541 function DELETEquery($table, $where) {
542 if (is_string($where)) {
543
544 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
545 $query = 'DELETE FROM ' . $table .
546 (strlen($where) > 0 ? ' WHERE ' . $where : '');
547
548 if ($this->debugOutput || $this->store_lastBuiltQuery) {
549 $this->debug_lastBuiltQuery = $query;
550 }
551 return $query;
552 } else {
553 throw new InvalidArgumentException(
554 'TYPO3 Fatal Error: "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !',
555 1270853881
556 );
557 }
558 }
559
560 /**
561 * Creates a SELECT SQL-statement
562 * Usage count/core: 11
563 *
564 * @param string See exec_SELECTquery()
565 * @param string See exec_SELECTquery()
566 * @param string See exec_SELECTquery()
567 * @param string See exec_SELECTquery()
568 * @param string See exec_SELECTquery()
569 * @param string See exec_SELECTquery()
570 * @return string Full SQL query for SELECT
571 */
572 function SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
573
574 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
575 // Build basic query:
576 $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table .
577 (strlen($where_clause) > 0 ? ' WHERE ' . $where_clause : '');
578
579 // Group by:
580 $query .= (strlen($groupBy) > 0 ? ' GROUP BY ' . $groupBy : '');
581
582 // Order by:
583 $query .= (strlen($orderBy) > 0 ? ' ORDER BY ' . $orderBy : '');
584
585 // Group by:
586 $query .= (strlen($limit) > 0 ? ' LIMIT ' . $limit : '');
587
588 // Return query:
589 if ($this->debugOutput || $this->store_lastBuiltQuery) {
590 $this->debug_lastBuiltQuery = $query;
591 }
592 return $query;
593 }
594
595 /**
596 * Creates a SELECT SQL-statement to be used as subquery within another query.
597 * BEWARE: This method should not be overriden within DBAL to prevent quoting from happening.
598 *
599 * @param string $select_fields: List of fields to select from the table.
600 * @param string $from_table: Table from which to select.
601 * @param string $where_clause: Conditional WHERE statement
602 * @return string Full SQL query for SELECT
603 */
604 public function SELECTsubquery($select_fields, $from_table, $where_clause) {
605 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
606 // Build basic query:
607 $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table .
608 (strlen($where_clause) > 0 ? ' WHERE ' . $where_clause : '');
609
610 // Return query:
611 if ($this->debugOutput || $this->store_lastBuiltQuery) {
612 $this->debug_lastBuiltQuery = $query;
613 }
614
615 return $query;
616 }
617
618 /**
619 * Creates a TRUNCATE TABLE SQL-statement
620 *
621 * @param string See exec_TRUNCATEquery()
622 * @return string Full SQL query for TRUNCATE TABLE
623 */
624 public function TRUNCATEquery($table) {
625 // Table should be "SQL-injection-safe" when supplied to this function
626 // Build basic query:
627 $query = 'TRUNCATE TABLE ' . $table;
628
629 // Return query:
630 if ($this->debugOutput || $this->store_lastBuiltQuery) {
631 $this->debug_lastBuiltQuery = $query;
632 }
633
634 return $query;
635 }
636
637 /**
638 * Returns a WHERE clause that can find a value ($value) in a list field ($field)
639 * For instance a record in the database might contain a list of numbers,
640 * "34,234,5" (with no spaces between). This query would be able to select that
641 * record based on the value "34", "234" or "5" regardless of their position in
642 * the list (left, middle or right).
643 * The value must not contain a comma (,)
644 * Is nice to look up list-relations to records or files in TYPO3 database tables.
645 *
646 * @param string Field name
647 * @param string Value to find in list
648 * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
649 * @return string WHERE clause for a query
650 */
651 public function listQuery($field, $value, $table) {
652 $value = (string) $value;
653 if (strpos(',', $value) !== FALSE) {
654 throw new InvalidArgumentException('$value must not contain a comma (,) in $this->listQuery() !');
655 }
656 $pattern = $this->quoteStr($value, $table);
657 $where = 'FIND_IN_SET(\'' . $pattern . '\',' . $field . ')';
658 return $where;
659 }
660
661 /**
662 * 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.
663 *
664 * @param array Array of search words
665 * @param array Array of fields
666 * @param string Table in which we are searching (for DBAL detection of quoteStr() method)
667 * @return string WHERE clause for search
668 */
669 function searchQuery($searchWords, $fields, $table) {
670 $queryParts = array();
671
672 foreach ($searchWords as $sw) {
673 $like = ' LIKE \'%' . $this->quoteStr($sw, $table) . '%\'';
674 $queryParts[] = $table . '.' . implode($like . ' OR ' . $table . '.', $fields) . $like;
675 }
676 $query = '(' . implode(') AND (', $queryParts) . ')';
677 return $query;
678 }
679
680
681 /**************************************
682 *
683 * Prepared Query Support
684 *
685 **************************************/
686
687 /**
688 * Creates a SELECT prepared SQL statement.
689 *
690 * @param string See exec_SELECTquery()
691 * @param string See exec_SELECTquery()
692 * @param string See exec_SELECTquery()
693 * @param string See exec_SELECTquery()
694 * @param string See exec_SELECTquery()
695 * @param string See exec_SELECTquery()
696 * @param array $input_parameters An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as t3lib_db_PreparedStatement::PARAM_AUTOTYPE.
697 * @return t3lib_db_PreparedStatement Prepared statement
698 */
699 public function prepare_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', array $input_parameters = array()) {
700 $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
701 $preparedStatement = t3lib_div::makeInstance('t3lib_db_PreparedStatement', $query, $from_table, array());
702 /* @var $preparedStatement t3lib_db_PreparedStatement */
703
704 // Bind values to parameters
705 foreach ($input_parameters as $key => $value) {
706 $preparedStatement->bindValue($key, $value, t3lib_db_PreparedStatement::PARAM_AUTOTYPE);
707 }
708
709 // Return prepared statement
710 return $preparedStatement;
711 }
712
713 /**
714 * Creates a SELECT prepared SQL statement based on input query parts array
715 *
716 * @param array Query parts array
717 * @param array $input_parameters An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as t3lib_db_PreparedStatement::PARAM_AUTOTYPE.
718 * @return t3lib_db_PreparedStatement Prepared statement
719 */
720 public function prepare_SELECTqueryArray(array $queryParts, array $input_parameters = array()) {
721 return $this->prepare_SELECTquery(
722 $queryParts['SELECT'],
723 $queryParts['FROM'],
724 $queryParts['WHERE'],
725 $queryParts['GROUPBY'],
726 $queryParts['ORDERBY'],
727 $queryParts['LIMIT'],
728 $input_parameters
729 );
730 }
731
732 /**
733 * Executes a prepared query.
734 * This method may only be called by t3lib_db_PreparedStatement.
735 *
736 * @param string $query The query to execute
737 * @param array $queryComponents The components of the query to execute
738 * @return pointer MySQL result pointer / DBAL object
739 * @access private
740 */
741 public function exec_PREPAREDquery($query, array $queryComponents) {
742 $res = mysql_query($query, $this->link);
743 if ($this->debugOutput) {
744 $this->debug('stmt_execute', $query);
745 }
746 return $res;
747 }
748
749
750 /**************************************
751 *
752 * Various helper functions
753 *
754 * Functions recommended to be used for
755 * - escaping values,
756 * - cleaning lists of values,
757 * - stripping of excess ORDER BY/GROUP BY keywords
758 *
759 **************************************/
760
761 /**
762 * Escaping and quoting values for SQL statements.
763 * Usage count/core: 100
764 *
765 * @param string Input string
766 * @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!).
767 * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
768 * @see quoteStr()
769 */
770 function fullQuoteStr($str, $table) {
771 return '\'' . mysql_real_escape_string($str, $this->link) . '\'';
772 }
773
774 /**
775 * Will fullquote all values in the one-dimensional array so they are ready to "implode" for an sql query.
776 *
777 * @param array Array with values (either associative or non-associative array)
778 * @param string Table name for which to quote
779 * @param string/array List/array of keys NOT to quote (eg. SQL functions) - ONLY for associative arrays
780 * @return array The input array with the values quoted
781 * @see cleanIntArray()
782 */
783 function fullQuoteArray($arr, $table, $noQuote = FALSE) {
784 if (is_string($noQuote)) {
785 $noQuote = explode(',', $noQuote);
786 // sanity check
787 } elseif (!is_array($noQuote)) {
788 $noQuote = FALSE;
789 }
790
791 foreach ($arr as $k => $v) {
792 if ($noQuote === FALSE || !in_array($k, $noQuote)) {
793 $arr[$k] = $this->fullQuoteStr($v, $table);
794 }
795 }
796 return $arr;
797 }
798
799 /**
800 * Substitution for PHP function "addslashes()"
801 * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
802 * 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()!
803 *
804 * Usage count/core: 20
805 *
806 * @param string Input string
807 * @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!).
808 * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
809 * @see quoteStr()
810 */
811 function quoteStr($str, $table) {
812 return mysql_real_escape_string($str, $this->link);
813 }
814
815 /**
816 * Escaping values for SQL LIKE statements.
817 *
818 * @param string Input string
819 * @param string Table name for which to escape 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!).
820 * @return string Output string; % and _ will be escaped with \ (or otherwise based on DBAL handler)
821 * @see quoteStr()
822 */
823 function escapeStrForLike($str, $table) {
824 return addcslashes($str, '_%');
825 }
826
827 /**
828 * Will convert all values in the one-dimensional array to integers.
829 * Useful when you want to make sure an array contains only integers before imploding them in a select-list.
830 * Usage count/core: 7
831 *
832 * @param array Array with values
833 * @return array The input array with all values passed through intval()
834 * @see cleanIntList()
835 */
836 function cleanIntArray($arr) {
837 foreach ($arr as $k => $v) {
838 $arr[$k] = intval($arr[$k]);
839 }
840 return $arr;
841 }
842
843 /**
844 * Will force all entries in the input comma list to integers
845 * 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.
846 * Usage count/core: 6
847 *
848 * @param string List of comma-separated values which should be integers
849 * @return string The input list but with every value passed through intval()
850 * @see cleanIntArray()
851 */
852 function cleanIntList($list) {
853 return implode(',', t3lib_div::intExplode(',', $list));
854 }
855
856 /**
857 * Removes the prefix "ORDER BY" from the input string.
858 * 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.
859 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
860 * Usage count/core: 11
861 *
862 * @param string eg. "ORDER BY title, uid"
863 * @return string eg. "title, uid"
864 * @see exec_SELECTquery(), stripGroupBy()
865 */
866 function stripOrderBy($str) {
867 return preg_replace('/^ORDER[[:space:]]+BY[[:space:]]+/i', '', trim($str));
868 }
869
870 /**
871 * Removes the prefix "GROUP BY" from the input string.
872 * 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.
873 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
874 * Usage count/core: 1
875 *
876 * @param string eg. "GROUP BY title, uid"
877 * @return string eg. "title, uid"
878 * @see exec_SELECTquery(), stripOrderBy()
879 */
880 function stripGroupBy($str) {
881 return preg_replace('/^GROUP[[:space:]]+BY[[:space:]]+/i', '', trim($str));
882 }
883
884 /**
885 * 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)
886 * Work-around function for use where you know some userdefined end to an SQL clause is supplied and you need to separate these factors.
887 * Usage count/core: 13
888 *
889 * @param string Input string
890 * @return array
891 */
892 function splitGroupOrderLimit($str) {
893 // Prepending a space to make sure "[[:space:]]+" will find a space there
894 // for the first element.
895 $str = ' ' . $str;
896 // Init output array:
897 $wgolParts = array(
898 'WHERE' => '',
899 'GROUPBY' => '',
900 'ORDERBY' => '',
901 'LIMIT' => '',
902 );
903
904 // Find LIMIT:
905 $reg = array();
906 if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
907 $wgolParts['LIMIT'] = trim($reg[2]);
908 $str = $reg[1];
909 }
910
911 // Find ORDER BY:
912 $reg = array();
913 if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
914 $wgolParts['ORDERBY'] = trim($reg[2]);
915 $str = $reg[1];
916 }
917
918 // Find GROUP BY:
919 $reg = array();
920 if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
921 $wgolParts['GROUPBY'] = trim($reg[2]);
922 $str = $reg[1];
923 }
924
925 // Rest is assumed to be "WHERE" clause:
926 $wgolParts['WHERE'] = $str;
927
928 return $wgolParts;
929 }
930
931
932 /**************************************
933 *
934 * MySQL wrapper functions
935 * (For use in your applications)
936 *
937 **************************************/
938
939 /**
940 * Executes query
941 * mysql() wrapper function
942 * Usage count/core: 0
943 *
944 * @param string Database name
945 * @param string Query to execute
946 * @return pointer Result pointer / DBAL object
947 * @deprecated since TYPO3 3.6, will be removed in TYPO3 4.6
948 * @see sql_query()
949 */
950 function sql($db, $query) {
951 t3lib_div::logDeprecatedFunction();
952
953 $res = mysql_query($query, $this->link);
954 if ($this->debugOutput) {
955 $this->debug('sql', $query);
956 }
957 return $res;
958 }
959
960 /**
961 * Executes query
962 * mysql_query() wrapper function
963 * Beware: Use of this method should be avoided as it is experimentally supported by DBAL. You should consider
964 * using exec_SELECTquery() and similar methods instead.
965 * Usage count/core: 1
966 *
967 * @param string Query to execute
968 * @return pointer Result pointer / DBAL object
969 */
970 function sql_query($query) {
971 $res = mysql_query($query, $this->link);
972 if ($this->debugOutput) {
973 $this->debug('sql_query', $query);
974 }
975 return $res;
976 }
977
978 /**
979 * Returns the error status on the last sql() execution
980 * mysql_error() wrapper function
981 * Usage count/core: 32
982 *
983 * @return string MySQL error string.
984 */
985 function sql_error() {
986 return mysql_error($this->link);
987 }
988
989 /**
990 * Returns the error number on the last sql() execution
991 * mysql_errno() wrapper function
992 *
993 * @return int MySQL error number.
994 */
995 function sql_errno() {
996 return mysql_errno($this->link);
997 }
998
999 /**
1000 * Returns the number of selected rows.
1001 * mysql_num_rows() wrapper function
1002 * Usage count/core: 85
1003 *
1004 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1005 * @return integer Number of resulting rows
1006 */
1007 function sql_num_rows($res) {
1008 if ($this->debug_check_recordset($res)) {
1009 return mysql_num_rows($res);
1010 } else {
1011 return FALSE;
1012 }
1013 }
1014
1015 /**
1016 * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
1017 * mysql_fetch_assoc() wrapper function
1018 * Usage count/core: 307
1019 *
1020 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1021 * @return array Associative array of result row.
1022 */
1023 function sql_fetch_assoc($res) {
1024 if ($this->debug_check_recordset($res)) {
1025 return mysql_fetch_assoc($res);
1026 } else {
1027 return FALSE;
1028 }
1029 }
1030
1031 /**
1032 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
1033 * The array contains the values in numerical indices.
1034 * mysql_fetch_row() wrapper function
1035 * Usage count/core: 56
1036 *
1037 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1038 * @return array Array with result rows.
1039 */
1040 function sql_fetch_row($res) {
1041 if ($this->debug_check_recordset($res)) {
1042 return mysql_fetch_row($res);
1043 } else {
1044 return FALSE;
1045 }
1046 }
1047
1048 /**
1049 * Free result memory
1050 * mysql_free_result() wrapper function
1051 * Usage count/core: 3
1052 *
1053 * @param pointer MySQL result pointer to free / DBAL object
1054 * @return boolean Returns TRUE on success or FALSE on failure.
1055 */
1056 function sql_free_result($res) {
1057 if ($this->debug_check_recordset($res)) {
1058 return mysql_free_result($res);
1059 } else {
1060 return FALSE;
1061 }
1062 }
1063
1064 /**
1065 * Get the ID generated from the previous INSERT operation
1066 * mysql_insert_id() wrapper function
1067 * Usage count/core: 13
1068 *
1069 * @return integer The uid of the last inserted record.
1070 */
1071 function sql_insert_id() {
1072 return mysql_insert_id($this->link);
1073 }
1074
1075 /**
1076 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
1077 * mysql_affected_rows() wrapper function
1078 * Usage count/core: 1
1079 *
1080 * @return integer Number of rows affected by last query
1081 */
1082 function sql_affected_rows() {
1083 return mysql_affected_rows($this->link);
1084 }
1085
1086 /**
1087 * Move internal result pointer
1088 * mysql_data_seek() wrapper function
1089 * Usage count/core: 3
1090 *
1091 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1092 * @param integer Seek result number.
1093 * @return boolean Returns TRUE on success or FALSE on failure.
1094 */
1095 function sql_data_seek($res, $seek) {
1096 if ($this->debug_check_recordset($res)) {
1097 return mysql_data_seek($res, $seek);
1098 } else {
1099 return FALSE;
1100 }
1101 }
1102
1103 /**
1104 * Get the type of the specified field in a result
1105 * mysql_field_type() wrapper function
1106 * Usage count/core: 2
1107 *
1108 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1109 * @param integer Field index.
1110 * @return string Returns the name of the specified field index
1111 */
1112 function sql_field_type($res, $pointer) {
1113 if ($this->debug_check_recordset($res)) {
1114 return mysql_field_type($res, $pointer);
1115 } else {
1116 return FALSE;
1117 }
1118 }
1119
1120 /**
1121 * Open a (persistent) connection to a MySQL server
1122 * mysql_pconnect() wrapper function
1123 * Usage count/core: 12
1124 *
1125 * @param string Database host IP/domain
1126 * @param string Username to connect with.
1127 * @param string Password to connect with.
1128 * @return pointer Returns a positive MySQL persistent link identifier on success, or FALSE on error.
1129 */
1130 function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) {
1131 // mysql_error() is tied to an established connection
1132 // if the connection fails we need a different method to get the error message
1133 @ini_set('track_errors', 1);
1134 @ini_set('html_errors', 0);
1135
1136 // check if MySQL extension is loaded
1137 if (!extension_loaded('mysql')) {
1138 $message = 'Database Error: It seems that MySQL support for PHP is not installed!';
1139 throw new RuntimeException($message, 1271492606);
1140 }
1141
1142 // Check for client compression
1143 $isLocalhost = ($TYPO3_db_host == 'localhost' || $TYPO3_db_host == '127.0.0.1');
1144 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
1145 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
1146 // We use PHP's default value for 4th parameter (new_link), which is false.
1147 // See PHP sources, for example: file php-5.2.5/ext/mysql/php_mysql.c,
1148 // function php_mysql_do_connect(), near line 525
1149 $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, FALSE, MYSQL_CLIENT_COMPRESS);
1150 } else {
1151 $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
1152 }
1153 } else {
1154 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
1155 // See comment about 4th parameter in block above
1156 $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, MYSQL_CLIENT_COMPRESS);
1157 } else {
1158 $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
1159 }
1160 }
1161
1162 $error_msg = $php_errormsg;
1163 @ini_restore('track_errors');
1164 @ini_restore('html_errors');
1165
1166 if (!$this->link) {
1167 t3lib_div::sysLog('Could not connect to MySQL server ' . $TYPO3_db_host .
1168 ' with user ' . $TYPO3_db_username . ': ' . $error_msg,
1169 'Core',
1170 4
1171 );
1172 } else {
1173 $setDBinit = t3lib_div::trimExplode(LF, str_replace("' . LF . '", LF, $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']), TRUE);
1174 foreach ($setDBinit as $v) {
1175 if (mysql_query($v, $this->link) === FALSE) {
1176 t3lib_div::sysLog('Could not initialize DB connection with query "' . $v .
1177 '": ' . mysql_error($this->link),
1178 'Core',
1179 3
1180 );
1181 }
1182 }
1183 }
1184
1185 return $this->link;
1186 }
1187
1188 /**
1189 * Select a MySQL database
1190 * mysql_select_db() wrapper function
1191 * Usage count/core: 8
1192 *
1193 * @param string Database to connect to.
1194 * @return boolean Returns TRUE on success or FALSE on failure.
1195 */
1196 function sql_select_db($TYPO3_db) {
1197 $ret = @mysql_select_db($TYPO3_db, $this->link);
1198 if (!$ret) {
1199 t3lib_div::sysLog('Could not select MySQL database ' . $TYPO3_db . ': ' .
1200 mysql_error(),
1201 'Core',
1202 4
1203 );
1204 }
1205 return $ret;
1206 }
1207
1208
1209 /**************************************
1210 *
1211 * SQL admin functions
1212 * (For use in the Install Tool and Extension Manager)
1213 *
1214 **************************************/
1215
1216 /**
1217 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
1218 * This is only used as a service function in the (1-2-3 process) of the Install Tool.
1219 * In any case a lookup should be done in the _DEFAULT handler DBMS then.
1220 * Use in Install Tool only!
1221 * Usage count/core: 1
1222 *
1223 * @return array Each entry represents a database name
1224 */
1225 function admin_get_dbs() {
1226 $dbArr = array();
1227 $db_list = mysql_list_dbs($this->link);
1228 while ($row = mysql_fetch_object($db_list)) {
1229 if ($this->sql_select_db($row->Database)) {
1230 $dbArr[] = $row->Database;
1231 }
1232 }
1233 return $dbArr;
1234 }
1235
1236 /**
1237 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
1238 * In a DBAL this method should 1) look up all tables from the DBMS of
1239 * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
1240 * Usage count/core: 2
1241 *
1242 * @return array Array with tablenames as key and arrays with status information as value
1243 */
1244 function admin_get_tables() {
1245 $whichTables = array();
1246
1247 $tables_result = mysql_query('SHOW TABLE STATUS FROM `' . TYPO3_db . '`', $this->link);
1248 if (!mysql_error()) {
1249 while ($theTable = mysql_fetch_assoc($tables_result)) {
1250 $whichTables[$theTable['Name']] = $theTable;
1251 }
1252
1253 $this->sql_free_result($tables_result);
1254 }
1255
1256 return $whichTables;
1257 }
1258
1259 /**
1260 * Returns information about each field in the $table (quering the DBMS)
1261 * In a DBAL this should look up the right handler for the table and return compatible information
1262 * This function is important not only for the Install Tool but probably for
1263 * DBALs as well since they might need to look up table specific information
1264 * in order to construct correct queries. In such cases this information should
1265 * probably be cached for quick delivery.
1266 *
1267 * @param string Table name
1268 * @return array Field information in an associative array with fieldname => field row
1269 */
1270 function admin_get_fields($tableName) {
1271 $output = array();
1272
1273 $columns_res = mysql_query('SHOW COLUMNS FROM `' . $tableName . '`', $this->link);
1274 while ($fieldRow = mysql_fetch_assoc($columns_res)) {
1275 $output[$fieldRow['Field']] = $fieldRow;
1276 }
1277
1278 $this->sql_free_result($columns_res);
1279
1280 return $output;
1281 }
1282
1283 /**
1284 * Returns information about each index key in the $table (quering the DBMS)
1285 * In a DBAL this should look up the right handler for the table and return compatible information
1286 *
1287 * @param string Table name
1288 * @return array Key information in a numeric array
1289 */
1290 function admin_get_keys($tableName) {
1291 $output = array();
1292
1293 $keyRes = mysql_query('SHOW KEYS FROM `' . $tableName . '`', $this->link);
1294 while ($keyRow = mysql_fetch_assoc($keyRes)) {
1295 $output[] = $keyRow;
1296 }
1297
1298 $this->sql_free_result($keyRes);
1299
1300 return $output;
1301 }
1302
1303 /**
1304 * Returns information about the character sets supported by the current DBM
1305 * This function is important not only for the Install Tool but probably for
1306 * DBALs as well since they might need to look up table specific information
1307 * in order to construct correct queries. In such cases this information should
1308 * probably be cached for quick delivery.
1309 *
1310 * This is used by the Install Tool to convert tables tables with non-UTF8 charsets
1311 * Use in Install Tool only!
1312 *
1313 * @return array Array with Charset as key and an array of "Charset", "Description", "Default collation", "Maxlen" as values
1314 */
1315 function admin_get_charsets() {
1316 $output = array();
1317
1318 $columns_res = mysql_query('SHOW CHARACTER SET', $this->link);
1319 if ($columns_res) {
1320 while (($row = mysql_fetch_assoc($columns_res))) {
1321 $output[$row['Charset']] = $row;
1322 }
1323
1324 $this->sql_free_result($columns_res);
1325 }
1326
1327 return $output;
1328 }
1329
1330 /**
1331 * mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
1332 * Usage count/core: 10
1333 *
1334 * @param string Query to execute
1335 * @return pointer Result pointer
1336 */
1337 function admin_query($query) {
1338 $res = mysql_query($query, $this->link);
1339 if ($this->debugOutput) {
1340 $this->debug('admin_query', $query);
1341 }
1342 return $res;
1343 }
1344
1345
1346 /******************************
1347 *
1348 * Connecting service
1349 *
1350 ******************************/
1351
1352 /**
1353 * Connects to database for TYPO3 sites:
1354 *
1355 * @param string $host
1356 * @param string $user
1357 * @param string $password
1358 * @param string $db
1359 * @return void
1360 */
1361 function connectDB($host = TYPO3_db_host, $user = TYPO3_db_username, $password = TYPO3_db_password, $db = TYPO3_db) {
1362 if ($this->sql_pconnect($host, $user, $password)) {
1363 if (!$db) {
1364 throw new RuntimeException(
1365 'TYPO3 Fatal Error: No database selected!',
1366 1270853882
1367 );
1368 } elseif (!$this->sql_select_db($db)) {
1369 throw new RuntimeException(
1370 'TYPO3 Fatal Error: Cannot connect to the current database, "' . $db . '"!',
1371 1270853883
1372 );
1373 }
1374 } else {
1375 throw new RuntimeException(
1376 'TYPO3 Fatal Error: The current username, password or host was not accepted when the connection to the database was attempted to be established!',
1377 1270853884
1378 );
1379 }
1380 }
1381
1382 /**
1383 * Checks if database is connected
1384 *
1385 * @return boolean
1386 */
1387 public function isConnected() {
1388 return is_resource($this->link);
1389 }
1390
1391
1392 /******************************
1393 *
1394 * Debugging
1395 *
1396 ******************************/
1397
1398 /**
1399 * Debug function: Outputs error if any
1400 *
1401 * @param string Function calling debug()
1402 * @param string Last query if not last built query
1403 * @return void
1404 */
1405 function debug($func, $query = '') {
1406
1407 $error = $this->sql_error();
1408 if ($error || $this->debugOutput == 2) {
1409 debug(
1410 array(
1411 'caller' => 't3lib_DB::' . $func,
1412 'ERROR' => $error,
1413 'lastBuiltQuery' => ($query ? $query : $this->debug_lastBuiltQuery),
1414 'debug_backtrace' => t3lib_utility_Debug::debugTrail(),
1415 ),
1416 $func,
1417 is_object($GLOBALS['error']) && @is_callable(array($GLOBALS['error'], 'debug')) ? '' : 'DB Error'
1418 );
1419 }
1420 }
1421
1422 /**
1423 * Checks if recordset is valid and writes debugging inormation into devLog if not.
1424 *
1425 * @param resource $res Recordset
1426 * @return boolean <code>false</code> if recordset is not valid
1427 */
1428 function debug_check_recordset($res) {
1429 if (!$res) {
1430 $trace = FALSE;
1431 $msg = 'Invalid database result resource detected';
1432 $trace = debug_backtrace();
1433 array_shift($trace);
1434 $cnt = count($trace);
1435 for ($i = 0; $i < $cnt; $i++) {
1436 // complete objects are too large for the log
1437 if (isset($trace['object'])) {
1438 unset($trace['object']);
1439 }
1440 }
1441 $msg .= ': function t3lib_DB->' . $trace[0]['function'] . ' called from file ' .
1442 substr($trace[0]['file'], strlen(PATH_site) + 2) . ' in line ' .
1443 $trace[0]['line'];
1444 t3lib_div::sysLog($msg . '. Use a devLog extension to get more details.', 'Core/t3lib_db', 3);
1445 // Send to devLog if enabled
1446 if (TYPO3_DLOG) {
1447 $debugLogData = array(
1448 'SQL Error' => $this->sql_error(),
1449 'Backtrace' => $trace,
1450 );
1451 if ($this->debug_lastBuiltQuery) {
1452 $debugLogData = array('SQL Query' => $this->debug_lastBuiltQuery) + $debugLogData;
1453 }
1454 t3lib_div::devLog($msg . '.', 'Core/t3lib_db', 3, $debugLogData);
1455 }
1456
1457 return FALSE;
1458 }
1459 return TRUE;
1460 }
1461
1462 /**
1463 * Explain select queries
1464 * If $this->explainOutput is set, SELECT queries will be explained here. Only queries with more than one possible result row will be displayed.
1465 * The output is either printed as raw HTML output or embedded into the TS admin panel (checkbox must be enabled!)
1466 *
1467 * TODO: Feature is not DBAL-compliant
1468 *
1469 * @param string SQL query
1470 * @param string Table(s) from which to select. This is what comes right after "FROM ...". Required value.
1471 * @param integer Number of resulting rows
1472 * @return boolean True if explain was run, false otherwise
1473 */
1474 protected function explain($query, $from_table, $row_count) {
1475
1476 if ((int) $this->explainOutput == 1 || ((int) $this->explainOutput == 2 &&
1477 t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']))
1478 ) {
1479 // raw HTML output
1480 $explainMode = 1;
1481 } elseif ((int) $this->explainOutput == 3 && is_object($GLOBALS['TT'])) {
1482 // embed the output into the TS admin panel
1483 $explainMode = 2;
1484 } else {
1485 return FALSE;
1486 }
1487
1488 $error = $this->sql_error();
1489 $trail = t3lib_utility_Debug::debugTrail();
1490
1491 $explain_tables = array();
1492 $explain_output = array();
1493 $res = $this->sql_query('EXPLAIN ' . $query, $this->link);
1494 if (is_resource($res)) {
1495 while ($tempRow = $this->sql_fetch_assoc($res)) {
1496 $explain_output[] = $tempRow;
1497 $explain_tables[] = $tempRow['table'];
1498 }
1499 $this->sql_free_result($res);
1500 }
1501
1502 $indices_output = array();
1503 // Notice: Rows are skipped if there is only one result, or if no conditions are set
1504 if ($explain_output[0]['rows'] > 1 || t3lib_div::inList('ALL', $explain_output[0]['type'])) {
1505 // only enable output if it's really useful
1506 $debug = TRUE;
1507
1508 foreach ($explain_tables as $table) {
1509 $tableRes = $this->sql_query('SHOW TABLE STATUS LIKE \'' . $table . '\'');
1510 $isTable = $this->sql_num_rows($tableRes);
1511 if ($isTable) {
1512 $res = $this->sql_query('SHOW INDEX FROM ' . $table, $this->link);
1513 if (is_resource($res)) {
1514 while ($tempRow = $this->sql_fetch_assoc($res)) {
1515 $indices_output[] = $tempRow;
1516 }
1517 $this->sql_free_result($res);
1518 }
1519 }
1520 $this->sql_free_result($tableRes);
1521 }
1522 } else {
1523 $debug = FALSE;
1524 }
1525
1526 if ($debug) {
1527 if ($explainMode) {
1528 $data = array();
1529 $data['query'] = $query;
1530 $data['trail'] = $trail;
1531 $data['row_count'] = $row_count;
1532
1533 if ($error) {
1534 $data['error'] = $error;
1535 }
1536 if (count($explain_output)) {
1537 $data['explain'] = $explain_output;
1538 }
1539 if (count($indices_output)) {
1540 $data['indices'] = $indices_output;
1541 }
1542
1543 if ($explainMode == 1) {
1544 t3lib_utility_Debug::debug($data, 'Tables: ' . $from_table, 'DB SQL EXPLAIN');
1545 } elseif ($explainMode == 2) {
1546 $GLOBALS['TT']->setTSselectQuery($data);
1547 }
1548 }
1549 return TRUE;
1550 }
1551
1552 return FALSE;
1553 }
1554
1555 }
1556
1557
1558 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php'])) {
1559 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
1560 }
1561
1562 ?>