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