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