[SECURITY] Extbase must not cache dynamic parts of queries
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Generic / Storage / Typo3DbBackend.php
1 <?php
2 namespace TYPO3\CMS\Extbase\Persistence\Generic\Storage;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2010-2013 Extbase Team (http://forge.typo3.org/projects/typo3v4-mvc)
8 * Extbase is a backport of TYPO3 Flow. All credits go to the TYPO3 Flow team.
9 * All rights reserved
10 *
11 * This script is part of the TYPO3 project. The TYPO3 project is
12 * free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
19 * A copy is found in the text file GPL.txt and important notices to the license
20 * from the author is found in LICENSE.txt distributed with these scripts.
21 *
22 *
23 * This script is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * This copyright notice MUST APPEAR in all copies of the script!
29 ***************************************************************/
30
31 use TYPO3\CMS\Backend\Utility\BackendUtility;
32 use TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement;
33 use TYPO3\CMS\Extbase\Persistence\QueryInterface;
34
35 /**
36 * A Storage backend
37 */
38 class Typo3DbBackend implements BackendInterface, \TYPO3\CMS\Core\SingletonInterface {
39
40 /**
41 * The TYPO3 database object
42 *
43 * @var \TYPO3\CMS\Core\Database\DatabaseConnection
44 */
45 protected $databaseHandle;
46
47 /**
48 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
49 * @inject
50 */
51 protected $dataMapper;
52
53 /**
54 * The TYPO3 page repository. Used for language and workspace overlay
55 *
56 * @var \TYPO3\CMS\Frontend\Page\PageRepository
57 */
58 protected $pageRepository;
59
60 /**
61 * A first-level TypoScript configuration cache
62 *
63 * @var array
64 */
65 protected $pageTSConfigCache = array();
66
67 /**
68 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
69 * @inject
70 */
71 protected $configurationManager;
72
73 /**
74 * @var \TYPO3\CMS\Extbase\Service\CacheService
75 * @inject
76 */
77 protected $cacheService;
78
79 /**
80 * @var \TYPO3\CMS\Core\Cache\CacheManager
81 * @inject
82 */
83 protected $cacheManager;
84
85 /**
86 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
87 */
88 protected $tableColumnCache;
89
90 /**
91 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
92 */
93 protected $queryCache;
94
95 /**
96 * @var \TYPO3\CMS\Extbase\Service\EnvironmentService
97 * @inject
98 */
99 protected $environmentService;
100
101 /**
102 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Typo3DbQueryParser
103 * @inject
104 */
105 protected $queryParser;
106
107 /**
108 * A first level cache for queries during runtime
109 *
110 * @var array
111 */
112 protected $queryRuntimeCache = array();
113
114 /**
115 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
116 */
117 public function __construct() {
118 $this->databaseHandle = $GLOBALS['TYPO3_DB'];
119 }
120
121 /**
122 * Lifecycle method
123 *
124 * @return void
125 */
126 public function initializeObject() {
127 $this->tableColumnCache = $this->cacheManager->getCache('extbase_typo3dbbackend_tablecolumns');
128 $this->queryCache = $this->cacheManager->getCache('extbase_typo3dbbackend_queries');
129 }
130
131 /**
132 * Adds a row to the storage
133 *
134 * @param string $tableName The database table name
135 * @param array $fieldValues The row to be inserted
136 * @param bool $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
137 * @return integer The uid of the inserted row
138 */
139 public function addRow($tableName, array $fieldValues, $isRelation = FALSE) {
140 if (isset($fieldValues['uid'])) {
141 unset($fieldValues['uid']);
142 }
143
144 $this->databaseHandle->exec_INSERTquery($tableName, $fieldValues);
145 $this->checkSqlErrors();
146 $uid = $this->databaseHandle->sql_insert_id();
147
148 if (!$isRelation) {
149 $this->clearPageCache($tableName, $uid);
150 }
151 return (int)$uid;
152 }
153
154 /**
155 * Updates a row in the storage
156 *
157 * @param string $tableName The database table name
158 * @param array $fieldValues The row to be updated
159 * @param bool $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
160 * @throws \InvalidArgumentException
161 * @return bool
162 */
163 public function updateRow($tableName, array $fieldValues, $isRelation = FALSE) {
164 if (!isset($fieldValues['uid'])) {
165 throw new \InvalidArgumentException('The given row must contain a value for "uid".');
166 }
167
168 $uid = (int)$fieldValues['uid'];
169 unset($fieldValues['uid']);
170
171 $updateSuccessful = $this->databaseHandle->exec_UPDATEquery($tableName, 'uid = '. $uid, $fieldValues);
172 $this->checkSqlErrors();
173
174 if (!$isRelation) {
175 $this->clearPageCache($tableName, $uid);
176 }
177
178 return $updateSuccessful;
179 }
180
181 /**
182 * Updates a relation row in the storage.
183 *
184 * @param string $tableName The database relation table name
185 * @param array $fieldValues The row to be updated
186 * @throws \InvalidArgumentException
187 * @return bool
188 */
189 public function updateRelationTableRow($tableName, array $fieldValues) {
190 if (!isset($fieldValues['uid_local']) && !isset($fieldValues['uid_foreign'])) {
191 throw new \InvalidArgumentException(
192 'The given fieldValues must contain a value for "uid_local" and "uid_foreign".', 1360500126
193 );
194 }
195
196 $where['uid_local'] = (int)$fieldValues['uid_local'];
197 $where['uid_foreign'] = (int)$fieldValues['uid_foreign'];
198 unset($fieldValues['uid_local']);
199 unset($fieldValues['uid_foreign']);
200
201 $updateSuccessful = $this->databaseHandle->exec_UPDATEquery(
202 $tableName,
203 $this->resolveWhereStatement($where, $tableName),
204 $fieldValues
205 );
206 $this->checkSqlErrors();
207
208 return $updateSuccessful;
209 }
210
211 /**
212 * Deletes a row in the storage
213 *
214 * @param string $tableName The database table name
215 * @param array $where An array of where array('fieldname' => value).
216 * @param bool $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
217 * @return bool
218 */
219 public function removeRow($tableName, array $where, $isRelation = FALSE) {
220 $deleteSuccessful = $this->databaseHandle->exec_DELETEquery(
221 $tableName,
222 $this->resolveWhereStatement($where, $tableName)
223 );
224 $this->checkSqlErrors();
225
226 if (!$isRelation && isset($where['uid'])) {
227 $this->clearPageCache($tableName, $where['uid']);
228 }
229
230 return $deleteSuccessful;
231 }
232
233 /**
234 * Fetches maximal value for given table column from database.
235 *
236 * @param string $tableName The database table name
237 * @param array $where An array of where array('fieldname' => value).
238 * @param string $columnName column name to get the max value from
239 * @return mixed the max value
240 */
241 public function getMaxValueFromTable($tableName, array $where, $columnName) {
242 $result = $this->databaseHandle->exec_SELECTgetSingleRow(
243 $columnName,
244 $tableName,
245 $this->resolveWhereStatement($where, $tableName),
246 '',
247 $columnName . ' DESC',
248 TRUE
249 );
250 $this->checkSqlErrors();
251
252 return $result[0];
253 }
254
255 /**
256 * Fetches row data from the database
257 *
258 * @param string $tableName
259 * @param array $where An array of where array('fieldname' => value).
260 * @return array|bool
261 */
262 public function getRowByIdentifier($tableName, array $where) {
263 $row = $this->databaseHandle->exec_SELECTgetSingleRow(
264 '*',
265 $tableName,
266 $this->resolveWhereStatement($where, $tableName)
267 );
268 $this->checkSqlErrors();
269
270 return $row ?: FALSE;
271 }
272
273 /**
274 * Converts an array to an AND concatenated where statement
275 *
276 * @param array $where array('fieldName' => 'fieldValue')
277 * @param string $tableName table to use for escaping config
278 *
279 * @return string
280 */
281 protected function resolveWhereStatement(array $where, $tableName = 'foo') {
282 $whereStatement = array();
283
284 foreach ($where as $fieldName => $fieldValue) {
285 $whereStatement[] = $fieldName . ' = ' . $this->databaseHandle->fullQuoteStr($fieldValue, $tableName);
286 }
287
288 return implode(' AND ', $whereStatement);
289 }
290
291 /**
292 * Returns the object data matching the $query.
293 *
294 * @param QueryInterface $query
295 * @return array
296 */
297 public function getObjectDataByQuery(QueryInterface $query) {
298 $statement = $query->getStatement();
299 if ($statement instanceof Statement) {
300 $rows = $this->getObjectDataByRawQuery($statement);
301 } else {
302 $rows = $this->getRowsByStatementParts($query);
303 }
304
305 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows, $query->getQuerySettings());
306 return $rows;
307 }
308
309 /**
310 * Creates the parameters for the query methods of the database methods in the TYPO3 core, from an array
311 * that came from a parsed query.
312 *
313 * @param array $statementParts
314 * @return array
315 */
316 protected function createQueryCommandParametersFromStatementParts(array $statementParts) {
317 return array(
318 'selectFields' => implode(' ', $statementParts['keywords']) . ' ' . implode(',', $statementParts['fields']),
319 'fromTable' => implode(' ', $statementParts['tables']) . ' ' . implode(' ', $statementParts['unions']),
320 'whereClause' => (!empty($statementParts['where']) ? implode('', $statementParts['where']) : '1')
321 . (!empty($statementParts['additionalWhereClause'])
322 ? ' AND ' . implode(' AND ', $statementParts['additionalWhereClause'])
323 : ''
324 ),
325 'orderBy' => (!empty($statementParts['orderings']) ? implode(', ', $statementParts['orderings']) : ''),
326 'limit' => ($statementParts['offset'] ? $statementParts['offset'] . ', ' : '')
327 . ($statementParts['limit'] ? $statementParts['limit'] : '')
328 );
329 }
330
331 /**
332 * Determines whether to use prepared statement or not and returns the rows from the corresponding method
333 *
334 * @param QueryInterface $query
335 * @return array
336 */
337 protected function getRowsByStatementParts(QueryInterface $query) {
338 if ($query->getQuerySettings()->getUsePreparedStatement()) {
339 list($statementParts, $parameters) = $this->getStatementParts($query, FALSE);
340 $rows = $this->getRowsFromPreparedDatabase($statementParts, $parameters);
341 } else {
342 list($statementParts) = $this->getStatementParts($query);
343 $rows = $this->getRowsFromDatabase($statementParts);
344 }
345
346 return $rows;
347 }
348
349 /**
350 * Fetches the rows directly from the database, not using prepared statement
351 *
352 * @param array $statementParts
353 * @return array the result
354 */
355 protected function getRowsFromDatabase(array $statementParts) {
356 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
357 $rows = $this->databaseHandle->exec_SELECTgetRows(
358 $queryCommandParameters['selectFields'],
359 $queryCommandParameters['fromTable'],
360 $queryCommandParameters['whereClause'],
361 '',
362 $queryCommandParameters['orderBy'],
363 $queryCommandParameters['limit']
364 );
365 $this->checkSqlErrors();
366
367 return $rows;
368 }
369
370 /**
371 * Fetches the rows from the database, using prepared statement
372 *
373 * @param array $statementParts
374 * @param array $parameters
375 * @return array the result
376 */
377 protected function getRowsFromPreparedDatabase(array $statementParts, array $parameters) {
378 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
379 $preparedStatement = $this->databaseHandle->prepare_SELECTquery(
380 $queryCommandParameters['selectFields'],
381 $queryCommandParameters['fromTable'],
382 $queryCommandParameters['whereClause'],
383 '',
384 $queryCommandParameters['orderBy'],
385 $queryCommandParameters['limit']
386 );
387
388 $preparedStatement->execute($parameters);
389 $rows = $preparedStatement->fetchAll();
390
391 $preparedStatement->free();
392 return $rows;
393 }
394
395 /**
396 * Returns the object data using a custom statement
397 *
398 * @param Statement $statement
399 * @return array
400 */
401 protected function getObjectDataByRawQuery(Statement $statement) {
402 $realStatement = $statement->getStatement();
403 $parameters = $statement->getBoundVariables();
404
405 if ($realStatement instanceof \TYPO3\CMS\Core\Database\PreparedStatement) {
406 $realStatement->execute($parameters);
407 $rows = $realStatement->fetchAll();
408
409 $realStatement->free();
410 } else {
411 /**
412 * @deprecated since 6.2, this block will be removed in two versions
413 * the deprecation log is in Qom\Statement
414 */
415 if (!empty($parameters)) {
416 $this->replacePlaceholders($realStatement, $parameters);
417 }
418
419 $result = $this->databaseHandle->sql_query($realStatement);
420 $this->checkSqlErrors();
421
422 $rows = array();
423 while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
424 if (is_array($row)) {
425 $rows[] = $row;
426 }
427 }
428 $this->databaseHandle->sql_free_result($result);
429 }
430
431 return $rows;
432 }
433
434 /**
435 * Returns the number of tuples matching the query.
436 *
437 * @param QueryInterface $query
438 * @throws Exception\BadConstraintException
439 * @return integer The number of matching tuples
440 */
441 public function getObjectCountByQuery(QueryInterface $query) {
442 if ($query->getConstraint() instanceof Statement) {
443 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\BadConstraintException('Could not execute count on queries with a constraint of type TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Qom\\Statement', 1256661045);
444 }
445
446 list($statementParts) = $this->getStatementParts($query);
447
448 $fields = '*';
449 if (isset($statementParts['keywords']['distinct'])) {
450 $fields = 'DISTINCT ' . reset($statementParts['tables']) . '.uid';
451 }
452
453 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
454 $count = $this->databaseHandle->exec_SELECTcountRows(
455 $fields,
456 $queryCommandParameters['fromTable'],
457 $queryCommandParameters['whereClause']
458 );
459 $this->checkSqlErrors();
460
461 if ($statementParts['offset']) {
462 $count -= $statementParts['offset'];
463 }
464
465 if ($statementParts['limit']) {
466 $count = min($count, $statementParts['limit']);
467 }
468
469 return (int)max(0, $count);
470 }
471
472 /**
473 * Looks for the query in cache or builds it up otherwise
474 *
475 * @param QueryInterface $query
476 * @param bool $resolveParameterPlaceholders whether to resolve the parameters or leave the placeholders
477 * @return array
478 * @throws \RuntimeException
479 */
480 protected function getStatementParts($query, $resolveParameterPlaceholders = TRUE) {
481 /**
482 * The queryParser will preparse the query to get the query's hash and parameters.
483 * If the hash is found in the cache and useQueryCaching is enabled, extbase will
484 * then take the string representation from cache and build a prepared query with
485 * the parameters found.
486 *
487 * Otherwise extbase will parse the complete query, build the string representation
488 * and run a usual query.
489 */
490 list($queryHash, $parameters) = $this->queryParser->preparseQuery($query);
491
492 if ($query->getQuerySettings()->getUseQueryCache()) {
493 $statementParts = $this->getQueryCacheEntry($queryHash);
494 if ($queryHash && !$statementParts) {
495 $statementParts = $this->queryParser->parseQuery($query);
496 $this->setQueryCacheEntry($queryHash, $statementParts);
497 }
498 } else {
499 $statementParts = $this->queryParser->parseQuery($query);
500 }
501
502 if (!$statementParts) {
503 throw new \RuntimeException('Your query could not be built.', 1394453197);
504 }
505
506 $this->queryParser->addDynamicQueryParts($query->getQuerySettings(), $statementParts);
507
508 // Limit and offset are not cached to allow caching of pagebrowser queries.
509 $statementParts['limit'] = ((int)$query->getLimit() ?: NULL);
510 $statementParts['offset'] = ((int)$query->getOffset() ?: NULL);
511
512 if ($resolveParameterPlaceholders === TRUE) {
513 $statementParts = $this->resolveParameterPlaceholders($statementParts, $parameters);
514 }
515
516 return array($statementParts, $parameters);
517 }
518
519 /**
520 * Replaces the parameters in the queryStructure with given values
521 *
522 * @param array $statementParts
523 * @param array $parameters
524 * @return array
525 */
526 protected function resolveParameterPlaceholders(array $statementParts, array $parameters) {
527 $tableNameForEscape = (reset($statementParts['tables']) ?: 'foo');
528
529 foreach ($parameters as $parameterPlaceholder => $parameter) {
530 if ($parameter instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
531 $parameter = $parameter->_loadRealInstance();
532 }
533
534 if ($parameter instanceof \DateTime) {
535 $parameter = $parameter->format('U');
536 } elseif ($parameter instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
537 $parameter = (int)$parameter->getUid();
538 } elseif (is_array($parameter)) {
539 $subParameters = array();
540 foreach ($parameter as $subParameter) {
541 $subParameters[] = $this->databaseHandle->fullQuoteStr($subParameter, $tableNameForEscape);
542 }
543 $parameter = implode(',', $subParameters);
544 } elseif ($parameter === NULL) {
545 $parameter = 'NULL';
546 } elseif (is_bool($parameter)) {
547 $parameter = (int)$parameter;
548 } else {
549 $parameter = $this->databaseHandle->fullQuoteStr((string)$parameter, $tableNameForEscape);
550 }
551
552 $statementParts['where'] = str_replace($parameterPlaceholder, $parameter, $statementParts['where']);
553 }
554
555 return $statementParts;
556 }
557
558 /**
559 * Checks if a Value Object equal to the given Object exists in the data base
560 *
561 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object The Value Object
562 * @return mixed The matching uid if an object was found, else FALSE
563 * @todo this is the last monster in this persistence series. refactor!
564 */
565 public function getUidOfAlreadyPersistedValueObject(\TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object) {
566 $fields = array();
567 $parameters = array();
568 $dataMap = $this->dataMapper->getDataMap(get_class($object));
569 $properties = $object->_getProperties();
570 foreach ($properties as $propertyName => $propertyValue) {
571 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
572 if ($dataMap->isPersistableProperty($propertyName) && $propertyName !== 'uid' && $propertyName !== 'pid' && $propertyName !== 'isClone') {
573 if ($propertyValue === NULL) {
574 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
575 } else {
576 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
577 $parameters[] = $this->getPlainValue($propertyValue);
578 }
579 }
580 }
581 $sql = array();
582 $sql['additionalWhereClause'] = array();
583 $tableName = $dataMap->getTableName();
584 $this->addVisibilityConstraintStatement(new \TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings(), $tableName, $sql);
585 $statement = 'SELECT * FROM ' . $tableName;
586 $statement .= ' WHERE ' . implode(' AND ', $fields);
587 if (!empty($sql['additionalWhereClause'])) {
588 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
589 }
590 $this->replacePlaceholders($statement, $parameters, $tableName);
591 // debug($statement,-2);
592 $res = $this->databaseHandle->sql_query($statement);
593 $this->checkSqlErrors($statement);
594 $row = $this->databaseHandle->sql_fetch_assoc($res);
595 if ($row !== FALSE) {
596 return (int)$row['uid'];
597 } else {
598 return FALSE;
599 }
600 }
601
602 /**
603 * Returns a plain value, i.e. objects are flattened out if possible.
604 *
605 * @param mixed $input
606 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException
607 * @return mixed
608 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
609 */
610 protected function getPlainValue($input) {
611 if (is_array($input)) {
612 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
613 }
614 if ($input instanceof \DateTime) {
615 return $input->format('U');
616 } elseif ($input instanceof \TYPO3\CMS\Core\Type\TypeInterface) {
617 return (string) $input;
618 } elseif (is_object($input)) {
619 if ($input instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
620 $realInput = $input->_loadRealInstance();
621 } else {
622 $realInput = $input;
623 }
624 if ($realInput instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
625 return $realInput->getUid();
626 } else {
627 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An object of class "' . get_class($realInput) . '" could not be converted to a plain value.', 1274799934);
628 }
629 } elseif (is_bool($input)) {
630 return (int)$input;
631 } else {
632 return $input;
633 }
634 }
635
636 /**
637 * Replace query placeholders in a query part by the given
638 * parameters.
639 *
640 * @param string &$sqlString The query part with placeholders
641 * @param array $parameters The parameters
642 * @param string $tableName
643 *
644 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
645 * @deprecated since 6.2, will be removed two versions later
646 * @todo add deprecation notice after getUidOfAlreadyPersistedValueObject is adjusted
647 */
648 protected function replacePlaceholders(&$sqlString, array $parameters, $tableName = 'foo') {
649 // TODO profile this method again
650 if (substr_count($sqlString, '?') !== count($parameters)) {
651 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
652 }
653 $offset = 0;
654 foreach ($parameters as $parameter) {
655 $markPosition = strpos($sqlString, '?', $offset);
656 if ($markPosition !== FALSE) {
657 if ($parameter === NULL) {
658 $parameter = 'NULL';
659 } elseif (is_array($parameter) || $parameter instanceof \ArrayAccess || $parameter instanceof \Traversable) {
660 $items = array();
661 foreach ($parameter as $item) {
662 $items[] = $this->databaseHandle->fullQuoteStr($item, $tableName);
663 }
664 $parameter = '(' . implode(',', $items) . ')';
665 } else {
666 $parameter = $this->databaseHandle->fullQuoteStr($parameter, $tableName);
667 }
668 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, ($markPosition + 1));
669 }
670 $offset = $markPosition + strlen($parameter);
671 }
672 }
673
674 /**
675 * Adds enableFields and deletedClause to the query if necessary
676 *
677 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings
678 * @param string $tableName The database table name
679 * @param array &$sql The query parts
680 * @return void
681 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
682 */
683 protected function addVisibilityConstraintStatement(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, array &$sql) {
684 $statement = '';
685 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
686 $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
687 $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
688 $includeDeleted = $querySettings->getIncludeDeleted();
689 if ($this->environmentService->isEnvironmentInFrontendMode()) {
690 $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
691 } else {
692 // TYPO3_MODE === 'BE'
693 $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
694 }
695 if (!empty($statement)) {
696 $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
697 $sql['additionalWhereClause'][] = $statement;
698 }
699 }
700 }
701
702 /**
703 * Returns constraint statement for frontend context
704 *
705 * @param string $tableName
706 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
707 * @param array $enableFieldsToBeIgnored If $ignoreEnableFields is true, this array specifies enable fields to be ignored. If it is NULL or an empty array (default) all enable fields are ignored.
708 * @param bool $includeDeleted A flag indicating whether deleted records should be included
709 * @return string
710 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException
711 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
712 */
713 protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, array $enableFieldsToBeIgnored = array(), $includeDeleted) {
714 $statement = '';
715 if ($ignoreEnableFields && !$includeDeleted) {
716 if (count($enableFieldsToBeIgnored)) {
717 // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
718 $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
719 } else {
720 $statement .= $this->getPageRepository()->deleteClause($tableName);
721 }
722 } elseif (!$ignoreEnableFields && !$includeDeleted) {
723 $statement .= $this->getPageRepository()->enableFields($tableName);
724 } elseif (!$ignoreEnableFields && $includeDeleted) {
725 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException('Query setting "ignoreEnableFields=FALSE" can not be used together with "includeDeleted=TRUE" in frontend context.', 1327678173);
726 }
727 return $statement;
728 }
729
730 /**
731 * Returns constraint statement for backend context
732 *
733 * @param string $tableName
734 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
735 * @param bool $includeDeleted A flag indicating whether deleted records should be included
736 * @return string
737 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
738 */
739 protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted) {
740 $statement = '';
741 if (!$ignoreEnableFields) {
742 $statement .= BackendUtility::BEenableFields($tableName);
743 }
744 if (!$includeDeleted) {
745 $statement .= BackendUtility::deleteClause($tableName);
746 }
747 return $statement;
748 }
749
750 /**
751 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
752 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
753 *
754 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source (selector od join)
755 * @param array $rows
756 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
757 * @param null|integer $workspaceUid
758 * @return array
759 */
760 protected function doLanguageAndWorkspaceOverlay(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array $rows, \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $workspaceUid = NULL) {
761 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
762 $tableName = $source->getSelectorName();
763 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
764 $tableName = $source->getRight()->getSelectorName();
765 } else {
766 // No proper source, so we do not have a table name here
767 // we cannot do an overlay and return the original rows instead.
768 return $rows;
769 }
770
771 $pageRepository = $this->getPageRepository();
772 if (is_object($GLOBALS['TSFE'])) {
773 if ($workspaceUid !== NULL) {
774 $pageRepository->versioningWorkspaceId = $workspaceUid;
775 }
776 } else {
777 if ($workspaceUid === NULL) {
778 $workspaceUid = $GLOBALS['BE_USER']->workspace;
779 }
780 $pageRepository->versioningWorkspaceId = $workspaceUid;
781 }
782
783 $overlaidRows = array();
784 foreach ($rows as $row) {
785 // If current row is a translation select its parent
786 if (isset($tableName) && isset($GLOBALS['TCA'][$tableName])
787 && isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
788 && isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
789 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
790 ) {
791 if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
792 && $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
793 ) {
794 $row = $this->databaseHandle->exec_SELECTgetSingleRow(
795 $tableName . '.*',
796 $tableName,
797 $tableName . '.uid=' . (int)$row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
798 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
799 );
800 }
801 }
802 $pageRepository->versionOL($tableName, $row, TRUE);
803 if ($pageRepository->versioningPreview && isset($row['_ORIG_uid'])) {
804 $row['uid'] = $row['_ORIG_uid'];
805 }
806 if ($tableName == 'pages') {
807 $row = $pageRepository->getPageOverlay($row, $querySettings->getLanguageUid());
808 } elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
809 && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
810 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
811 ) {
812 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1, 0))) {
813 $overlayMode = $querySettings->getLanguageMode() === 'strict' ? 'hideNonTranslated' : '';
814 $row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getLanguageUid(), $overlayMode);
815 }
816 }
817 if ($row !== NULL && is_array($row)) {
818 $overlaidRows[] = $row;
819 }
820 }
821 return $overlaidRows;
822 }
823
824 /**
825 * @return \TYPO3\CMS\Frontend\Page\PageRepository
826 */
827 protected function getPageRepository() {
828 if (!$this->pageRepository instanceof \TYPO3\CMS\Frontend\Page\PageRepository) {
829 if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
830 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
831 } else {
832 $this->pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
833 }
834 }
835
836 return $this->pageRepository;
837 }
838
839 /**
840 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
841 *
842 * @return void
843 * @param string $sql The SQL statement
844 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException
845 */
846 protected function checkSqlErrors($sql = '') {
847 $error = $this->databaseHandle->sql_error();
848 if ($error !== '') {
849 $error .= $sql ? ': ' . $sql : '';
850 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException($error, 1247602160);
851 }
852 }
853
854 /**
855 * Clear the TYPO3 page cache for the given record.
856 * If the record lies on a page, then we clear the cache of this page.
857 * If the record has no PID column, we clear the cache of the current page as best-effort.
858 *
859 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
860 *
861 * @param string $tableName Table name of the record
862 * @param integer $uid UID of the record
863 * @return void
864 */
865 protected function clearPageCache($tableName, $uid) {
866 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
867 if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
868 } else {
869 // if disabled, return
870 return;
871 }
872 $pageIdsToClear = array();
873 $storagePage = NULL;
874 $columns = $this->databaseHandle->admin_get_fields($tableName);
875 if (array_key_exists('pid', $columns)) {
876 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid=' . (int)$uid);
877 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
878 $storagePage = $row['pid'];
879 $pageIdsToClear[] = $storagePage;
880 }
881 } elseif (isset($GLOBALS['TSFE'])) {
882 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
883 $storagePage = $GLOBALS['TSFE']->id;
884 $pageIdsToClear[] = $storagePage;
885 }
886 if ($storagePage === NULL) {
887 return;
888 }
889 if (!isset($this->pageTSConfigCache[$storagePage])) {
890 $this->pageTSConfigCache[$storagePage] = BackendUtility::getPagesTSconfig($storagePage);
891 }
892 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
893 $clearCacheCommands = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']), TRUE);
894 $clearCacheCommands = array_unique($clearCacheCommands);
895 foreach ($clearCacheCommands as $clearCacheCommand) {
896 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($clearCacheCommand)) {
897 $pageIdsToClear[] = $clearCacheCommand;
898 }
899 }
900 }
901
902 foreach ($pageIdsToClear as $pageIdToClear) {
903 $this->cacheService->getPageIdStack()->push($pageIdToClear);
904 }
905 }
906
907 /**
908 * Finds and returns a variable value from the query cache.
909 *
910 * @param string $entryIdentifier Identifier of the cache entry to fetch
911 * @return mixed The value
912 */
913 protected function getQueryCacheEntry($entryIdentifier) {
914 if (!isset($this->queryRuntimeCache[$entryIdentifier])) {
915 $this->queryRuntimeCache[$entryIdentifier] = $this->queryCache->get($entryIdentifier);
916 }
917 return $this->queryRuntimeCache[$entryIdentifier];
918 }
919
920 /**
921 * Saves the value of a PHP variable in the query cache.
922 *
923 * @param string $entryIdentifier An identifier used for this cache entry
924 * @param mixed $variable The query to cache
925 * @return void
926 */
927 protected function setQueryCacheEntry($entryIdentifier, $variable) {
928 $this->queryRuntimeCache[$entryIdentifier] = $variable;
929 $this->queryCache->set($entryIdentifier, $variable, array(), 0);
930 }
931 }