[TASK] Simplify TYPO3_DB->cleanIntArray
[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 * Prepares a prepared query.
769 *
770 * @param string $query The query to execute
771 * @param array $queryComponents The components of the query to execute
772 * @return \mysqli_statement|object MySQLi statement / DBAL object
773 * @internal This method may only be called by \TYPO3\CMS\Core\Database\PreparedStatement
774 */
775 public function prepare_PREPAREDquery($query, array $queryComponents) {
776 if (!$this->isConnected) {
777 $this->connectDB();
778 }
779 $stmt = $this->link->stmt_init();
780 $success = $stmt->prepare($query);
781 if ($this->debugOutput) {
782 $this->debug('stmt_execute', $query);
783 }
784 return $success ? $stmt : NULL;
785 }
786
787 /**************************************
788 *
789 * Various helper functions
790 *
791 * Functions recommended to be used for
792 * - escaping values,
793 * - cleaning lists of values,
794 * - stripping of excess ORDER BY/GROUP BY keywords
795 *
796 **************************************/
797 /**
798 * Escaping and quoting values for SQL statements.
799 *
800 * @param string $str Input string
801 * @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!).
802 * @param boolean $allowNull Whether to allow NULL values
803 * @return string Output string; Wrapped in single quotes and quotes in the string (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
804 * @see quoteStr()
805 */
806 public function fullQuoteStr($str, $table, $allowNull = FALSE) {
807 if (!$this->isConnected) {
808 $this->connectDB();
809 }
810 if ($allowNull && $str === NULL) {
811 return 'NULL';
812 }
813
814 return '\'' . $this->link->real_escape_string($str) . '\'';
815 }
816
817 /**
818 * Will fullquote all values in the one-dimensional array so they are ready to "implode" for an sql query.
819 *
820 * @param array $arr Array with values (either associative or non-associative array)
821 * @param string $table Table name for which to quote
822 * @param boolean|array $noQuote List/array of keys NOT to quote (eg. SQL functions) - ONLY for associative arrays
823 * @param boolean $allowNull Whether to allow NULL values
824 * @return array The input array with the values quoted
825 * @see cleanIntArray()
826 */
827 public function fullQuoteArray($arr, $table, $noQuote = FALSE, $allowNull = FALSE) {
828 if (is_string($noQuote)) {
829 $noQuote = explode(',', $noQuote);
830 } elseif (!is_array($noQuote)) {
831 $noQuote = FALSE;
832 }
833 foreach ($arr as $k => $v) {
834 if ($noQuote === FALSE || !in_array($k, $noQuote)) {
835 $arr[$k] = $this->fullQuoteStr($v, $table, $allowNull);
836 }
837 }
838 return $arr;
839 }
840
841 /**
842 * Substitution for PHP function "addslashes()"
843 * Use this function instead of the PHP addslashes() function when you build queries - this will prepare your code for DBAL.
844 * 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()!
845 *
846 * @param string $str Input string
847 * @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!).
848 * @return string Output string; Quotes (" / ') and \ will be backslashed (or otherwise based on DBAL handler)
849 * @see quoteStr()
850 */
851 public function quoteStr($str, $table) {
852 if (!$this->isConnected) {
853 $this->connectDB();
854 }
855 return $this->link->real_escape_string($str);
856 }
857
858 /**
859 * Escaping values for SQL LIKE statements.
860 *
861 * @param string $str Input string
862 * @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!).
863 * @return string Output string; % and _ will be escaped with \ (or otherwise based on DBAL handler)
864 * @see quoteStr()
865 */
866 public function escapeStrForLike($str, $table) {
867 return addcslashes($str, '_%');
868 }
869
870 /**
871 * Will convert all values in the one-dimensional array to integers.
872 * Useful when you want to make sure an array contains only integers before imploding them in a select-list.
873 *
874 * @param array $arr Array with values
875 * @return array The input array with all values cast to (int)
876 * @see cleanIntList()
877 */
878 public function cleanIntArray($arr) {
879 return array_map('intval', $arr);
880 }
881
882 /**
883 * Will force all entries in the input comma list to integers
884 * 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.
885 *
886 * @param string $list List of comma-separated values which should be integers
887 * @return string The input list but with every value cast to (int)
888 * @see cleanIntArray()
889 */
890 public function cleanIntList($list) {
891 return implode(',', GeneralUtility::intExplode(',', $list));
892 }
893
894 /**
895 * Removes the prefix "ORDER BY" from the input string.
896 * 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.
897 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
898 *
899 * @param string $str eg. "ORDER BY title, uid
900 * @return string eg. "title, uid
901 * @see exec_SELECTquery(), stripGroupBy()
902 */
903 public function stripOrderBy($str) {
904 return preg_replace('/^(?:ORDER[[:space:]]*BY[[:space:]]*)+/i', '', trim($str));
905 }
906
907 /**
908 * Removes the prefix "GROUP BY" from the input string.
909 * 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.
910 * Generally; This function provides a work-around to the situation where you cannot pass only the fields by which to order the result.
911 *
912 * @param string $str eg. "GROUP BY title, uid
913 * @return string eg. "title, uid
914 * @see exec_SELECTquery(), stripOrderBy()
915 */
916 public function stripGroupBy($str) {
917 return preg_replace('/^(?:GROUP[[:space:]]*BY[[:space:]]*)+/i', '', trim($str));
918 }
919
920 /**
921 * 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)
922 * Work-around function for use where you know some userdefined end to an SQL clause is supplied and you need to separate these factors.
923 *
924 * @param string $str Input string
925 * @return array
926 */
927 public function splitGroupOrderLimit($str) {
928 // Prepending a space to make sure "[[:space:]]+" will find a space there
929 // for the first element.
930 $str = ' ' . $str;
931 // Init output array:
932 $wgolParts = array(
933 'WHERE' => '',
934 'GROUPBY' => '',
935 'ORDERBY' => '',
936 'LIMIT' => ''
937 );
938 // Find LIMIT
939 $reg = array();
940 if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
941 $wgolParts['LIMIT'] = trim($reg[2]);
942 $str = $reg[1];
943 }
944 // Find ORDER BY
945 $reg = array();
946 if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
947 $wgolParts['ORDERBY'] = trim($reg[2]);
948 $str = $reg[1];
949 }
950 // Find GROUP BY
951 $reg = array();
952 if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $str, $reg)) {
953 $wgolParts['GROUPBY'] = trim($reg[2]);
954 $str = $reg[1];
955 }
956 // Rest is assumed to be "WHERE" clause
957 $wgolParts['WHERE'] = $str;
958 return $wgolParts;
959 }
960
961 /**
962 * Returns the date and time formats compatible with the given database table.
963 *
964 * @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).
965 * @return array
966 */
967 public function getDateTimeFormats($table) {
968 return array(
969 'date' => array(
970 'empty' => '0000-00-00',
971 'format' => 'Y-m-d'
972 ),
973 'datetime' => array(
974 'empty' => '0000-00-00 00:00:00',
975 'format' => 'Y-m-d H:i:s'
976 )
977 );
978 }
979
980 /**************************************
981 *
982 * MySQL(i) wrapper functions
983 * (For use in your applications)
984 *
985 **************************************/
986 /**
987 * Executes query
988 * MySQLi query() wrapper function
989 * Beware: Use of this method should be avoided as it is experimentally supported by DBAL. You should consider
990 * using exec_SELECTquery() and similar methods instead.
991 *
992 * @param string $query Query to execute
993 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
994 */
995 public function sql_query($query) {
996 $res = $this->query($query);
997 if ($this->debugOutput) {
998 $this->debug('sql_query', $query);
999 }
1000 return $res;
1001 }
1002
1003 /**
1004 * Returns the error status on the last query() execution
1005 *
1006 * @return string MySQLi error string.
1007 */
1008 public function sql_error() {
1009 return $this->link->error;
1010 }
1011
1012 /**
1013 * Returns the error number on the last query() execution
1014 *
1015 * @return integer MySQLi error number
1016 */
1017 public function sql_errno() {
1018 return $this->link->errno;
1019 }
1020
1021 /**
1022 * Returns the number of selected rows.
1023 *
1024 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1025 * @return integer Number of resulting rows
1026 */
1027 public function sql_num_rows($res) {
1028 if ($this->debug_check_recordset($res)) {
1029 return $res->num_rows;
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 * MySQLi fetch_assoc() wrapper function
1038 *
1039 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1040 * @return array|boolean Associative array of result row.
1041 */
1042 public function sql_fetch_assoc($res) {
1043 if ($this->debug_check_recordset($res)) {
1044 $result = $res->fetch_assoc();
1045 if ($result === NULL) {
1046 // Needed for compatibility
1047 $result = FALSE;
1048 }
1049 return $result;
1050 } else {
1051 return FALSE;
1052 }
1053 }
1054
1055 /**
1056 * Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
1057 * The array contains the values in numerical indices.
1058 * MySQLi fetch_row() wrapper function
1059 *
1060 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1061 * @return array|boolean Array with result rows.
1062 */
1063 public function sql_fetch_row($res) {
1064 if ($this->debug_check_recordset($res)) {
1065 $result = $res->fetch_row();
1066 if ($result === NULL) {
1067 // Needed for compatibility
1068 $result = FALSE;
1069 }
1070 return $result;
1071 } else {
1072 return FALSE;
1073 }
1074 }
1075
1076 /**
1077 * Free result memory
1078 * free_result() wrapper function
1079 *
1080 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1081 * @return boolean Returns TRUE on success or FALSE on failure.
1082 */
1083 public function sql_free_result($res) {
1084 if ($this->debug_check_recordset($res)) {
1085 return $res->free();
1086 } else {
1087 return FALSE;
1088 }
1089 }
1090
1091 /**
1092 * Get the ID generated from the previous INSERT operation
1093 *
1094 * @return integer The uid of the last inserted record.
1095 */
1096 public function sql_insert_id() {
1097 return $this->link->insert_id;
1098 }
1099
1100 /**
1101 * Returns the number of rows affected by the last INSERT, UPDATE or DELETE query
1102 *
1103 * @return integer Number of rows affected by last query
1104 */
1105 public function sql_affected_rows() {
1106 return $this->link->affected_rows;
1107 }
1108
1109 /**
1110 * Move internal result pointer
1111 *
1112 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1113 * @param integer $seek Seek result number.
1114 * @return boolean Returns TRUE on success or FALSE on failure.
1115 */
1116 public function sql_data_seek($res, $seek) {
1117 if ($this->debug_check_recordset($res)) {
1118 return $res->data_seek($seek);
1119 } else {
1120 return FALSE;
1121 }
1122 }
1123
1124 /**
1125 * Get the type of the specified field in a result
1126 * mysql_field_type() wrapper function
1127 *
1128 * @param boolean|\mysqli_result|object $res MySQLi result object / DBAL object
1129 * @param integer $pointer Field index.
1130 * @return string Returns the name of the specified field index, or FALSE on error
1131 */
1132 public function sql_field_type($res, $pointer) {
1133 // mysql_field_type compatibility map
1134 // taken from: http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php#89117
1135 // Constant numbers see http://php.net/manual/en/mysqli.constants.php
1136 $mysql_data_type_hash = array(
1137 1=>'tinyint',
1138 2=>'smallint',
1139 3=>'int',
1140 4=>'float',
1141 5=>'double',
1142 7=>'timestamp',
1143 8=>'bigint',
1144 9=>'mediumint',
1145 10=>'date',
1146 11=>'time',
1147 12=>'datetime',
1148 13=>'year',
1149 16=>'bit',
1150 //252 is currently mapped to all text and blob types (MySQL 5.0.51a)
1151 253=>'varchar',
1152 254=>'char',
1153 246=>'decimal'
1154 );
1155 if ($this->debug_check_recordset($res)) {
1156 $metaInfo = $res->fetch_field_direct($pointer);
1157 if ($metaInfo === FALSE) {
1158 return FALSE;
1159 }
1160 return $mysql_data_type_hash[$metaInfo->type];
1161 } else {
1162 return FALSE;
1163 }
1164 }
1165
1166 /**
1167 * Open a (persistent) connection to a MySQL server
1168 *
1169 * @param string $host Deprecated since 6.1, will be removed in two versions. Database host IP/domain[:port]
1170 * @param string $username Deprecated since 6.1, will be removed in two versions. Username to connect with.
1171 * @param string $password Deprecated since 6.1, will be removed in two versions. Password to connect with.
1172 * @return boolean|void
1173 * @throws \RuntimeException
1174 */
1175 public function sql_pconnect($host = NULL, $username = NULL, $password = NULL) {
1176 if ($this->isConnected) {
1177 return $this->link;
1178 }
1179
1180 if (!extension_loaded('mysqli')) {
1181 throw new \RuntimeException(
1182 'Database Error: PHP mysqli extension not loaded. This is a must have for TYPO3 CMS!',
1183 1271492607
1184 );
1185 }
1186
1187 if ($host || $username || $password) {
1188 $this->handleDeprecatedConnectArguments($host, $username, $password);
1189 }
1190
1191 $host = $this->persistentDatabaseConnection
1192 ? 'p:' . $this->databaseHost
1193 : $this->databaseHost;
1194
1195 $this->link = mysqli_init();
1196 $connected = $this->link->real_connect(
1197 $host,
1198 $this->databaseUsername,
1199 $this->databaseUserPassword,
1200 NULL,
1201 (int)$this->databasePort,
1202 $this->databaseSocket,
1203 $this->connectionCompression ? MYSQLI_CLIENT_COMPRESS : 0
1204 );
1205
1206 if ($connected) {
1207 $this->isConnected = TRUE;
1208
1209 if ($this->link->set_charset($this->connectionCharset) === FALSE) {
1210 GeneralUtility::sysLog(
1211 'Error setting connection charset to "' . $this->connectionCharset . '"',
1212 'Core',
1213 GeneralUtility::SYSLOG_SEVERITY_ERROR
1214 );
1215 }
1216
1217 foreach ($this->initializeCommandsAfterConnect as $command) {
1218 if ($this->query($command) === FALSE) {
1219 GeneralUtility::sysLog(
1220 'Could not initialize DB connection with query "' . $command . '": ' . $this->sql_error(),
1221 'Core',
1222 GeneralUtility::SYSLOG_SEVERITY_ERROR
1223 );
1224 }
1225 }
1226 $this->setSqlMode();
1227 $this->checkConnectionCharset();
1228 } else {
1229 // @TODO: This should raise an exception. Would be useful especially to work during installation.
1230 $error_msg = $this->link->connect_error;
1231 $this->link = NULL;
1232 GeneralUtility::sysLog(
1233 'Could not connect to MySQL server ' . $host . ' with user ' . $username . ': ' . $error_msg,
1234 'Core',
1235 GeneralUtility::SYSLOG_SEVERITY_FATAL
1236 );
1237 }
1238 return $this->link;
1239 }
1240
1241 /**
1242 * Fixes the SQL mode by unsetting NO_BACKSLASH_ESCAPES if found.
1243 *
1244 * @return void
1245 */
1246 protected function setSqlMode() {
1247 $resource = $this->sql_query('SELECT @@SESSION.sql_mode;');
1248 if ($resource) {
1249 $result = $this->sql_fetch_row($resource);
1250 if (isset($result[0]) && $result[0] && strpos($result[0], 'NO_BACKSLASH_ESCAPES') !== FALSE) {
1251 $modes = array_diff(GeneralUtility::trimExplode(',', $result[0]), array('NO_BACKSLASH_ESCAPES'));
1252 $query = 'SET sql_mode=\'' . $this->link->real_escape_string(implode(',', $modes)) . '\';';
1253 $this->sql_query($query);
1254 GeneralUtility::sysLog(
1255 'NO_BACKSLASH_ESCAPES could not be removed from SQL mode: ' . $this->sql_error(),
1256 'Core',
1257 GeneralUtility::SYSLOG_SEVERITY_ERROR
1258 );
1259 }
1260 }
1261 }
1262
1263 /**
1264 * Select a SQL database
1265 *
1266 * @param string $TYPO3_db Deprecated since 6.1, will be removed in two versions. Database to connect to.
1267 * @return boolean Returns TRUE on success or FALSE on failure.
1268 */
1269 public function sql_select_db($TYPO3_db = NULL) {
1270 if (!$this->isConnected) {
1271 $this->connectDB();
1272 }
1273
1274 if ($TYPO3_db) {
1275 GeneralUtility::deprecationLog(
1276 'DatabaseConnection->sql_select_db() should be called without arguments.' .
1277 ' Use the setDatabaseName() before. Will be removed two versions after 6.1.'
1278 );
1279 } else {
1280 $TYPO3_db = $this->databaseName;
1281 }
1282
1283 $ret = $this->link->select_db($TYPO3_db);
1284 if (!$ret) {
1285 GeneralUtility::sysLog(
1286 'Could not select MySQL database ' . $TYPO3_db . ': ' . $this->sql_error(),
1287 'Core',
1288 GeneralUtility::SYSLOG_SEVERITY_FATAL
1289 );
1290 }
1291 return $ret;
1292 }
1293
1294 /**************************************
1295 *
1296 * SQL admin functions
1297 * (For use in the Install Tool and Extension Manager)
1298 *
1299 **************************************/
1300 /**
1301 * Listing databases from current MySQL connection. NOTICE: It WILL try to select those databases and thus break selection of current database.
1302 * This is only used as a service function in the (1-2-3 process) of the Install Tool.
1303 * In any case a lookup should be done in the _DEFAULT handler DBMS then.
1304 * Use in Install Tool only!
1305 *
1306 * @return array Each entry represents a database name
1307 * @throws \RuntimeException
1308 */
1309 public function admin_get_dbs() {
1310 $dbArr = array();
1311 $db_list = $this->query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA");
1312 if ($db_list === FALSE) {
1313 throw new \RuntimeException(
1314 'MySQL Error: Cannot get tablenames: "' . $this->sql_error() . '"!',
1315 1378457171
1316 );
1317 } else {
1318 while ($row = $db_list->fetch_object()) {
1319 try {
1320 $this->setDatabaseName($row->SCHEMA_NAME);
1321 if ($this->sql_select_db()) {
1322 $dbArr[] = $row->SCHEMA_NAME;
1323 }
1324 } catch (\RuntimeException $exception) {
1325 // The exception happens if we cannot connect to the database
1326 // (usually due to missing permissions). This is ok here.
1327 // We catch the exception, skip the database and continue.
1328 }
1329 }
1330 }
1331 return $dbArr;
1332 }
1333
1334 /**
1335 * Returns the list of tables from the default database, TYPO3_db (quering the DBMS)
1336 * In a DBAL this method should 1) look up all tables from the DBMS of
1337 * the _DEFAULT handler and then 2) add all tables *configured* to be managed by other handlers
1338 *
1339 * @return array Array with tablenames as key and arrays with status information as value
1340 */
1341 public function admin_get_tables() {
1342 $whichTables = array();
1343 $tables_result = $this->query('SHOW TABLE STATUS FROM `' . $this->databaseName . '`');
1344 if ($tables_result !== FALSE) {
1345 while ($theTable = $tables_result->fetch_assoc()) {
1346 $whichTables[$theTable['Name']] = $theTable;
1347 }
1348 $tables_result->free();
1349 }
1350 return $whichTables;
1351 }
1352
1353 /**
1354 * Returns information about each field in the $table (quering the DBMS)
1355 * In a DBAL this should look up the right handler for the table and return compatible information
1356 * This function is important not only for the Install Tool but probably for
1357 * DBALs as well since they might need to look up table specific information
1358 * in order to construct correct queries. In such cases this information should
1359 * probably be cached for quick delivery.
1360 *
1361 * @param string $tableName Table name
1362 * @return array Field information in an associative array with fieldname => field row
1363 */
1364 public function admin_get_fields($tableName) {
1365 $output = array();
1366 $columns_res = $this->query('SHOW COLUMNS FROM `' . $tableName . '`');
1367 if ($columns_res !== FALSE) {
1368 while ($fieldRow = $columns_res->fetch_assoc()) {
1369 $output[$fieldRow['Field']] = $fieldRow;
1370 }
1371 $columns_res->free();
1372 }
1373 return $output;
1374 }
1375
1376 /**
1377 * Returns information about each index key in the $table (quering the DBMS)
1378 * In a DBAL this should look up the right handler for the table and return compatible information
1379 *
1380 * @param string $tableName Table name
1381 * @return array Key information in a numeric array
1382 */
1383 public function admin_get_keys($tableName) {
1384 $output = array();
1385 $keyRes = $this->query('SHOW KEYS FROM `' . $tableName . '`');
1386 if ($keyRes !== FALSE) {
1387 while ($keyRow = $keyRes->fetch_assoc()) {
1388 $output[] = $keyRow;
1389 }
1390 $keyRes->free();
1391 }
1392 return $output;
1393 }
1394
1395 /**
1396 * Returns information about the character sets supported by the current DBM
1397 * This function is important not only for the Install Tool but probably for
1398 * DBALs as well since they might need to look up table specific information
1399 * in order to construct correct queries. In such cases this information should
1400 * probably be cached for quick delivery.
1401 *
1402 * This is used by the Install Tool to convert tables with non-UTF8 charsets
1403 * Use in Install Tool only!
1404 *
1405 * @return array Array with Charset as key and an array of "Charset", "Description", "Default collation", "Maxlen" as values
1406 */
1407 public function admin_get_charsets() {
1408 $output = array();
1409 $columns_res = $this->query('SHOW CHARACTER SET');
1410 if ($columns_res !== FALSE) {
1411 while ($row = $columns_res->fetch_assoc()) {
1412 $output[$row['Charset']] = $row;
1413 }
1414 $columns_res->free();
1415 }
1416 return $output;
1417 }
1418
1419 /**
1420 * mysqli() wrapper function, used by the Install Tool and EM for all queries regarding management of the database!
1421 *
1422 * @param string $query Query to execute
1423 * @return boolean|\mysqli_result|object MySQLi result object / DBAL object
1424 */
1425 public function admin_query($query) {
1426 $res = $this->query($query);
1427 if ($this->debugOutput) {
1428 $this->debug('admin_query', $query);
1429 }
1430 return $res;
1431 }
1432
1433 /******************************
1434 *
1435 * Connect handling
1436 *
1437 ******************************/
1438
1439 /**
1440 * Set database host
1441 *
1442 * @param string $host
1443 */
1444 public function setDatabaseHost($host = 'localhost') {
1445 $this->disconnectIfConnected();
1446 $this->databaseHost = $host;
1447 }
1448
1449 /**
1450 * Set database port
1451 *
1452 * @param integer $port
1453 */
1454 public function setDatabasePort($port = 3306) {
1455 $this->disconnectIfConnected();
1456 $this->databasePort = (int)$port;
1457 }
1458
1459 /**
1460 * Set database socket
1461 *
1462 * @param string|NULL $socket
1463 */
1464 public function setDatabaseSocket($socket = NULL) {
1465 $this->disconnectIfConnected();
1466 $this->databaseSocket = $socket;
1467 }
1468
1469 /**
1470 * Set database name
1471 *
1472 * @param string $name
1473 */
1474 public function setDatabaseName($name) {
1475 $this->disconnectIfConnected();
1476 $this->databaseName = $name;
1477 }
1478
1479 /**
1480 * Set database username
1481 *
1482 * @param string $username
1483 */
1484 public function setDatabaseUsername($username) {
1485 $this->disconnectIfConnected();
1486 $this->databaseUsername = $username;
1487 }
1488
1489 /**
1490 * Set database password
1491 *
1492 * @param string $password
1493 */
1494 public function setDatabasePassword($password) {
1495 $this->disconnectIfConnected();
1496 $this->databaseUserPassword = $password;
1497 }
1498
1499 /**
1500 * Set persistent database connection
1501 *
1502 * @param boolean $persistentDatabaseConnection
1503 * @see http://php.net/manual/de/mysqli.persistconns.php
1504 */
1505 public function setPersistentDatabaseConnection($persistentDatabaseConnection) {
1506 $this->disconnectIfConnected();
1507 $this->persistentDatabaseConnection = (bool)$persistentDatabaseConnection;
1508 }
1509
1510 /**
1511 * Set connection compression. Might be an advantage, if SQL server is not on localhost
1512 *
1513 * @param bool $connectionCompression TRUE if connection should be compressed
1514 */
1515 public function setConnectionCompression($connectionCompression) {
1516 $this->disconnectIfConnected();
1517 $this->connectionCompression = (bool)$connectionCompression;
1518 }
1519
1520 /**
1521 * Set commands to be fired after connection was established
1522 *
1523 * @param array $commands List of SQL commands to be executed after connect
1524 */
1525 public function setInitializeCommandsAfterConnect(array $commands) {
1526 $this->disconnectIfConnected();
1527 $this->initializeCommandsAfterConnect = $commands;
1528 }
1529
1530 /**
1531 * Set the charset that should be used for the MySQL connection.
1532 * The given value will be passed on to mysqli_set_charset().
1533 *
1534 * The default value of this setting is utf8.
1535 *
1536 * @param string $connectionCharset The connection charset that will be passed on to mysqli_set_charset() when connecting the database. Default is utf8.
1537 * @return void
1538 */
1539 public function setConnectionCharset($connectionCharset = 'utf8') {
1540 $this->disconnectIfConnected();
1541 $this->connectionCharset = $connectionCharset;
1542 }
1543
1544 /**
1545 * Connects to database for TYPO3 sites:
1546 *
1547 * @param string $host Deprecated since 6.1, will be removed in two versions Database. host IP/domain[:port]
1548 * @param string $username Deprecated since 6.1, will be removed in two versions. Username to connect with
1549 * @param string $password Deprecated since 6.1, will be removed in two versions. Password to connect with
1550 * @param string $db Deprecated since 6.1, will be removed in two versions. Database name to connect to
1551 * @throws \RuntimeException
1552 * @throws \UnexpectedValueException
1553 * @internal param string $user Username to connect with.
1554 * @return void
1555 */
1556 public function connectDB($host = NULL, $username = NULL, $password = NULL, $db = NULL) {
1557 // Early return if connected already
1558 if ($this->isConnected) {
1559 return;
1560 }
1561
1562 if (!$this->databaseName && !$db) {
1563 throw new \RuntimeException(
1564 'TYPO3 Fatal Error: No database selected!',
1565 1270853882
1566 );
1567 }
1568
1569 if ($host || $username || $password || $db) {
1570 $this->handleDeprecatedConnectArguments($host, $username, $password, $db);
1571 }
1572
1573 if ($this->sql_pconnect()) {
1574 if (!$this->sql_select_db()) {
1575 throw new \RuntimeException(
1576 'TYPO3 Fatal Error: Cannot connect to the current database, "' . $this->databaseName . '"!',
1577 1270853883
1578 );
1579 }
1580 } else {
1581 throw new \RuntimeException(
1582 'TYPO3 Fatal Error: The current username, password or host was not accepted when the connection to the database was attempted to be established!',
1583 1270853884
1584 );
1585 }
1586
1587 // Prepare user defined objects (if any) for hooks which extend query methods
1588 $this->preProcessHookObjects = array();
1589 $this->postProcessHookObjects = array();
1590 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_db.php']['queryProcessors'])) {
1591 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_db.php']['queryProcessors'] as $classRef) {
1592 $hookObject = GeneralUtility::getUserObj($classRef);
1593 if (!(
1594 $hookObject instanceof PreProcessQueryHookInterface
1595 || $hookObject instanceof PostProcessQueryHookInterface
1596 )) {
1597 throw new \UnexpectedValueException(
1598 '$hookObject must either implement interface TYPO3\\CMS\\Core\\Database\\PreProcessQueryHookInterface or interface TYPO3\\CMS\\Core\\Database\\PostProcessQueryHookInterface',
1599 1299158548
1600 );
1601 }
1602 if ($hookObject instanceof PreProcessQueryHookInterface) {
1603 $this->preProcessHookObjects[] = $hookObject;
1604 }
1605 if ($hookObject instanceof PostProcessQueryHookInterface) {
1606 $this->postProcessHookObjects[] = $hookObject;
1607 }
1608 }
1609 }
1610 }
1611
1612 /**
1613 * Checks if database is connected
1614 *
1615 * @return boolean
1616 */
1617 public function isConnected() {
1618 // We think we're still connected
1619 if ($this->isConnected) {
1620 // Check if this is really the case or if the database server has gone away for some reason
1621 $this->isConnected = $this->link->ping();
1622 }
1623 return $this->isConnected;
1624 }
1625
1626 /**
1627 * Checks if the current connection character set has the same value
1628 * as the connectionCharset variable.
1629 *
1630 * To determine the character set these MySQL session variables are
1631 * checked: character_set_client, character_set_results and
1632 * character_set_connection.
1633 *
1634 * If the character set does not match or if the session variables
1635 * can not be read a RuntimeException is thrown.
1636 *
1637 * @return void
1638 * @throws \RuntimeException
1639 */
1640 protected function checkConnectionCharset() {
1641 $sessionResult = $this->sql_query('SHOW SESSION VARIABLES LIKE \'character_set%\'');
1642
1643 if ($sessionResult === FALSE) {
1644 GeneralUtility::sysLog(
1645 'Error while retrieving the current charset session variables from the database: ' . $this->sql_error(),
1646 'Core',
1647 GeneralUtility::SYSLOG_SEVERITY_ERROR
1648 );
1649 throw new \RuntimeException(
1650 'TYPO3 Fatal Error: Could not determine the current charset of the database.',
1651 1381847136
1652 );
1653 }
1654
1655 $charsetVariables = array();
1656 while (($row = $this->sql_fetch_row($sessionResult)) !== FALSE) {
1657 $variableName = $row[0];
1658 $variableValue = $row[1];
1659 $charsetVariables[$variableName] = $variableValue;
1660 }
1661 $this->sql_free_result($sessionResult);
1662
1663 // These variables are set with the "Set names" command which was
1664 // used in the past. This is why we check them.
1665 $charsetRequiredVariables = array(
1666 'character_set_client',
1667 'character_set_results',
1668 'character_set_connection',
1669 );
1670
1671 $hasValidCharset = TRUE;
1672 foreach ($charsetRequiredVariables as $variableName) {
1673 if (empty($charsetVariables[$variableName])) {
1674 GeneralUtility::sysLog(
1675 'A required session variable is missing in the current MySQL connection: ' . $variableName,
1676 'Core',
1677 GeneralUtility::SYSLOG_SEVERITY_ERROR
1678 );
1679 throw new \RuntimeException(
1680 'TYPO3 Fatal Error: Could not determine the value of the database session variable: ' . $variableName,
1681 1381847779
1682 );
1683 }
1684
1685 if ($charsetVariables[$variableName] !== $this->connectionCharset) {
1686 $hasValidCharset = FALSE;
1687 break;
1688 }
1689 }
1690
1691 if (!$hasValidCharset) {
1692 throw new \RuntimeException(
1693 'It looks like the character set ' . $this->connectionCharset . ' is not used for this connection even though it is configured as connection charset. ' .
1694 'This TYPO3 installation is using the $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'setDBinit\'] property with the following value: "' .
1695 $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'] . '". Please make sure that this command does not overwrite the configured charset. ' .
1696 'Please note that for the TYPO3 database everything other than utf8 is unsupported since version 4.7.',
1697 1389697515
1698 );
1699 }
1700 }
1701
1702 /**
1703 * Disconnect from database if connected
1704 *
1705 * @return void
1706 */
1707 protected function disconnectIfConnected() {
1708 if ($this->isConnected) {
1709 $this->link->close();
1710 $this->isConnected = FALSE;
1711 }
1712 }
1713
1714 /**
1715 * Returns current database handle
1716 *
1717 * @return \mysqli|NULL
1718 */
1719 public function getDatabaseHandle() {
1720 return $this->link;
1721 }
1722
1723 /**
1724 * Set current database handle, usually \mysqli
1725 *
1726 * @param \mysqli $handle
1727 */
1728 public function setDatabaseHandle($handle) {
1729 $this->link = $handle;
1730 }
1731
1732 /**
1733 * Handle deprecated arguments for sql_pconnect() and connectDB()
1734 *
1735 * @param string|null $host Database host[:port]
1736 * @param string|null $username Database user name
1737 * @param string|null $password User password
1738 * @param string|null $db Database
1739 */
1740 protected function handleDeprecatedConnectArguments($host = NULL, $username = NULL, $password = NULL, $db = NULL) {
1741 GeneralUtility::deprecationLog(
1742 'DatabaseConnection->sql_pconnect() and DatabaseConnection->connectDB() should be ' .
1743 'called without arguments. Use the setters instead.'
1744 );
1745 if ($host) {
1746 if (strpos($host, ':') > 0) {
1747 list($databaseHost, $databasePort) = explode(':', $host);
1748 $this->setDatabaseHost($databaseHost);
1749 $this->setDatabasePort($databasePort);
1750 } else {
1751 $this->setDatabaseHost($host);
1752 }
1753 }
1754 if ($username) {
1755 $this->setDatabaseUsername($username);
1756 }
1757 if ($password) {
1758 $this->setDatabasePassword($password);
1759 }
1760 if ($db) {
1761 $this->setDatabaseName($db);
1762 }
1763 }
1764
1765 /******************************
1766 *
1767 * Debugging
1768 *
1769 ******************************/
1770 /**
1771 * Debug function: Outputs error if any
1772 *
1773 * @param string $func Function calling debug()
1774 * @param string $query Last query if not last built query
1775 * @return void
1776 * @todo Define visibility
1777 */
1778 public function debug($func, $query = '') {
1779 $error = $this->sql_error();
1780 if ($error || (int)$this->debugOutput === 2) {
1781 \TYPO3\CMS\Core\Utility\DebugUtility::debug(
1782 array(
1783 'caller' => 'TYPO3\\CMS\\Core\\Database\\DatabaseConnection::' . $func,
1784 'ERROR' => $error,
1785 'lastBuiltQuery' => $query ? $query : $this->debug_lastBuiltQuery,
1786 'debug_backtrace' => \TYPO3\CMS\Core\Utility\DebugUtility::debugTrail()
1787 ),
1788 $func,
1789 is_object($GLOBALS['error']) && @is_callable(array($GLOBALS['error'], 'debug'))
1790 ? ''
1791 : 'DB Error'
1792 );
1793 }
1794 }
1795
1796 /**
1797 * Checks if record set is valid and writes debugging information into devLog if not.
1798 *
1799 * @param boolean|\mysqli_result|object MySQLi result object / DBAL object
1800 * @return boolean TRUE if the record set is valid, FALSE otherwise
1801 * @todo Define visibility
1802 */
1803 public function debug_check_recordset($res) {
1804 if ($res !== FALSE) {
1805 return TRUE;
1806 }
1807 $msg = 'Invalid database result detected';
1808 $trace = debug_backtrace();
1809 array_shift($trace);
1810 $cnt = count($trace);
1811 for ($i = 0; $i < $cnt; $i++) {
1812 // Complete objects are too large for the log
1813 if (isset($trace['object'])) {
1814 unset($trace['object']);
1815 }
1816 }
1817 $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'];
1818 GeneralUtility::sysLog(
1819 $msg . '. Use a devLog extension to get more details.',
1820 'Core/t3lib_db',
1821 GeneralUtility::SYSLOG_SEVERITY_ERROR
1822 );
1823 // Send to devLog if enabled
1824 if (TYPO3_DLOG) {
1825 $debugLogData = array(
1826 'SQL Error' => $this->sql_error(),
1827 'Backtrace' => $trace
1828 );
1829 if ($this->debug_lastBuiltQuery) {
1830 $debugLogData = array('SQL Query' => $this->debug_lastBuiltQuery) + $debugLogData;
1831 }
1832 GeneralUtility::devLog($msg . '.', 'Core/t3lib_db', 3, $debugLogData);
1833 }
1834 return FALSE;
1835 }
1836
1837 /**
1838 * Explain select queries
1839 * If $this->explainOutput is set, SELECT queries will be explained here. Only queries with more than one possible result row will be displayed.
1840 * The output is either printed as raw HTML output or embedded into the TS admin panel (checkbox must be enabled!)
1841 *
1842 * TODO: Feature is not DBAL-compliant
1843 *
1844 * @param string $query SQL query
1845 * @param string $from_table Table(s) from which to select. This is what comes right after "FROM ...". Required value.
1846 * @param integer $row_count Number of resulting rows
1847 * @return boolean TRUE if explain was run, FALSE otherwise
1848 */
1849 protected function explain($query, $from_table, $row_count) {
1850 $debugAllowedForIp = GeneralUtility::cmpIP(
1851 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1852 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1853 );
1854 if (
1855 (int)$this->explainOutput == 1
1856 || ((int)$this->explainOutput == 2 && $debugAllowedForIp)
1857 ) {
1858 // Raw HTML output
1859 $explainMode = 1;
1860 } elseif ((int)$this->explainOutput == 3 && is_object($GLOBALS['TT'])) {
1861 // Embed the output into the TS admin panel
1862 $explainMode = 2;
1863 } else {
1864 return FALSE;
1865 }
1866 $error = $this->sql_error();
1867 $trail = \TYPO3\CMS\Core\Utility\DebugUtility::debugTrail();
1868 $explain_tables = array();
1869 $explain_output = array();
1870 $res = $this->sql_query('EXPLAIN ' . $query, $this->link);
1871 if (is_a($res, '\\mysqli_result')) {
1872 while ($tempRow = $this->sql_fetch_assoc($res)) {
1873 $explain_output[] = $tempRow;
1874 $explain_tables[] = $tempRow['table'];
1875 }
1876 $this->sql_free_result($res);
1877 }
1878 $indices_output = array();
1879 // Notice: Rows are skipped if there is only one result, or if no conditions are set
1880 if (
1881 $explain_output[0]['rows'] > 1
1882 || GeneralUtility::inList('ALL', $explain_output[0]['type'])
1883 ) {
1884 // Only enable output if it's really useful
1885 $debug = TRUE;
1886 foreach ($explain_tables as $table) {
1887 $tableRes = $this->sql_query('SHOW TABLE STATUS LIKE \'' . $table . '\'');
1888 $isTable = $this->sql_num_rows($tableRes);
1889 if ($isTable) {
1890 $res = $this->sql_query('SHOW INDEX FROM ' . $table, $this->link);
1891 if (is_a($res, '\\mysqli_result')) {
1892 while ($tempRow = $this->sql_fetch_assoc($res)) {
1893 $indices_output[] = $tempRow;
1894 }
1895 $this->sql_free_result($res);
1896 }
1897 }
1898 $this->sql_free_result($tableRes);
1899 }
1900 } else {
1901 $debug = FALSE;
1902 }
1903 if ($debug) {
1904 if ($explainMode) {
1905 $data = array();
1906 $data['query'] = $query;
1907 $data['trail'] = $trail;
1908 $data['row_count'] = $row_count;
1909 if ($error) {
1910 $data['error'] = $error;
1911 }
1912 if (count($explain_output)) {
1913 $data['explain'] = $explain_output;
1914 }
1915 if (count($indices_output)) {
1916 $data['indices'] = $indices_output;
1917 }
1918 if ($explainMode == 1) {
1919 \TYPO3\CMS\Core\Utility\DebugUtility::debug($data, 'Tables: ' . $from_table, 'DB SQL EXPLAIN');
1920 } elseif ($explainMode == 2) {
1921 $GLOBALS['TT']->setTSselectQuery($data);
1922 }
1923 }
1924 return TRUE;
1925 }
1926 return FALSE;
1927 }
1928
1929 /**
1930 * Serialize destructs current connection
1931 *
1932 * @return array All protected properties that should be saved
1933 */
1934 public function __sleep() {
1935 $this->disconnectIfConnected();
1936 return array(
1937 'debugOutput',
1938 'explainOutput',
1939 'databaseHost',
1940 'databasePort',
1941 'databaseSocket',
1942 'databaseName',
1943 'databaseUsername',
1944 'databaseUserPassword',
1945 'persistentDatabaseConnection',
1946 'connectionCompression',
1947 'initializeCommandsAfterConnect',
1948 'default_charset',
1949 );
1950 }
1951 }