cca1a7d5a4c85630cd8dce8af7e19b951b9aa0ed
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Database / DatabaseConnection.php
1 <?php
2 namespace TYPO3\CMS\Core\Database;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2004-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 use TYPO3\CMS\Core\Utility\GeneralUtility;
31
32 /**
33 * Contains the class "DatabaseConnection" containing functions for building SQL queries
34 * and mysqli wrappers, thus providing a foundational API to all database
35 * interaction.
36 * This class is instantiated globally as $TYPO3_DB in TYPO3 scripts.
37 *
38 * TYPO3 "database wrapper" class (new in 3.6.0)
39 * This class contains
40 * - 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!)
41 * - 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!
42 * - mysqli 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 mysqli functions not found as wrapper functions in this class!
43 * See the Project Coding Guidelines (doc_core_cgl) for more instructions on best-practise
44 *
45 * 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)
46 * ALL connectivity to the database in TYPO3 must be done through this class!
47 * The points of this class are:
48 * - To direct all database calls through this class so it becomes possible to implement DBAL with extensions.
49 * - 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...
50 * - To create an interface for DBAL implemented by extensions; (Eg. making possible escaping characters, clob/blob handling, reserved words handling)
51 * - Benchmarking the DB bottleneck queries will become much easier; Will make it easier to find optimization possibilities.
52 *
53 * USE:
54 * In all TYPO3 scripts the global variable $TYPO3_DB is an instance of this class. Use that.
55 * Eg. $GLOBALS['TYPO3_DB']->sql_fetch_assoc()
56 *
57 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
58 */
59 class DatabaseConnection {
60
61 /**
62 * The AND constraint in where clause
63 *
64 * @var string
65 */
66 const AND_Constraint = 'AND';
67
68 /**
69 * The OR constraint in where clause
70 *
71 * @var string
72 */
73 const OR_Constraint = 'OR';
74
75 // Set "TRUE" or "1" if you want database errors outputted. Set to "2" if you also want successful database actions outputted.
76 /**
77 * @todo Define visibility
78 */
79 public $debugOutput = FALSE;
80
81 // Internally: Set to last built query (not necessarily executed...)
82 /**
83 * @todo Define visibility
84 */
85 public $debug_lastBuiltQuery = '';
86
87 // Set "TRUE" if you want the last built query to be stored in $debug_lastBuiltQuery independent of $this->debugOutput
88 /**
89 * @todo Define visibility
90 */
91 public $store_lastBuiltQuery = FALSE;
92
93 // Set this to 1 to get queries explained (devIPmask must match). Set the value to 2 to the same but disregarding the devIPmask.
94 // 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.
95 /**
96 * @todo Define visibility
97 */
98 public $explainOutput = 0;
99
100 /**
101 * @var string Database host to connect to
102 */
103 protected $databaseHost = '';
104
105 /**
106 * @var integer Database port to connect to
107 */
108 protected $databasePort = 3306;
109
110 /**
111 * @var string|NULL Database socket to connect to
112 */
113 protected $databaseSocket = NULL;
114
115 /**
116 * @var string Database name to connect to
117 */
118 protected $databaseName = '';
119
120 /**
121 * @var string Database user to connect with
122 */
123 protected $databaseUsername = '';
124
125 /**
126 * @var string Database password to connect with
127 */
128 protected $databaseUserPassword = '';
129
130 /**
131 * @var boolean TRUE if database connection should be persistent
132 * @see http://php.net/manual/de/mysqli.persistconns.php
133 */
134 protected $persistentDatabaseConnection = FALSE;
135
136 /**
137 * @var boolean TRUE if connection between client and sql server is compressed
138 */
139 protected $connectionCompression = FALSE;
140
141 /**
142 * The charset for the connection; will be passed on to
143 * mysqli_set_charset during connection initialization.
144 *
145 * @var string
146 */
147 protected $connectionCharset = 'utf8';
148
149 /**
150 * @var array List of commands executed after connection was established
151 */
152 protected $initializeCommandsAfterConnect = array();
153
154 /**
155 * @var boolean TRUE if database connection is established
156 */
157 protected $isConnected = FALSE;
158
159 /**
160 * @var \mysqli $link Default database link object
161 */
162 protected $link = NULL;
163
164 // Default character set, applies unless character set or collation are explicitly set
165 /**
166 * @todo Define visibility
167 */
168 public $default_charset = 'utf8';
169
170 /**
171 * @var array<PostProcessQueryHookInterface>
172 */
173 protected $preProcessHookObjects = array();
174
175 /**
176 * @var array<PreProcessQueryHookInterface>
177 */
178 protected $postProcessHookObjects = array();
179
180
181 /**
182 * Initialize the database connection
183 *
184 * @return void
185 */
186 public function initialize() {
187 // Intentionally blank as this will be overloaded by DBAL
188 }
189
190 /************************************
191 *
192 * Query execution
193 *
194 * These functions are the RECOMMENDED DBAL functions for use in your applications
195 * Using these functions will allow the DBAL to use alternative ways of accessing data (contrary to if a query is returned!)
196 * They compile a query AND execute it immediately and then return the result
197 * This principle heightens our ability to create various forms of DBAL of the functions.
198 * Generally: We want to return a result pointer/object, never queries.
199 * Also, having the table name together with the actual query execution allows us to direct the request to other databases.
200 *
201 **************************************/
202
203 /**
204 * Creates and executes an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
205 * Using this function specifically allows us to handle BLOB and CLOB fields depending on DB
206 *
207 * @param string $table Table name
208 * @param array $fields_values 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.
209 * @param boolean $no_quote_fields See fullQuoteArray()
210 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
211 */
212 public function exec_INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
213 $res = $this->query($this->INSERTquery($table, $fields_values, $no_quote_fields));
214 if ($this->debugOutput) {
215 $this->debug('exec_INSERTquery');
216 }
217 foreach ($this->postProcessHookObjects as $hookObject) {
218 /** @var $hookObject PostProcessQueryHookInterface */
219 $hookObject->exec_INSERTquery_postProcessAction($table, $fields_values, $no_quote_fields, $this);
220 }
221 return $res;
222 }
223
224 /**
225 * Creates and executes an INSERT SQL-statement for $table with multiple rows.
226 *
227 * @param string $table Table name
228 * @param array $fields Field names
229 * @param array $rows Table rows. Each row should be an array with field values mapping to $fields
230 * @param boolean $no_quote_fields See fullQuoteArray()
231 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
232 */
233 public function exec_INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
234 $res = $this->query($this->INSERTmultipleRows($table, $fields, $rows, $no_quote_fields));
235 if ($this->debugOutput) {
236 $this->debug('exec_INSERTmultipleRows');
237 }
238 foreach ($this->postProcessHookObjects as $hookObject) {
239 /** @var $hookObject PostProcessQueryHookInterface */
240 $hookObject->exec_INSERTmultipleRows_postProcessAction($table, $fields, $rows, $no_quote_fields, $this);
241 }
242 return $res;
243 }
244
245 /**
246 * Creates and executes an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
247 * Using this function specifically allow us to handle BLOB and CLOB fields depending on DB
248 *
249 * @param string $table Database tablename
250 * @param string $where WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
251 * @param array $fields_values 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.
252 * @param boolean $no_quote_fields See fullQuoteArray()
253 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
254 */
255 public function exec_UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
256 $res = $this->query($this->UPDATEquery($table, $where, $fields_values, $no_quote_fields));
257 if ($this->debugOutput) {
258 $this->debug('exec_UPDATEquery');
259 }
260 foreach ($this->postProcessHookObjects as $hookObject) {
261 /** @var $hookObject PostProcessQueryHookInterface */
262 $hookObject->exec_UPDATEquery_postProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
263 }
264 return $res;
265 }
266
267 /**
268 * Creates and executes a DELETE SQL-statement for $table where $where-clause
269 *
270 * @param string $table Database tablename
271 * @param string $where WHERE clause, eg. "uid=1". NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
272 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
273 */
274 public function exec_DELETEquery($table, $where) {
275 $res = $this->query($this->DELETEquery($table, $where));
276 if ($this->debugOutput) {
277 $this->debug('exec_DELETEquery');
278 }
279 foreach ($this->postProcessHookObjects as $hookObject) {
280 /** @var $hookObject PostProcessQueryHookInterface */
281 $hookObject->exec_DELETEquery_postProcessAction($table, $where, $this);
282 }
283 return $res;
284 }
285
286 /**
287 * Creates and executes a SELECT SQL-statement
288 * Using this function specifically allow us to handle the LIMIT feature independently of DB.
289 *
290 * @param string $select_fields List of fields to select from the table. This is what comes right after "SELECT ...". Required value.
291 * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
292 * @param string $where_clause 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!
293 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
294 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
295 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
296 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
297 */
298 public function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
299 $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
300 $res = $this->query($query);
301 if ($this->debugOutput) {
302 $this->debug('exec_SELECTquery');
303 }
304 if ($this->explainOutput) {
305 $this->explain($query, $from_table, $res->num_rows);
306 }
307 foreach ($this->postProcessHookObjects as $hookObject) {
308 /** @var $hookObject PostProcessQueryHookInterface */
309 $hookObject->exec_SELECTquery_postProcessAction($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', $this);
310 }
311 return $res;
312 }
313
314 /**
315 * Creates and executes a SELECT query, selecting fields ($select) from two/three tables joined
316 * 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.
317 * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local / [$mm_table].uid_foreign <--> [$foreign_table].uid
318 * 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.
319 *
320 * @param string $select Field list for SELECT
321 * @param string $local_table Tablename, local table
322 * @param string $mm_table Tablename, relation table
323 * @param string $foreign_table Tablename, foreign table
324 * @param string $whereClause 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!
325 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
326 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
327 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
328 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
329 * @see exec_SELECTquery()
330 */
331 public function exec_SELECT_mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
332 $foreign_table_as = $foreign_table == $local_table ? $foreign_table . uniqid('_join') : '';
333 $mmWhere = $local_table ? $local_table . '.uid=' . $mm_table . '.uid_local' : '';
334 $mmWhere .= ($local_table and $foreign_table) ? ' AND ' : '';
335 $tables = ($local_table ? $local_table . ',' : '') . $mm_table;
336 if ($foreign_table) {
337 $mmWhere .= ($foreign_table_as ?: $foreign_table) . '.uid=' . $mm_table . '.uid_foreign';
338 $tables .= ',' . $foreign_table . ($foreign_table_as ? ' AS ' . $foreign_table_as : '');
339 }
340 return $this->exec_SELECTquery($select, $tables, $mmWhere . ' ' . $whereClause, $groupBy, $orderBy, $limit);
341 }
342
343 /**
344 * Executes a select based on input query parts array
345 *
346 * @param array $queryParts Query parts array
347 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
348 * @see exec_SELECTquery()
349 */
350 public function exec_SELECT_queryArray($queryParts) {
351 return $this->exec_SELECTquery($queryParts['SELECT'], $queryParts['FROM'], $queryParts['WHERE'], $queryParts['GROUPBY'], $queryParts['ORDERBY'], $queryParts['LIMIT']);
352 }
353
354 /**
355 * Creates and executes a SELECT SQL-statement AND traverse result set and returns array with records in.
356 *
357 * @param string $select_fields See exec_SELECTquery()
358 * @param string $from_table See exec_SELECTquery()
359 * @param string $where_clause See exec_SELECTquery()
360 * @param string $groupBy See exec_SELECTquery()
361 * @param string $orderBy See exec_SELECTquery()
362 * @param string $limit See exec_SELECTquery()
363 * @param string $uidIndexField If set, the result array will carry this field names value as index. Requires that field to be selected of course!
364 * @return array|NULL Array of rows, or NULL in case of SQL error
365 */
366 public function exec_SELECTgetRows($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', $uidIndexField = '') {
367 $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
368 if ($this->debugOutput) {
369 $this->debug('exec_SELECTquery');
370 }
371 if (!$this->sql_error()) {
372 $output = array();
373 if ($uidIndexField) {
374 while ($tempRow = $this->sql_fetch_assoc($res)) {
375 $output[$tempRow[$uidIndexField]] = $tempRow;
376 }
377 } else {
378 while ($output[] = $this->sql_fetch_assoc($res)) {
379
380 }
381 array_pop($output);
382 }
383 $this->sql_free_result($res);
384 } else {
385 $output = NULL;
386 }
387 return $output;
388 }
389
390 /**
391 * Creates and executes a SELECT SQL-statement AND gets a result set and returns an array with a single record in.
392 * LIMIT is automatically set to 1 and can not be overridden.
393 *
394 * @param string $select_fields List of fields to select from the table.
395 * @param string $from_table Table(s) from which to select.
396 * @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!
397 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
398 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
399 * @param boolean $numIndex If set, the result will be fetched with sql_fetch_row, otherwise sql_fetch_assoc will be used.
400 * @return array Single row or NULL if it fails.
401 */
402 public function exec_SELECTgetSingleRow($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $numIndex = FALSE) {
403 $res = $this->exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, '1');
404 if ($this->debugOutput) {
405 $this->debug('exec_SELECTquery');
406 }
407 $output = NULL;
408 if ($res !== FALSE) {
409 if ($numIndex) {
410 $output = $this->sql_fetch_row($res);
411 } else {
412 $output = $this->sql_fetch_assoc($res);
413 }
414 $this->sql_free_result($res);
415 }
416 return $output;
417 }
418
419 /**
420 * Counts the number of rows in a table.
421 *
422 * @param string $field Name of the field to use in the COUNT() expression (e.g. '*')
423 * @param string $table Name of the table to count rows for
424 * @param string $where (optional) WHERE statement of the query
425 * @return mixed Number of rows counter (integer) or FALSE if something went wrong (boolean)
426 */
427 public function exec_SELECTcountRows($field, $table, $where = '') {
428 $count = FALSE;
429 $resultSet = $this->exec_SELECTquery('COUNT(' . $field . ')', $table, $where);
430 if ($resultSet !== FALSE) {
431 list($count) = $this->sql_fetch_row($resultSet);
432 $count = (int)$count;
433 $this->sql_free_result($resultSet);
434 }
435 return $count;
436 }
437
438 /**
439 * Truncates a table.
440 *
441 * @param string $table Database tablename
442 * @return mixed Result from handler
443 */
444 public function exec_TRUNCATEquery($table) {
445 $res = $this->query($this->TRUNCATEquery($table));
446 if ($this->debugOutput) {
447 $this->debug('exec_TRUNCATEquery');
448 }
449 foreach ($this->postProcessHookObjects as $hookObject) {
450 /** @var $hookObject PostProcessQueryHookInterface */
451 $hookObject->exec_TRUNCATEquery_postProcessAction($table, $this);
452 }
453 return $res;
454 }
455
456 /**
457 * Central query method. Also checks if there is a database connection.
458 * Use this to execute database queries instead of directly calling $this->link->query()
459 *
460 * @param string $query The query to send to the database
461 * @return bool|\mysqli_result
462 */
463 protected function query($query) {
464 if (!$this->isConnected) {
465 $this->connectDB();
466 }
467 return $this->link->query($query);
468 }
469
470 /**************************************
471 *
472 * Query building
473 *
474 **************************************/
475 /**
476 * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
477 *
478 * @param string $table See exec_INSERTquery()
479 * @param array $fields_values See exec_INSERTquery()
480 * @param boolean $no_quote_fields See fullQuoteArray()
481 * @return string|NULL Full SQL query for INSERT, NULL if $fields_values is empty
482 */
483 public function INSERTquery($table, $fields_values, $no_quote_fields = FALSE) {
484 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
485 // function (contrary to values in the arrays which may be insecure).
486 if (!is_array($fields_values) || count($fields_values) === 0) {
487 return NULL;
488 }
489 foreach ($this->preProcessHookObjects as $hookObject) {
490 $hookObject->INSERTquery_preProcessAction($table, $fields_values, $no_quote_fields, $this);
491 }
492 // Quote and escape values
493 $fields_values = $this->fullQuoteArray($fields_values, $table, $no_quote_fields, TRUE);
494 // Build query
495 $query = 'INSERT INTO ' . $table . ' (' . implode(',', array_keys($fields_values)) . ') VALUES ' . '(' . implode(',', $fields_values) . ')';
496 // Return query
497 if ($this->debugOutput || $this->store_lastBuiltQuery) {
498 $this->debug_lastBuiltQuery = $query;
499 }
500 return $query;
501 }
502
503 /**
504 * Creates an INSERT SQL-statement for $table with multiple rows.
505 *
506 * @param string $table Table name
507 * @param array $fields Field names
508 * @param array $rows Table rows. Each row should be an array with field values mapping to $fields
509 * @param boolean $no_quote_fields See fullQuoteArray()
510 * @return string|NULL Full SQL query for INSERT, NULL if $rows is empty
511 */
512 public function INSERTmultipleRows($table, array $fields, array $rows, $no_quote_fields = FALSE) {
513 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
514 // function (contrary to values in the arrays which may be insecure).
515 if (count($rows) === 0) {
516 return NULL;
517 }
518 foreach ($this->preProcessHookObjects as $hookObject) {
519 /** @var $hookObject PreProcessQueryHookInterface */
520 $hookObject->INSERTmultipleRows_preProcessAction($table, $fields, $rows, $no_quote_fields, $this);
521 }
522 // Build query
523 $query = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES ';
524 $rowSQL = array();
525 foreach ($rows as $row) {
526 // Quote and escape values
527 $row = $this->fullQuoteArray($row, $table, $no_quote_fields);
528 $rowSQL[] = '(' . implode(', ', $row) . ')';
529 }
530 $query .= implode(', ', $rowSQL);
531 // Return query
532 if ($this->debugOutput || $this->store_lastBuiltQuery) {
533 $this->debug_lastBuiltQuery = $query;
534 }
535 return $query;
536 }
537
538 /**
539 * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
540 *
541 *
542 * @param string $table See exec_UPDATEquery()
543 * @param string $where See exec_UPDATEquery()
544 * @param array $fields_values See exec_UPDATEquery()
545 * @param boolean $no_quote_fields
546 * @throws \InvalidArgumentException
547 * @return string Full SQL query for UPDATE
548 */
549 public function UPDATEquery($table, $where, $fields_values, $no_quote_fields = FALSE) {
550 // Table and fieldnames should be "SQL-injection-safe" when supplied to this
551 // function (contrary to values in the arrays which may be insecure).
552 if (is_string($where)) {
553 foreach ($this->preProcessHookObjects as $hookObject) {
554 /** @var $hookObject PreProcessQueryHookInterface */
555 $hookObject->UPDATEquery_preProcessAction($table, $where, $fields_values, $no_quote_fields, $this);
556 }
557 $fields = array();
558 if (is_array($fields_values) && count($fields_values)) {
559 // Quote and escape values
560 $nArr = $this->fullQuoteArray($fields_values, $table, $no_quote_fields, TRUE);
561 foreach ($nArr as $k => $v) {
562 $fields[] = $k . '=' . $v;
563 }
564 }
565 // Build query
566 $query = 'UPDATE ' . $table . ' SET ' . implode(',', $fields) . ((string)$where !== '' ? ' WHERE ' . $where : '');
567 if ($this->debugOutput || $this->store_lastBuiltQuery) {
568 $this->debug_lastBuiltQuery = $query;
569 }
570 return $query;
571 } else {
572 throw new \InvalidArgumentException('TYPO3 Fatal Error: "Where" clause argument for UPDATE query was not a string in $this->UPDATEquery() !', 1270853880);
573 }
574 }
575
576 /**
577 * Creates a DELETE SQL-statement for $table where $where-clause
578 *
579 * @param string $table See exec_DELETEquery()
580 * @param string $where See exec_DELETEquery()
581 * @return string Full SQL query for DELETE
582 * @throws \InvalidArgumentException
583 */
584 public function DELETEquery($table, $where) {
585 if (is_string($where)) {
586 foreach ($this->preProcessHookObjects as $hookObject) {
587 /** @var $hookObject PreProcessQueryHookInterface */
588 $hookObject->DELETEquery_preProcessAction($table, $where, $this);
589 }
590 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
591 $query = 'DELETE FROM ' . $table . ((string)$where !== '' ? ' WHERE ' . $where : '');
592 if ($this->debugOutput || $this->store_lastBuiltQuery) {
593 $this->debug_lastBuiltQuery = $query;
594 }
595 return $query;
596 } else {
597 throw new \InvalidArgumentException('TYPO3 Fatal Error: "Where" clause argument for DELETE query was not a string in $this->DELETEquery() !', 1270853881);
598 }
599 }
600
601 /**
602 * Creates a SELECT SQL-statement
603 *
604 * @param string $select_fields See exec_SELECTquery()
605 * @param string $from_table See exec_SELECTquery()
606 * @param string $where_clause See exec_SELECTquery()
607 * @param string $groupBy See exec_SELECTquery()
608 * @param string $orderBy See exec_SELECTquery()
609 * @param string $limit See exec_SELECTquery()
610 * @return string Full SQL query for SELECT
611 */
612 public function SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
613 foreach ($this->preProcessHookObjects as $hookObject) {
614 /** @var $hookObject PreProcessQueryHookInterface */
615 $hookObject->SELECTquery_preProcessAction($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit, $this);
616 }
617 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
618 // Build basic query
619 $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table . ((string)$where_clause !== '' ? ' WHERE ' . $where_clause : '');
620 // Group by
621 $query .= (string)$groupBy !== '' ? ' GROUP BY ' . $groupBy : '';
622 // Order by
623 $query .= (string)$orderBy !== '' ? ' ORDER BY ' . $orderBy : '';
624 // Group by
625 $query .= (string)$limit !== '' ? ' LIMIT ' . $limit : '';
626 // Return query
627 if ($this->debugOutput || $this->store_lastBuiltQuery) {
628 $this->debug_lastBuiltQuery = $query;
629 }
630 return $query;
631 }
632
633 /**
634 * Creates a SELECT SQL-statement to be used as subquery within another query.
635 * BEWARE: This method should not be overriden within DBAL to prevent quoting from happening.
636 *
637 * @param string $select_fields List of fields to select from the table.
638 * @param string $from_table Table from which to select.
639 * @param string $where_clause Conditional WHERE statement
640 * @return string Full SQL query for SELECT
641 */
642 public function SELECTsubquery($select_fields, $from_table, $where_clause) {
643 // Table and fieldnames should be "SQL-injection-safe" when supplied to this function
644 // Build basic query:
645 $query = 'SELECT ' . $select_fields . ' FROM ' . $from_table . ((string)$where_clause !== '' ? ' WHERE ' . $where_clause : '');
646 // Return query
647 if ($this->debugOutput || $this->store_lastBuiltQuery) {
648 $this->debug_lastBuiltQuery = $query;
649 }
650 return $query;
651 }
652
653 /**
654 * Creates a TRUNCATE TABLE SQL-statement
655 *
656 * @param string $table See exec_TRUNCATEquery()
657 * @return string Full SQL query for TRUNCATE TABLE
658 */
659 public function TRUNCATEquery($table) {
660 foreach ($this->preProcessHookObjects as $hookObject) {
661 /** @var $hookObject PreProcessQueryHookInterface */
662 $hookObject->TRUNCATEquery_preProcessAction($table, $this);
663 }
664 // Table should be "SQL-injection-safe" when supplied to this function
665 // Build basic query:
666 $query = 'TRUNCATE TABLE ' . $table;
667 // Return query:
668 if ($this->debugOutput || $this->store_lastBuiltQuery) {
669 $this->debug_lastBuiltQuery = $query;
670 }
671 return $query;
672 }
673
674 /**
675 * Returns a WHERE clause that can find a value ($value) in a list field ($field)
676 * For instance a record in the database might contain a list of numbers,
677 * "34,234,5" (with no spaces between). This query would be able to select that
678 * record based on the value "34", "234" or "5" regardless of their position in
679 * the list (left, middle or right).
680 * The value must not contain a comma (,)
681 * Is nice to look up list-relations to records or files in TYPO3 database tables.
682 *
683 * @param string $field Field name
684 * @param string $value Value to find in list
685 * @param string $table Table in which we are searching (for DBAL detection of quoteStr() method)
686 * @return string WHERE clause for a query
687 * @throws \InvalidArgumentException
688 */
689 public function listQuery($field, $value, $table) {
690 $value = (string)$value;
691 if (strpos($value, ',') !== FALSE) {
692 throw new \InvalidArgumentException('$value must not contain a comma (,) in $this->listQuery() !', 1294585862);
693 }
694 $pattern = $this->quoteStr($value, $table);
695 $where = 'FIND_IN_SET(\'' . $pattern . '\',' . $field . ')';
696 return $where;
697 }
698
699 /**
700 * Returns a WHERE clause which will make an AND or OR search for the words in the $searchWords array in any of the fields in array $fields.
701 *
702 * @param array $searchWords Array of search words
703 * @param array $fields Array of fields
704 * @param string $table Table in which we are searching (for DBAL detection of quoteStr() method)
705 * @param string $constraint How multiple search words have to match ('AND' or 'OR')
706 * @return string WHERE clause for search
707 */
708 public function searchQuery($searchWords, $fields, $table, $constraint = self::AND_Constraint) {
709 switch ($constraint) {
710 case self::OR_Constraint:
711 $constraint = 'OR';
712 break;
713 default:
714 $constraint = 'AND';
715 }
716
717 $queryParts = array();
718 foreach ($searchWords as $sw) {
719 $like = ' LIKE \'%' . $this->quoteStr($sw, $table) . '%\'';
720 $queryParts[] = $table . '.' . implode(($like . ' OR ' . $table . '.'), $fields) . $like;
721 }
722 $query = '(' . implode(') ' . $constraint . ' (', $queryParts) . ')';
723
724 return $query;
725 }
726
727 /**************************************
728 *
729 * Prepared Query Support
730 *
731 **************************************/
732 /**
733 * Creates a SELECT prepared SQL statement.
734 *
735 * @param string $select_fields See exec_SELECTquery()
736 * @param string $from_table See exec_SELECTquery()
737 * @param string $where_clause See exec_SELECTquery()
738 * @param string $groupBy See exec_SELECTquery()
739 * @param string $orderBy See exec_SELECTquery()
740 * @param string $limit See exec_SELECTquery()
741 * @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 \TYPO3\CMS\Core\Database\PreparedStatement::PARAM_AUTOTYPE.
742 * @return \TYPO3\CMS\Core\Database\PreparedStatement Prepared statement
743 */
744 public function prepare_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '', array $input_parameters = array()) {
745 $query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
746 /** @var $preparedStatement \TYPO3\CMS\Core\Database\PreparedStatement */
747 $preparedStatement = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\PreparedStatement', $query, $from_table, array());
748 // Bind values to parameters
749 foreach ($input_parameters as $key => $value) {
750 $preparedStatement->bindValue($key, $value, PreparedStatement::PARAM_AUTOTYPE);
751 }
752 // Return prepared statement
753 return $preparedStatement;
754 }
755
756 /**
757 * Creates a SELECT prepared SQL statement based on input query parts array
758 *
759 * @param array $queryParts Query parts array
760 * @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 \TYPO3\CMS\Core\Database\PreparedStatement::PARAM_AUTOTYPE.
761 * @return \TYPO3\CMS\Core\Database\PreparedStatement Prepared statement
762 */
763 public function prepare_SELECTqueryArray(array $queryParts, array $input_parameters = array()) {
764 return $this->prepare_SELECTquery($queryParts['SELECT'], $queryParts['FROM'], $queryParts['WHERE'], $queryParts['GROUPBY'], $queryParts['ORDERBY'], $queryParts['LIMIT'], $input_parameters);
765 }
766
767 /**
768 * Executes a prepared query.
769 * This method may only be called by \TYPO3\CMS\Core\Database\PreparedStatement
770 *
771 * @param string $query The query to execute
772 * @param array $queryComponents The components of the query to execute
773 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
774 */
775 public function exec_PREPAREDquery($query, array $queryComponents) {
776 $res = $this->query($query);
777 if ($this->debugOutput) {
778 $this->debug('stmt_execute', $query);
779 }
780 return $res;
781 }
782
783 /**************************************
784 *
785 * Various helper functions
786 *
787 * Functions recommended to be used for
788 * - escaping values,
789 * - cleaning lists of values,
790 * - stripping of excess ORDER BY/GROUP BY keywords
791 *
792 **************************************/
793 /**
794 * Escaping and quoting values for SQL statements.
795 *
796 * @param string $str Input string
797 * @param string $table 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!).
798 * @param boolean $allowNull Whether to allow NULL values
799 * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
800 * @see quoteStr()
801 */
802 public function fullQuoteStr($str, $table, $allowNull = FALSE) {
803 if (!$this->isConnected) {
804 $this->connectDB();
805 }
806 if ($allowNull && $str === NULL) {
807 return 'NULL';
808 }
809
810 return '\'' . $this->link->real_escape_string($str) . '\'';
811 }
812
813 /**
814 * Will fullquote all values in the one-dimensional array so they are ready to "implode" for an sql query.
815 *
816 * @param array $arr Array with values (either associative or non-associative array)
817 * @param string $table Table name for which to quote
818 * @param boolean|array $noQuote List/array of keys NOT to quote (eg. SQL functions) - ONLY for associative arrays
819 * @param boolean $allowNull Whether to allow NULL values
820 * @return array The input array with the values quoted
821 * @see cleanIntArray()
822 */
823 public function fullQuoteArray($arr, $table, $noQuote = FALSE, $allowNull = FALSE) {
824 if (is_string($noQuote)) {
825 $noQuote = explode(',', $noQuote);
826 } elseif (!is_array($noQuote)) {
827 $noQuote = FALSE;
828 }
829 foreach ($arr as $k => $v) {
830 if ($noQuote === FALSE || !in_array($k, $noQuote)) {
831 $arr[$k] = $this->fullQuoteStr($v, $table, $allowNull);
832 }
833 }
834 return $arr;
835 }
836
837 /**
838 * Substitution for PHP function "addslashes()"
839 * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
840 * 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()!
841 *
842 * @param string $str Input string
843 * @param string $table 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!).
844 * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
845 * @see quoteStr()
846 */
847 public function quoteStr($str, $table) {
848 if (!$this->isConnected) {
849 $this->connectDB();
850 }
851 return $this->link->real_escape_string($str);
852 }
853
854 /**
855 * Escaping values for SQL LIKE statements.
856 *
857 * @param string $str Input string
858 * @param string $table 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!).
859 * @return string Output string; % and _ will be escaped with \ (or otherwise based on DBAL handler)
860 * @see quoteStr()
861 */
862 public function escapeStrForLike($str, $table) {
863 return addcslashes($str, '_%');
864 }
865
866 /**
867 * Will convert all values in the one-dimensional array to integers.
868 * Useful when you want to make sure an array contains only integers before imploding them in a select-list.
869 *
870 * @param array $arr Array with values
871 * @return array The input array with all values cast to (int)
872 * @see cleanIntList()
873 */
874 public function cleanIntArray($arr) {
875 foreach ($arr as $k => $v) {
876 $arr[$k] = (int)$arr[$k];
877 }
878 return $arr;
879 }
880
881 /**
882 * Will force all entries in the input comma list to integers
883 * 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.
884 *
885 * @param string $list List of comma-separated values which should be integers
886 * @return string The input list but with every value cast to (int)
887 * @see cleanIntArray()
888 */
889 public function cleanIntList($list) {
890 return implode(',', GeneralUtility::intExplode(',', $list));
891 }
892
893 /**
894 * Removes the prefix "ORDER BY" from the input string.
895 * 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.
896 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
897 *
898 * @param string $str eg. "ORDER BY title, uid
899 * @return string eg. "title, uid
900 * @see exec_SELECTquery(), stripGroupBy()
901 */
902 public function stripOrderBy($str) {
903 return preg_replace('/^(?:ORDER[[:space:]]*BY[[:space:]]*)+/i', '', trim($str));
904 }
905
906 /**
907 * Removes the prefix "GROUP BY" from the input string.
908 * 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.
909 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
910 *
911 * @param string $str eg. "GROUP BY title, uid
912 * @return string eg. "title, uid
913 * @see exec_SELECTquery(), stripOrderBy()
914 */
915 public function stripGroupBy($str) {
916 return preg_replace('/^(?:GROUP[[:space:]]*BY[[:space:]]*)+/i', '', trim($str));
917 }
918
919 /**
920 * 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)
921 * Work-around function for use where you know some userdefined end to an SQL clause is supplied and you need to separate these factors.
922 *
923 * @param string $str Input string
924 * @return array
925 */
926 public function splitGroupOrderLimit($str) {
927 // Prepending a space to make sure "[[:space:]]+" will find a space there
928 // for the first element.
929 $str = ' ' . $str;
930 // Init output array:
931 $wgolParts = array(
932 'WHERE' => '',
933 'GROUPBY' => '',
934 'ORDERBY' => '',
935 'LIMIT' => ''
936 );
937 // Find LIMIT
938 $reg = array();
939 if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
940 $wgolParts['LIMIT'] = trim($reg[2]);
941 $str = $reg[1];
942 }
943 // Find ORDER BY
944 $reg = array();
945 if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
946 $wgolParts['ORDERBY'] = trim($reg[2]);
947 $str = $reg[1];
948 }
949 // Find GROUP BY
950 $reg = array();
951 if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
952 $wgolParts['GROUPBY'] = trim($reg[2]);
953 $str = $reg[1];
954 }
955 // Rest is assumed to be "WHERE" clause
956 $wgolParts['WHERE'] = $str;
957 return $wgolParts;
958 }
959
960 /**
961 * Returns the date and time formats compatible with the given database table.
962 *
963 * @param string $table Table name for which to return an empty date. Just enter the table that the field-value is selected from (and any DBAL will look up which handler to use and then how date and time should be formatted).
964 * @return array
965 */
966 public function getDateTimeFormats($table) {
967 return array(
968 'date' => array(
969 'empty' => '0000-00-00',
970 'format' => 'Y-m-d'
971 ),
972 'datetime' => array(
973 'empty' => '0000-00-00 00:00:00',
974 'format' => 'Y-m-d H:i:s'
975 )
976 );
977 }
978
979 /**************************************
980 *
981 * MySQL(i) wrapper functions
982 * (For use in your applications)
983 *
984 **************************************/
985 /**
986 * Executes query
987 * MySQLi query() wrapper function
988 * Beware: Use of this method should be avoided as it is experimentally supported by DBAL. You should consider
989 * using exec_SELECTquery() and similar methods instead.
990 *
991 * @param string $query Query to execute
992 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
993 */
994 public function sql_query($query) {
995 $res = $this->query($query);
996 if ($this->debugOutput) {
997 $this->debug('sql_query', $query);
998 }
999 return $res;
1000 }
1001
1002 /**
1003 * Returns the error status on the last query() execution
1004 *
1005 * @return string MySQLi error string.
1006 */
1007 public function sql_error() {
1008 return $this->link->error;
1009 }
1010
1011 /**
1012 * Returns the error number on the last query() execution
1013 *
1014 * @return integer MySQLi error number
1015 */
1016 public function sql_errno() {
1017 return $this->link->errno;
1018 }
1019
1020 /**
1021 * Returns the number of selected rows.
1022 *
1023 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1024 * @return integer Number of resulting rows
1025 */
1026 public function sql_num_rows($res) {
1027 if ($this->debug_check_recordset($res)) {
1028 return $res->num_rows;
1029 } else {
1030 return FALSE;
1031 }
1032 }
1033
1034 /**
1035 * Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
1036 * MySQLi fetch_assoc() wrapper function
1037 *
1038 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1039 * @return array|boolean Associative array of result row.
1040 */
1041 public function sql_fetch_assoc($res) {
1042 if ($this->debug_check_recordset($res)) {
1043 $result = $res->fetch_assoc();
1044 if ($result === NULL) {
1045 // Needed for compatibility
1046 $result = FALSE;
1047 }
1048 return $result;
1049 } else {
1050 return FALSE;
1051 }
1052 }
1053
1054 /**
1055 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
1056 * The array contains the values in numerical indices.
1057 * MySQLi fetch_row() wrapper function
1058 *
1059 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1060 * @return array|boolean Array with result rows.
1061 */
1062 public function sql_fetch_row($res) {
1063 if ($this->debug_check_recordset($res)) {
1064 $result = $res->fetch_row();
1065 if ($result === NULL) {
1066 // Needed for compatibility
1067 $result = FALSE;
1068 }
1069 return $result;
1070 } else {
1071 return FALSE;
1072 }
1073 }
1074
1075 /**
1076 * Free result memory
1077 * free_result() wrapper function
1078 *
1079 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1080 * @return boolean Returns TRUE on success or FALSE on failure.
1081 */
1082 public function sql_free_result($res) {
1083 if ($this->debug_check_recordset($res)) {
1084 return $res->free();
1085 } else {
1086 return FALSE;
1087 }
1088 }
1089
1090 /**
1091 * Get the ID generated from the previous INSERT operation
1092 *
1093 * @return integer The uid of the last inserted record.
1094 */
1095 public function sql_insert_id() {
1096 return $this->link->insert_id;
1097 }
1098
1099 /**
1100 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
1101 *
1102 * @return integer Number of rows affected by last query
1103 */
1104 public function sql_affected_rows() {
1105 return $this->link->affected_rows;
1106 }
1107
1108 /**
1109 * Move internal result pointer
1110 *
1111 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1112 * @param integer $seek Seek result number.
1113 * @return boolean Returns TRUE on success or FALSE on failure.
1114 */
1115 public function sql_data_seek($res, $seek) {
1116 if ($this->debug_check_recordset($res)) {
1117 return $res->data_seek($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 *
1127 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1128 * @param integer $pointer Field index.
1129 * @return string Returns the name of the specified field index, or FALSE on error
1130 */
1131 public function sql_field_type($res, $pointer) {
1132 // mysql_field_type compatibility map
1133 // taken from: http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php#89117
1134 // Constant numbers see http://php.net/manual/en/mysqli.constants.php
1135 $mysql_data_type_hash = array(
1136 1=>'tinyint',
1137 2=>'smallint',
1138 3=>'int',
1139 4=>'float',
1140 5=>'double',
1141 7=>'timestamp',
1142 8=>'bigint',
1143 9=>'mediumint',
1144 10=>'date',
1145 11=>'time',
1146 12=>'datetime',
1147 13=>'year',
1148 16=>'bit',
1149 //252 is currently mapped to all text and blob types (MySQL 5.0.51a)
1150 253=>'varchar',
1151 254=>'char',
1152 246=>'decimal'
1153 );
1154 if ($this->debug_check_recordset($res)) {
1155 $metaInfo = $res->fetch_field_direct($pointer);
1156 if ($metaInfo === FALSE) {
1157 return FALSE;
1158 }
1159 return $mysql_data_type_hash[$metaInfo->type];
1160 } else {
1161 return FALSE;
1162 }
1163 }
1164
1165 /**
1166 * Open a (persistent) connection to a MySQL server
1167 *
1168 * @param string $host Deprecated since 6.1, will be removed in two versions. Database host IP/domain[:port]
1169 * @param string $username Deprecated since 6.1, will be removed in two versions. Username to connect with.
1170 * @param string $password Deprecated since 6.1, will be removed in two versions. Password to connect with.
1171 * @return boolean|void
1172 * @throws \RuntimeException
1173 */
1174 public function sql_pconnect($host = NULL, $username = NULL, $password = NULL) {
1175 if ($this->isConnected) {
1176 return $this->link;
1177 }
1178
1179 if (!extension_loaded('mysqli')) {
1180 throw new \RuntimeException(
1181 'Database Error: PHP mysqli extension not loaded. This is a must have for TYPO3 CMS!',
1182 1271492607
1183 );
1184 }
1185
1186 if ($host || $username || $password) {
1187 $this->handleDeprecatedConnectArguments($host, $username, $password);
1188 }
1189
1190 $host = $this->persistentDatabaseConnection
1191 ? 'p:' . $this->databaseHost
1192 : $this->databaseHost;
1193
1194 $this->link = mysqli_init();
1195 $connected = $this->link->real_connect(
1196 $host,
1197 $this->databaseUsername,
1198 $this->databaseUserPassword,
1199 NULL,
1200 (int)$this->databasePort,
1201 $this->databaseSocket,
1202 $this->connectionCompression ? MYSQLI_CLIENT_COMPRESS : 0
1203 );
1204
1205 if ($connected) {
1206 $this->isConnected = TRUE;
1207
1208 if ($this->link->set_charset($this->connectionCharset) === FALSE) {
1209 GeneralUtility::sysLog(
1210 'Error setting connection charset to "' . $this->connectionCharset . '"',
1211 'Core',
1212 GeneralUtility::SYSLOG_SEVERITY_ERROR
1213 );
1214 }
1215
1216 foreach ($this->initializeCommandsAfterConnect as $command) {
1217 if ($this->query($command) === FALSE) {
1218 GeneralUtility::sysLog(
1219 'Could not initialize DB connection with query "' . $command . '": ' . $this->sql_error(),
1220 'Core',
1221 GeneralUtility::SYSLOG_SEVERITY_ERROR
1222 );
1223 }
1224 }
1225 $this->setSqlMode();
1226 $this->checkConnectionCharset();
1227 } else {
1228 // @TODO: This should raise an exception. Would be useful especially to work during installation.
1229 $error_msg = $this->link->connect_error;
1230 $this->link = NULL;
1231 GeneralUtility::sysLog(
1232 'Could not connect to MySQL server ' . $host . ' with user ' . $username . ': ' . $error_msg,
1233 'Core',
1234 GeneralUtility::SYSLOG_SEVERITY_FATAL
1235 );
1236 }
1237 return $this->link;
1238 }
1239
1240 /**
1241 * Fixes the SQL mode by unsetting NO_BACKSLASH_ESCAPES if found.
1242 *
1243 * @return void
1244 */
1245 protected function setSqlMode() {
1246 $resource = $this->sql_query('SELECT @@SESSION.sql_mode;');
1247 if ($resource) {
1248 $result = $this->sql_fetch_row($resource);
1249 if (isset($result[0]) && $result[0] && strpos($result[0], 'NO_BACKSLASH_ESCAPES') !== FALSE) {
1250 $modes = array_diff(GeneralUtility::trimExplode(',', $result[0]), array('NO_BACKSLASH_ESCAPES'));
1251 $query = 'SET sql_mode=\'' . $this->link->real_escape_string(implode(',', $modes)) . '\';';
1252 $this->sql_query($query);
1253 GeneralUtility::sysLog(
1254 'NO_BACKSLASH_ESCAPES could not be removed from SQL mode: ' . $this->sql_error(),
1255 'Core',
1256 GeneralUtility::SYSLOG_SEVERITY_ERROR
1257 );
1258 }
1259 }
1260 }
1261
1262 /**
1263 * Select a SQL database
1264 *
1265 * @param string $TYPO3_db Deprecated since 6.1, will be removed in two versions. Database to connect to.
1266 * @return boolean Returns TRUE on success or FALSE on failure.
1267 */
1268 public function sql_select_db($TYPO3_db = NULL) {
1269 if (!$this->isConnected) {
1270 $this->connectDB();
1271 }
1272
1273 if ($TYPO3_db) {
1274 GeneralUtility::deprecationLog(
1275 'DatabaseConnection->sql_select_db() should be called without arguments.' .
1276 ' Use the setDatabaseName() before. Will be removed two versions after 6.1.'
1277 );
1278 } else {
1279 $TYPO3_db = $this->databaseName;
1280 }
1281
1282 $ret = $this->link->select_db($TYPO3_db);
1283 if (!$ret) {
1284 GeneralUtility::sysLog(
1285 'Could not select MySQL database ' . $TYPO3_db . ': ' . $this->sql_error(),
1286 'Core',
1287 GeneralUtility::SYSLOG_SEVERITY_FATAL
1288 );
1289 }
1290 return $ret;
1291 }
1292
1293 /**************************************
1294 *
1295 * SQL admin functions
1296 * (For use in the Install Tool and Extension Manager)
1297 *
1298 **************************************/
1299 /**
1300 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
1301 * This is only used as a service function in the (1-2-3 process) of the Install Tool.
1302 * In any case a lookup should be done in the _DEFAULT handler DBMS then.
1303 * Use in Install Tool only!
1304 *
1305 * @return array Each entry represents a database name
1306 * @throws \RuntimeException
1307 */
1308 public function admin_get_dbs() {
1309 $dbArr = array();
1310 $db_list = $this->query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA");
1311 if ($db_list === FALSE) {
1312 throw new \RuntimeException(
1313 'MySQL Error: Cannot get tablenames: "' . $this->sql_error() . '"!',
1314 1378457171
1315 );
1316 } else {
1317 while ($row = $db_list->fetch_object()) {
1318 try {
1319 $this->setDatabaseName($row->SCHEMA_NAME);
1320 if ($this->sql_select_db()) {
1321 $dbArr[] = $row->SCHEMA_NAME;
1322 }
1323 } catch (\RuntimeException $exception) {
1324 // The exception happens if we cannot connect to the database
1325 // (usually due to missing permissions). This is ok here.
1326 // We catch the exception, skip the database and continue.
1327 }
1328 }
1329 }
1330 return $dbArr;
1331 }
1332
1333 /**
1334 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
1335 * In a DBAL this method should 1) look up all tables from the DBMS of
1336 * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
1337 *
1338 * @return array Array with tablenames as key and arrays with status information as value
1339 */
1340 public function admin_get_tables() {
1341 $whichTables = array();
1342 $tables_result = $this->query('SHOW TABLE STATUS FROM `' . $this->databaseName . '`');
1343 if ($tables_result !== FALSE) {
1344 while ($theTable = $tables_result->fetch_assoc()) {
1345 $whichTables[$theTable['Name']] = $theTable;
1346 }
1347 $tables_result->free();
1348 }
1349 return $whichTables;
1350 }
1351
1352 /**
1353 * Returns information about each field in the $table (quering the DBMS)
1354 * In a DBAL this should look up the right handler for the table and return compatible information
1355 * This function is important not only for the Install Tool but probably for
1356 * DBALs as well since they might need to look up table specific information
1357 * in order to construct correct queries. In such cases this information should
1358 * probably be cached for quick delivery.
1359 *
1360 * @param string $tableName Table name
1361 * @return array Field information in an associative array with fieldname => field row
1362 */
1363 public function admin_get_fields($tableName) {
1364 $output = array();
1365 $columns_res = $this->query('SHOW COLUMNS FROM `' . $tableName . '`');
1366 if ($columns_res !== FALSE) {
1367 while ($fieldRow = $columns_res->fetch_assoc()) {
1368 $output[$fieldRow['Field']] = $fieldRow;
1369 }
1370 $columns_res->free();
1371 }
1372 return $output;
1373 }
1374
1375 /**
1376 * Returns information about each index key in the $table (quering the DBMS)
1377 * In a DBAL this should look up the right handler for the table and return compatible information
1378 *
1379 * @param string $tableName Table name
1380 * @return array Key information in a numeric array
1381 */
1382 public function admin_get_keys($tableName) {
1383 $output = array();
1384 $keyRes = $this->query('SHOW KEYS FROM `' . $tableName . '`');
1385 if ($keyRes !== FALSE) {
1386 while ($keyRow = $keyRes->fetch_assoc()) {
1387 $output[] = $keyRow;
1388 }
1389 $keyRes->free();
1390 }
1391 return $output;
1392 }
1393
1394 /**
1395 * Returns information about the character sets supported by the current DBM
1396 * This function is important not only for the Install Tool but probably for
1397 * DBALs as well since they might need to look up table specific information
1398 * in order to construct correct queries. In such cases this information should
1399 * probably be cached for quick delivery.
1400 *
1401 * This is used by the Install Tool to convert tables with non-UTF8 charsets
1402 * Use in Install Tool only!
1403 *
1404 * @return array Array with Charset as key and an array of "Charset", "Description", "Default collation", "Maxlen" as values
1405 */
1406 public function admin_get_charsets() {
1407 $output = array();
1408 $columns_res = $this->query('SHOW CHARACTER SET');
1409 if ($columns_res !== FALSE) {
1410 while ($row = $columns_res->fetch_assoc()) {
1411 $output[$row['Charset']] = $row;
1412 }
1413 $columns_res->free();
1414 }
1415 return $output;
1416 }
1417
1418 /**
1419 * mysqli() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
1420 *
1421 * @param string $query Query to execute
1422 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
1423 */
1424 public function admin_query($query) {
1425 $res = $this->query($query);
1426 if ($this->debugOutput) {
1427 $this->debug('admin_query', $query);
1428 }
1429 return $res;
1430 }
1431
1432 /******************************
1433 *
1434 * Connect handling
1435 *
1436 ******************************/
1437
1438 /**
1439 * Set database host
1440 *
1441 * @param string $host
1442 */
1443 public function setDatabaseHost($host = 'localhost') {
1444 $this->disconnectIfConnected();
1445 $this->databaseHost = $host;
1446 }
1447
1448 /**
1449 * Set database port
1450 *
1451 * @param integer $port
1452 */
1453 public function setDatabasePort($port = 3306) {
1454 $this->disconnectIfConnected();
1455 $this->databasePort = (int)$port;
1456 }
1457
1458 /**
1459 * Set database socket
1460 *
1461 * @param string|NULL $socket
1462 */
1463 public function setDatabaseSocket($socket = NULL) {
1464 $this->disconnectIfConnected();
1465 $this->databaseSocket = $socket;
1466 }
1467
1468 /**
1469 * Set database name
1470 *
1471 * @param string $name
1472 */
1473 public function setDatabaseName($name) {
1474 $this->disconnectIfConnected();
1475 $this->databaseName = $name;
1476 }
1477
1478 /**
1479 * Set database username
1480 *
1481 * @param string $username
1482 */
1483 public function setDatabaseUsername($username) {
1484 $this->disconnectIfConnected();
1485 $this->databaseUsername = $username;
1486 }
1487
1488 /**
1489 * Set database password
1490 *
1491 * @param string $password
1492 */
1493 public function setDatabasePassword($password) {
1494 $this->disconnectIfConnected();
1495 $this->databaseUserPassword = $password;
1496 }
1497
1498 /**
1499 * Set persistent database connection
1500 *
1501 * @param boolean $persistentDatabaseConnection
1502 * @see http://php.net/manual/de/mysqli.persistconns.php
1503 */
1504 public function setPersistentDatabaseConnection($persistentDatabaseConnection) {
1505 $this->disconnectIfConnected();
1506 $this->persistentDatabaseConnection = (bool)$persistentDatabaseConnection;
1507 }
1508
1509 /**
1510 * Set connection compression. Might be an advantage, if SQL server is not on localhost
1511 *
1512 * @param bool $connectionCompression TRUE if connection should be compressed
1513 */
1514 public function setConnectionCompression($connectionCompression) {
1515 $this->disconnectIfConnected();
1516 $this->connectionCompression = (bool)$connectionCompression;
1517 }
1518
1519 /**
1520 * Set commands to be fired after connection was established
1521 *
1522 * @param array $commands List of SQL commands to be executed after connect
1523 */
1524 public function setInitializeCommandsAfterConnect(array $commands) {
1525 $this->disconnectIfConnected();
1526 $this->initializeCommandsAfterConnect = $commands;
1527 }
1528
1529 /**
1530 * Set the charset that should be used for the MySQL connection.
1531 * The given value will be passed on to mysqli_set_charset().
1532 *
1533 * The default value of this setting is utf8.
1534 *
1535 * @param string $connectionCharset The connection charset that will be passed on to mysqli_set_charset() when connecting the database. Default is utf8.
1536 * @return void
1537 */
1538 public function setConnectionCharset($connectionCharset = 'utf8') {
1539 $this->disconnectIfConnected();
1540 $this->connectionCharset = $connectionCharset;
1541 }
1542
1543 /**
1544 * Connects to database for TYPO3 sites:
1545 *
1546 * @param string $host Deprecated since 6.1, will be removed in two versions Database. host IP/domain[:port]
1547 * @param string $username Deprecated since 6.1, will be removed in two versions. Username to connect with
1548 * @param string $password Deprecated since 6.1, will be removed in two versions. Password to connect with
1549 * @param string $db Deprecated since 6.1, will be removed in two versions. Database name to connect to
1550 * @throws \RuntimeException
1551 * @throws \UnexpectedValueException
1552 * @internal param string $user Username to connect with.
1553 * @return void
1554 */
1555 public function connectDB($host = NULL, $username = NULL, $password = NULL, $db = NULL) {
1556 // Early return if connected already
1557 if ($this->isConnected) {
1558 return;
1559 }
1560
1561 if (!$this->databaseName && !$db) {
1562 throw new \RuntimeException(
1563 'TYPO3 Fatal Error: No database selected!',
1564 1270853882
1565 );
1566 }
1567
1568 if ($host || $username || $password || $db) {
1569 $this->handleDeprecatedConnectArguments($host, $username, $password, $db);
1570 }
1571
1572 if ($this->sql_pconnect()) {
1573 if (!$this->sql_select_db()) {
1574 throw new \RuntimeException(
1575 'TYPO3 Fatal Error: Cannot connect to the current database, "' . $this->databaseName . '"!',
1576 1270853883
1577 );
1578 }
1579 } else {
1580 throw new \RuntimeException(
1581 'TYPO3 Fatal Error: The current username, password or host was not accepted when the connection to the database was attempted to be established!',
1582 1270853884
1583 );
1584 }
1585
1586 // Prepare user defined objects (if any) for hooks which extend query methods
1587 $this->preProcessHookObjects = array();
1588 $this->postProcessHookObjects = array();
1589 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_db.php']['queryProcessors'])) {
1590 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_db.php']['queryProcessors'] as $classRef) {
1591 $hookObject = GeneralUtility::getUserObj($classRef);
1592 if (!(
1593 $hookObject instanceof PreProcessQueryHookInterface
1594 || $hookObject instanceof PostProcessQueryHookInterface
1595 )) {
1596 throw new \UnexpectedValueException(
1597 '$hookObject must either implement interface TYPO3\\CMS\\Core\\Database\\PreProcessQueryHookInterface or interface TYPO3\\CMS\\Core\\Database\\PostProcessQueryHookInterface',
1598 1299158548
1599 );
1600 }
1601 if ($hookObject instanceof PreProcessQueryHookInterface) {
1602 $this->preProcessHookObjects[] = $hookObject;
1603 }
1604 if ($hookObject instanceof PostProcessQueryHookInterface) {
1605 $this->postProcessHookObjects[] = $hookObject;
1606 }
1607 }
1608 }
1609 }
1610
1611 /**
1612 * Checks if database is connected
1613 *
1614 * @return boolean
1615 */
1616 public function isConnected() {
1617 // We think we're still connected
1618 if ($this->isConnected) {
1619 // Check if this is really the case or if the database server has gone away for some reason
1620 $this->isConnected = $this->link->ping();
1621 }
1622 return $this->isConnected;
1623 }
1624
1625 /**
1626 * Checks if the current connection character set has the same value
1627 * as the connectionCharset variable.
1628 *
1629 * To determine the character set these MySQL session variables are
1630 * checked: character_set_client, character_set_results and
1631 * character_set_connection.
1632 *
1633 * If the character set does not match or if the session variables
1634 * can not be read a RuntimeException is thrown.
1635 *
1636 * @return void
1637 * @throws \RuntimeException
1638 */
1639 protected function checkConnectionCharset() {
1640 $sessionResult = $this->sql_query('SHOW SESSION VARIABLES LIKE \'character_set%\'');
1641
1642 if ($sessionResult === FALSE) {
1643 GeneralUtility::sysLog(
1644 'Error while retrieving the current charset session variables from the database: ' . $this->sql_error(),
1645 'Core',
1646 GeneralUtility::SYSLOG_SEVERITY_ERROR
1647 );
1648 throw new \RuntimeException(
1649 'TYPO3 Fatal Error: Could not determine the current charset of the database.',
1650 1381847136
1651 );
1652 }
1653
1654 $charsetVariables = array();
1655 while (($row = $this->sql_fetch_row($sessionResult)) !== FALSE) {
1656 $variableName = $row[0];
1657 $variableValue = $row[1];
1658 $charsetVariables[$variableName] = $variableValue;
1659 }
1660 $this->sql_free_result($sessionResult);
1661
1662 // These variables are set with the "Set names" command which was
1663 // used in the past. This is why we check them.
1664 $charsetRequiredVariables = array(
1665 'character_set_client',
1666 'character_set_results',
1667 'character_set_connection',
1668 );
1669
1670 $hasValidCharset = TRUE;
1671 foreach ($charsetRequiredVariables as $variableName) {
1672 if (empty($charsetVariables[$variableName])) {
1673 GeneralUtility::sysLog(
1674 'A required session variable is missing in the current MySQL connection: ' . $variableName,
1675 'Core',
1676 GeneralUtility::SYSLOG_SEVERITY_ERROR
1677 );
1678 throw new \RuntimeException(
1679 'TYPO3 Fatal Error: Could not determine the value of the database session variable: ' . $variableName,
1680 1381847779
1681 );
1682 }
1683
1684 if ($charsetVariables[$variableName] !== $this->connectionCharset) {
1685 $hasValidCharset = FALSE;
1686 break;
1687 }
1688 }
1689
1690 if (!$hasValidCharset) {
1691 throw new \RuntimeException(
1692 'It looks like the character set ' . $this->connectionCharset . ' is not used for this connection even though it is configured as connection charset. ' .
1693 'This TYPO3 installation is using the $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'setDBinit\'] property with the following value: "' .
1694 $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'] . '". Please make sure that this command does not overwrite the configured charset. ' .
1695 'Please note that for the TYPO3 database everything other than utf8 is unsupported since version 4.7.',
1696 1389697515
1697 );
1698 }
1699 }
1700
1701 /**
1702 * Disconnect from database if connected
1703 *
1704 * @return void
1705 */
1706 protected function disconnectIfConnected() {
1707 if ($this->isConnected) {
1708 $this->link->close();
1709 $this->isConnected = FALSE;
1710 }
1711 }
1712
1713 /**
1714 * Returns current database handle
1715 *
1716 * @return \mysqli|NULL
1717 */
1718 public function getDatabaseHandle() {
1719 return $this->link;
1720 }
1721
1722 /**
1723 * Set current database handle, usually \mysqli
1724 *
1725 * @param \mysqli $handle
1726 */
1727 public function setDatabaseHandle($handle) {
1728 $this->link = $handle;
1729 }
1730
1731 /**
1732 * Handle deprecated arguments for sql_pconnect() and connectDB()
1733 *
1734 * @param string|null $host Database host[:port]
1735 * @param string|null $username Database user name
1736 * @param string|null $password User password
1737 * @param string|null $db Database
1738 */
1739 protected function handleDeprecatedConnectArguments($host = NULL, $username = NULL, $password = NULL, $db = NULL) {
1740 GeneralUtility::deprecationLog(
1741 'DatabaseConnection->sql_pconnect() and DatabaseConnection->connectDB() should be ' .
1742 'called without arguments. Use the setters instead.'
1743 );
1744 if ($host) {
1745 if (strpos($host, ':') > 0) {
1746 list($databaseHost, $databasePort) = explode(':', $host);
1747 $this->setDatabaseHost($databaseHost);
1748 $this->setDatabasePort($databasePort);
1749 } else {
1750 $this->setDatabaseHost($host);
1751 }
1752 }
1753 if ($username) {
1754 $this->setDatabaseUsername($username);
1755 }
1756 if ($password) {
1757 $this->setDatabasePassword($password);
1758 }
1759 if ($db) {
1760 $this->setDatabaseName($db);
1761 }
1762 }
1763
1764 /******************************
1765 *
1766 * Debugging
1767 *
1768 ******************************/
1769 /**
1770 * Debug function: Outputs error if any
1771 *
1772 * @param string $func Function calling debug()
1773 * @param string $query Last query if not last built query
1774 * @return void
1775 * @todo Define visibility
1776 */
1777 public function debug($func, $query = '') {
1778 $error = $this->sql_error();
1779 if ($error || (int)$this->debugOutput === 2) {
1780 \TYPO3\CMS\Core\Utility\DebugUtility::debug(
1781 array(
1782 'caller' => 'TYPO3\\CMS\\Core\\Database\\DatabaseConnection::' . $func,
1783 'ERROR' => $error,
1784 'lastBuiltQuery' => $query ? $query : $this->debug_lastBuiltQuery,
1785 'debug_backtrace' => \TYPO3\CMS\Core\Utility\DebugUtility::debugTrail()
1786 ),
1787 $func,
1788 is_object($GLOBALS['error']) && @is_callable(array($GLOBALS['error'], 'debug'))
1789 ? ''
1790 : 'DB Error'
1791 );
1792 }
1793 }
1794
1795 /**
1796 * Checks if record set is valid and writes debugging information into devLog if not.
1797 *
1798 * @param boolean|\mysqli_result|object MySQLi result object / DBAL object
1799 * @return boolean TRUE if the record set is valid, FALSE otherwise
1800 * @todo Define visibility
1801 */
1802 public function debug_check_recordset($res) {
1803 if ($res !== FALSE) {
1804 return TRUE;
1805 }
1806 $msg = 'Invalid database result detected';
1807 $trace = debug_backtrace();
1808 array_shift($trace);
1809 $cnt = count($trace);
1810 for ($i = 0; $i < $cnt; $i++) {
1811 // Complete objects are too large for the log
1812 if (isset($trace['object'])) {
1813 unset($trace['object']);
1814 }
1815 }
1816 $msg .= ': function TYPO3\\CMS\\Core\\Database\\DatabaseConnection->' . $trace[0]['function'] . ' called from file ' . substr($trace[0]['file'], (strlen(PATH_site) + 2)) . ' in line ' . $trace[0]['line'];
1817 GeneralUtility::sysLog(
1818 $msg . '. Use a devLog extension to get more details.',
1819 'Core/t3lib_db',
1820 GeneralUtility::SYSLOG_SEVERITY_ERROR
1821 );
1822 // Send to devLog if enabled
1823 if (TYPO3_DLOG) {
1824 $debugLogData = array(
1825 'SQL Error' => $this->sql_error(),
1826 'Backtrace' => $trace
1827 );
1828 if ($this->debug_lastBuiltQuery) {
1829 $debugLogData = array('SQL Query' => $this->debug_lastBuiltQuery) + $debugLogData;
1830 }
1831 GeneralUtility::devLog($msg . '.', 'Core/t3lib_db', 3, $debugLogData);
1832 }
1833 return FALSE;
1834 }
1835
1836 /**
1837 * Explain select queries
1838 * If $this->explainOutput is set, SELECT queries will be explained here. Only queries with more than one possible result row will be displayed.
1839 * The output is either printed as raw HTML output or embedded into the TS admin panel (checkbox must be enabled!)
1840 *
1841 * TODO: Feature is not DBAL-compliant
1842 *
1843 * @param string $query SQL query
1844 * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
1845 * @param integer $row_count Number of resulting rows
1846 * @return boolean TRUE if explain was run, FALSE otherwise
1847 */
1848 protected function explain($query, $from_table, $row_count) {
1849 $debugAllowedForIp = GeneralUtility::cmpIP(
1850 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1851 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1852 );
1853 if (
1854 (int)$this->explainOutput == 1
1855 || ((int)$this->explainOutput == 2 && $debugAllowedForIp)
1856 ) {
1857 // Raw HTML output
1858 $explainMode = 1;
1859 } elseif ((int)$this->explainOutput == 3 && is_object($GLOBALS['TT'])) {
1860 // Embed the output into the TS admin panel
1861 $explainMode = 2;
1862 } else {
1863 return FALSE;
1864 }
1865 $error = $this->sql_error();
1866 $trail = \TYPO3\CMS\Core\Utility\DebugUtility::debugTrail();
1867 $explain_tables = array();
1868 $explain_output = array();
1869 $res = $this->sql_query('EXPLAIN ' . $query, $this->link);
1870 if (is_a($res, '\\mysqli_result')) {
1871 while ($tempRow = $this->sql_fetch_assoc($res)) {
1872 $explain_output[] = $tempRow;
1873 $explain_tables[] = $tempRow['table'];
1874 }
1875 $this->sql_free_result($res);
1876 }
1877 $indices_output = array();
1878 // Notice: Rows are skipped if there is only one result, or if no conditions are set
1879 if (
1880 $explain_output[0]['rows'] > 1
1881 || GeneralUtility::inList('ALL', $explain_output[0]['type'])
1882 ) {
1883 // Only enable output if it's really useful
1884 $debug = TRUE;
1885 foreach ($explain_tables as $table) {
1886 $tableRes = $this->sql_query('SHOW TABLE STATUS LIKE \'' . $table . '\'');
1887 $isTable = $this->sql_num_rows($tableRes);
1888 if ($isTable) {
1889 $res = $this->sql_query('SHOW INDEX FROM ' . $table, $this->link);
1890 if (is_a($res, '\\mysqli_result')) {
1891 while ($tempRow = $this->sql_fetch_assoc($res)) {
1892 $indices_output[] = $tempRow;
1893 }
1894 $this->sql_free_result($res);
1895 }
1896 }
1897 $this->sql_free_result($tableRes);
1898 }
1899 } else {
1900 $debug = FALSE;
1901 }
1902 if ($debug) {
1903 if ($explainMode) {
1904 $data = array();
1905 $data['query'] = $query;
1906 $data['trail'] = $trail;
1907 $data['row_count'] = $row_count;
1908 if ($error) {
1909 $data['error'] = $error;
1910 }
1911 if (count($explain_output)) {
1912 $data['explain'] = $explain_output;
1913 }
1914 if (count($indices_output)) {
1915 $data['indices'] = $indices_output;
1916 }
1917 if ($explainMode == 1) {
1918 \TYPO3\CMS\Core\Utility\DebugUtility::debug($data, 'Tables: ' . $from_table, 'DB SQL EXPLAIN');
1919 } elseif ($explainMode == 2) {
1920 $GLOBALS['TT']->setTSselectQuery($data);
1921 }
1922 }
1923 return TRUE;
1924 }
1925 return FALSE;
1926 }
1927
1928 /**
1929 * Serialize destructs current connection
1930 *
1931 * @return array All protected properties that should be saved
1932 */
1933 public function __sleep() {
1934 $this->disconnectIfConnected();
1935 return array(
1936 'debugOutput',
1937 'explainOutput',
1938 'databaseHost',
1939 'databasePort',
1940 'databaseSocket',
1941 'databaseName',
1942 'databaseUsername',
1943 'databaseUserPassword',
1944 'persistentDatabaseConnection',
1945 'connectionCompression',
1946 'initializeCommandsAfterConnect',
1947 'default_charset',
1948 );
1949 }
1950 }