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