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