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