Fixed bug #16445: Performance Tuning: Replace exec_SELECTgetRows with exec_SELECTgetS...
[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 * Usage count/core: 1
964 *
965 * @param string Query to execute
966 * @return pointer Result pointer / DBAL object
967 */
968 function sql_query($query) {
969 $res = mysql_query($query, $this->link);
970 if ($this->debugOutput) {
971 $this->debug('sql_query', $query);
972 }
973 return $res;
974 }
975
976 /**
977 * Returns the error status on the last sql() execution
978 * mysql_error() wrapper function
979 * Usage count/core: 32
980 *
981 * @return string MySQL error string.
982 */
983 function sql_error() {
984 return mysql_error($this->link);
985 }
986
987 /**
988 * Returns the error number on the last sql() execution
989 * mysql_errno() wrapper function
990 *
991 * @return int MySQL error number.
992 */
993 function sql_errno() {
994 return mysql_errno($this->link);
995 }
996
997 /**
998 * Returns the number of selected rows.
999 * mysql_num_rows() wrapper function
1000 * Usage count/core: 85
1001 *
1002 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1003 * @return integer Number of resulting rows
1004 */
1005 function sql_num_rows($res) {
1006 if ($this->debug_check_recordset($res)) {
1007 return mysql_num_rows($res);
1008 } else {
1009 return FALSE;
1010 }
1011 }
1012
1013 /**
1014 * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
1015 * mysql_fetch_assoc() wrapper function
1016 * Usage count/core: 307
1017 *
1018 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1019 * @return array Associative array of result row.
1020 */
1021 function sql_fetch_assoc($res) {
1022 if ($this->debug_check_recordset($res)) {
1023 return mysql_fetch_assoc($res);
1024 } else {
1025 return FALSE;
1026 }
1027 }
1028
1029 /**
1030 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
1031 * The array contains the values in numerical indices.
1032 * mysql_fetch_row() wrapper function
1033 * Usage count/core: 56
1034 *
1035 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1036 * @return array Array with result rows.
1037 */
1038 function sql_fetch_row($res) {
1039 if ($this->debug_check_recordset($res)) {
1040 return mysql_fetch_row($res);
1041 } else {
1042 return FALSE;
1043 }
1044 }
1045
1046 /**
1047 * Free result memory
1048 * mysql_free_result() wrapper function
1049 * Usage count/core: 3
1050 *
1051 * @param pointer MySQL result pointer to free / DBAL object
1052 * @return boolean Returns TRUE on success or FALSE on failure.
1053 */
1054 function sql_free_result($res) {
1055 if ($this->debug_check_recordset($res)) {
1056 return mysql_free_result($res);
1057 } else {
1058 return FALSE;
1059 }
1060 }
1061
1062 /**
1063 * Get the ID generated from the previous INSERT operation
1064 * mysql_insert_id() wrapper function
1065 * Usage count/core: 13
1066 *
1067 * @return integer The uid of the last inserted record.
1068 */
1069 function sql_insert_id() {
1070 return mysql_insert_id($this->link);
1071 }
1072
1073 /**
1074 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
1075 * mysql_affected_rows() wrapper function
1076 * Usage count/core: 1
1077 *
1078 * @return integer Number of rows affected by last query
1079 */
1080 function sql_affected_rows() {
1081 return mysql_affected_rows($this->link);
1082 }
1083
1084 /**
1085 * Move internal result pointer
1086 * mysql_data_seek() wrapper function
1087 * Usage count/core: 3
1088 *
1089 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1090 * @param integer Seek result number.
1091 * @return boolean Returns TRUE on success or FALSE on failure.
1092 */
1093 function sql_data_seek($res, $seek) {
1094 if ($this->debug_check_recordset($res)) {
1095 return mysql_data_seek($res, $seek);
1096 } else {
1097 return FALSE;
1098 }
1099 }
1100
1101 /**
1102 * Get the type of the specified field in a result
1103 * mysql_field_type() wrapper function
1104 * Usage count/core: 2
1105 *
1106 * @param pointer MySQL result pointer (of SELECT query) / DBAL object
1107 * @param integer Field index.
1108 * @return string Returns the name of the specified field index
1109 */
1110 function sql_field_type($res, $pointer) {
1111 if ($this->debug_check_recordset($res)) {
1112 return mysql_field_type($res, $pointer);
1113 } else {
1114 return FALSE;
1115 }
1116 }
1117
1118 /**
1119 * Open a (persistent) connection to a MySQL server
1120 * mysql_pconnect() wrapper function
1121 * Usage count/core: 12
1122 *
1123 * @param string Database host IP/domain
1124 * @param string Username to connect with.
1125 * @param string Password to connect with.
1126 * @return pointer Returns a positive MySQL persistent link identifier on success, or FALSE on error.
1127 */
1128 function sql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password) {
1129 // mysql_error() is tied to an established connection
1130 // if the connection fails we need a different method to get the error message
1131 @ini_set('track_errors', 1);
1132 @ini_set('html_errors', 0);
1133
1134 // check if MySQL extension is loaded
1135 if (!extension_loaded('mysql')) {
1136 $message = 'Database Error: It seems that MySQL support for PHP is not installed!';
1137 throw new RuntimeException($message, 1271492606);
1138 }
1139
1140 // Check for client compression
1141 $isLocalhost = ($TYPO3_db_host == 'localhost' || $TYPO3_db_host == '127.0.0.1');
1142 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']) {
1143 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
1144 // We use PHP's default value for 4th parameter (new_link), which is false.
1145 // See PHP sources, for example: file php-5.2.5/ext/mysql/php_mysql.c,
1146 // function php_mysql_do_connect(), near line 525
1147 $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, FALSE, MYSQL_CLIENT_COMPRESS);
1148 } else {
1149 $this->link = @mysql_connect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
1150 }
1151 } else {
1152 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'] && !$isLocalhost) {
1153 // See comment about 4th parameter in block above
1154 $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password, MYSQL_CLIENT_COMPRESS);
1155 } else {
1156 $this->link = @mysql_pconnect($TYPO3_db_host, $TYPO3_db_username, $TYPO3_db_password);
1157 }
1158 }
1159
1160 $error_msg = $php_errormsg;
1161 @ini_restore('track_errors');
1162 @ini_restore('html_errors');
1163
1164 if (!$this->link) {
1165 t3lib_div::sysLog('Could not connect to MySQL server ' . $TYPO3_db_host .
1166 ' with user ' . $TYPO3_db_username . ': ' . $error_msg,
1167 'Core',
1168 4
1169 );
1170 } else {
1171 $setDBinit = t3lib_div::trimExplode(LF, str_replace("' . LF . '", LF, $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']), TRUE);
1172 foreach ($setDBinit as $v) {
1173 if (mysql_query($v, $this->link) === FALSE) {
1174 t3lib_div::sysLog('Could not initialize DB connection with query "' . $v .
1175 '": ' . mysql_error($this->link),
1176 'Core',
1177 3
1178 );
1179 }
1180 }
1181 }
1182
1183 return $this->link;
1184 }
1185
1186 /**
1187 * Select a MySQL database
1188 * mysql_select_db() wrapper function
1189 * Usage count/core: 8
1190 *
1191 * @param string Database to connect to.
1192 * @return boolean Returns TRUE on success or FALSE on failure.
1193 */
1194 function sql_select_db($TYPO3_db) {
1195 $ret = @mysql_select_db($TYPO3_db, $this->link);
1196 if (!$ret) {
1197 t3lib_div::sysLog('Could not select MySQL database ' . $TYPO3_db . ': ' .
1198 mysql_error(),
1199 'Core',
1200 4
1201 );
1202 }
1203 return $ret;
1204 }
1205
1206
1207 /**************************************
1208 *
1209 * SQL admin functions
1210 * (For use in the Install Tool and Extension Manager)
1211 *
1212 **************************************/
1213
1214 /**
1215 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
1216 * This is only used as a service function in the (1-2-3 process) of the Install Tool.
1217 * In any case a lookup should be done in the _DEFAULT handler DBMS then.
1218 * Use in Install Tool only!
1219 * Usage count/core: 1
1220 *
1221 * @return array Each entry represents a database name
1222 */
1223 function admin_get_dbs() {
1224 $dbArr = array();
1225 $db_list = mysql_list_dbs($this->link);
1226 while ($row = mysql_fetch_object($db_list)) {
1227 if ($this->sql_select_db($row->Database)) {
1228 $dbArr[] = $row->Database;
1229 }
1230 }
1231 return $dbArr;
1232 }
1233
1234 /**
1235 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
1236 * In a DBAL this method should 1) look up all tables from the DBMS of
1237 * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
1238 * Usage count/core: 2
1239 *
1240 * @return array Array with tablenames as key and arrays with status information as value
1241 */
1242 function admin_get_tables() {
1243 $whichTables = array();
1244
1245 $tables_result = mysql_query('SHOW TABLE STATUS FROM `' . TYPO3_db . '`', $this->link);
1246 if (!mysql_error()) {
1247 while ($theTable = mysql_fetch_assoc($tables_result)) {
1248 $whichTables[$theTable['Name']] = $theTable;
1249 }
1250
1251 $this->sql_free_result($tables_result);
1252 }
1253
1254 return $whichTables;
1255 }
1256
1257 /**
1258 * Returns information about each field in the $table (quering the DBMS)
1259 * In a DBAL this should look up the right handler for the table and return compatible information
1260 * This function is important not only for the Install Tool but probably for
1261 * DBALs as well since they might need to look up table specific information
1262 * in order to construct correct queries. In such cases this information should
1263 * probably be cached for quick delivery.
1264 *
1265 * @param string Table name
1266 * @return array Field information in an associative array with fieldname => field row
1267 */
1268 function admin_get_fields($tableName) {
1269 $output = array();
1270
1271 $columns_res = mysql_query('SHOW COLUMNS FROM `' . $tableName . '`', $this->link);
1272 while ($fieldRow = mysql_fetch_assoc($columns_res)) {
1273 $output[$fieldRow['Field']] = $fieldRow;
1274 }
1275
1276 $this->sql_free_result($columns_res);
1277
1278 return $output;
1279 }
1280
1281 /**
1282 * Returns information about each index key in the $table (quering the DBMS)
1283 * In a DBAL this should look up the right handler for the table and return compatible information
1284 *
1285 * @param string Table name
1286 * @return array Key information in a numeric array
1287 */
1288 function admin_get_keys($tableName) {
1289 $output = array();
1290
1291 $keyRes = mysql_query('SHOW KEYS FROM `' . $tableName . '`', $this->link);
1292 while ($keyRow = mysql_fetch_assoc($keyRes)) {
1293 $output[] = $keyRow;
1294 }
1295
1296 $this->sql_free_result($keyRes);
1297
1298 return $output;
1299 }
1300
1301 /**
1302 * Returns information about the character sets supported by the current DBM
1303 * This function is important not only for the Install Tool but probably for
1304 * DBALs as well since they might need to look up table specific information
1305 * in order to construct correct queries. In such cases this information should
1306 * probably be cached for quick delivery.
1307 *
1308 * This is used by the Install Tool to convert tables tables with non-UTF8 charsets
1309 * Use in Install Tool only!
1310 *
1311 * @return array Array with Charset as key and an array of "Charset", "Description", "Default collation", "Maxlen" as values
1312 */
1313 function admin_get_charsets() {
1314 $output = array();
1315
1316 $columns_res = mysql_query('SHOW CHARACTER SET', $this->link);
1317 if ($columns_res) {
1318 while (($row = mysql_fetch_assoc($columns_res))) {
1319 $output[$row['Charset']] = $row;
1320 }
1321
1322 $this->sql_free_result($columns_res);
1323 }
1324
1325 return $output;
1326 }
1327
1328 /**
1329 * mysql() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
1330 * Usage count/core: 10
1331 *
1332 * @param string Query to execute
1333 * @return pointer Result pointer
1334 */
1335 function admin_query($query) {
1336 $res = mysql_query($query, $this->link);
1337 if ($this->debugOutput) {
1338 $this->debug('admin_query', $query);
1339 }
1340 return $res;
1341 }
1342
1343
1344 /******************************
1345 *
1346 * Connecting service
1347 *
1348 ******************************/
1349
1350 /**
1351 * Connects to database for TYPO3 sites:
1352 *
1353 * @param string $host
1354 * @param string $user
1355 * @param string $password
1356 * @param string $db
1357 * @return void
1358 */
1359 function connectDB($host = TYPO3_db_host, $user = TYPO3_db_username, $password = TYPO3_db_password, $db = TYPO3_db) {
1360 if ($this->sql_pconnect($host, $user, $password)) {
1361 if (!$db) {
1362 throw new RuntimeException(
1363 'TYPO3 Fatal Error: No database selected!',
1364 1270853882
1365 );
1366 } elseif (!$this->sql_select_db($db)) {
1367 throw new RuntimeException(
1368 'TYPO3 Fatal Error: Cannot connect to the current database, "' . $db . '"!',
1369 1270853883
1370 );
1371 }
1372 } else {
1373 throw new RuntimeException(
1374 'TYPO3 Fatal Error: The current username, password or host was not accepted when the connection to the database was attempted to be established!',
1375 1270853884
1376 );
1377 }
1378 }
1379
1380 /**
1381 * Checks if database is connected
1382 *
1383 * @return boolean
1384 */
1385 public function isConnected() {
1386 return is_resource($this->link);
1387 }
1388
1389
1390 /******************************
1391 *
1392 * Debugging
1393 *
1394 ******************************/
1395
1396 /**
1397 * Debug function: Outputs error if any
1398 *
1399 * @param string Function calling debug()
1400 * @param string Last query if not last built query
1401 * @return void
1402 */
1403 function debug($func, $query = '') {
1404
1405 $error = $this->sql_error();
1406 if ($error || $this->debugOutput == 2) {
1407 debug(
1408 array(
1409 'caller' => 't3lib_DB::' . $func,
1410 'ERROR' => $error,
1411 'lastBuiltQuery' => ($query ? $query : $this->debug_lastBuiltQuery),
1412 'debug_backtrace' => t3lib_utility_Debug::debugTrail(),
1413 ),
1414 $func,
1415 is_object($GLOBALS['error']) && @is_callable(array($GLOBALS['error'], 'debug')) ? '' : 'DB Error'
1416 );
1417 }
1418 }
1419
1420 /**
1421 * Checks if recordset is valid and writes debugging inormation into devLog if not.
1422 *
1423 * @param resource $res Recordset
1424 * @return boolean <code>false</code> if recordset is not valid
1425 */
1426 function debug_check_recordset($res) {
1427 if (!$res) {
1428 $trace = FALSE;
1429 $msg = 'Invalid database result resource detected';
1430 $trace = debug_backtrace();
1431 array_shift($trace);
1432 $cnt = count($trace);
1433 for ($i = 0; $i < $cnt; $i++) {
1434 // complete objects are too large for the log
1435 if (isset($trace['object'])) {
1436 unset($trace['object']);
1437 }
1438 }
1439 $msg .= ': function t3lib_DB->' . $trace[0]['function'] . ' called from file ' .
1440 substr($trace[0]['file'], strlen(PATH_site) + 2) . ' in line ' .
1441 $trace[0]['line'];
1442 t3lib_div::sysLog($msg . '. Use a devLog extension to get more details.', 'Core/t3lib_db', 3);
1443 // Send to devLog if enabled
1444 if (TYPO3_DLOG) {
1445 $debugLogData = array(
1446 'SQL Error' => $this->sql_error(),
1447 'Backtrace' => $trace,
1448 );
1449 if ($this->debug_lastBuiltQuery) {
1450 $debugLogData = array('SQL Query' => $this->debug_lastBuiltQuery) + $debugLogData;
1451 }
1452 t3lib_div::devLog($msg . '.', 'Core/t3lib_db', 3, $debugLogData);
1453 }
1454
1455 return FALSE;
1456 }
1457 return TRUE;
1458 }
1459
1460 /**
1461 * Explain select queries
1462 * If $this->explainOutput is set, SELECT queries will be explained here. Only queries with more than one possible result row will be displayed.
1463 * The output is either printed as raw HTML output or embedded into the TS admin panel (checkbox must be enabled!)
1464 *
1465 * TODO: Feature is not DBAL-compliant
1466 *
1467 * @param string SQL query
1468 * @param string Table(s) from which to select. This is what comes right after "FROM ...". Required value.
1469 * @param integer Number of resulting rows
1470 * @return boolean True if explain was run, false otherwise
1471 */
1472 protected function explain($query, $from_table, $row_count) {
1473
1474 if ((int) $this->explainOutput == 1 || ((int) $this->explainOutput == 2 &&
1475 t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']))
1476 ) {
1477 // raw HTML output
1478 $explainMode = 1;
1479 } elseif ((int) $this->explainOutput == 3 && is_object($GLOBALS['TT'])) {
1480 // embed the output into the TS admin panel
1481 $explainMode = 2;
1482 } else {
1483 return FALSE;
1484 }
1485
1486 $error = $this->sql_error();
1487 $trail = t3lib_utility_Debug::debugTrail();
1488
1489 $explain_tables = array();
1490 $explain_output = array();
1491 $res = $this->sql_query('EXPLAIN ' . $query, $this->link);
1492 if (is_resource($res)) {
1493 while ($tempRow = $this->sql_fetch_assoc($res)) {
1494 $explain_output[] = $tempRow;
1495 $explain_tables[] = $tempRow['table'];
1496 }
1497 $this->sql_free_result($res);
1498 }
1499
1500 $indices_output = array();
1501 // Notice: Rows are skipped if there is only one result, or if no conditions are set
1502 if ($explain_output[0]['rows'] > 1 || t3lib_div::inList('ALL', $explain_output[0]['type'])) {
1503 // only enable output if it's really useful
1504 $debug = TRUE;
1505
1506 foreach ($explain_tables as $table) {
1507 $tableRes = $this->sql_query('SHOW TABLE STATUS LIKE \'' . $table . '\'');
1508 $isTable = $this->sql_num_rows($tableRes);
1509 if ($isTable) {
1510 $res = $this->sql_query('SHOW INDEX FROM ' . $table, $this->link);
1511 if (is_resource($res)) {
1512 while ($tempRow = $this->sql_fetch_assoc($res)) {
1513 $indices_output[] = $tempRow;
1514 }
1515 $this->sql_free_result($res);
1516 }
1517 }
1518 $this->sql_free_result($tableRes);
1519 }
1520 } else {
1521 $debug = FALSE;
1522 }
1523
1524 if ($debug) {
1525 if ($explainMode) {
1526 $data = array();
1527 $data['query'] = $query;
1528 $data['trail'] = $trail;
1529 $data['row_count'] = $row_count;
1530
1531 if ($error) {
1532 $data['error'] = $error;
1533 }
1534 if (count($explain_output)) {
1535 $data['explain'] = $explain_output;
1536 }
1537 if (count($indices_output)) {
1538 $data['indices'] = $indices_output;
1539 }
1540
1541 if ($explainMode == 1) {
1542 t3lib_utility_Debug::debug($data, 'Tables: ' . $from_table, 'DB SQL EXPLAIN');
1543 } elseif ($explainMode == 2) {
1544 $GLOBALS['TT']->setTSselectQuery($data);
1545 }
1546 }
1547 return TRUE;
1548 }
1549
1550 return FALSE;
1551 }
1552
1553 }
1554
1555
1556 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']) {
1557 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_db.php']);
1558 }
1559
1560 ?>