1df4854e62d0ccc4a8fcfb9797778876cde9b067
[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 // Limit and offset are not cached to allow caching of pagebrowser queries.
507 $statementParts['limit'] = ((int)$query->getLimit() ?: NULL);
508 $statementParts['offset'] = ((int)$query->getOffset() ?: NULL);
509
510 if ($resolveParameterPlaceholders === TRUE) {
511 $statementParts = $this->resolveParameterPlaceholders($statementParts, $parameters);
512 }
513
514 return array($statementParts, $parameters);
515 }
516
517 /**
518 * Replaces the parameters in the queryStructure with given values
519 *
520 * @param array $statementParts
521 * @param array $parameters
522 * @return array
523 */
524 protected function resolveParameterPlaceholders(array $statementParts, array $parameters) {
525 $tableNameForEscape = (reset($statementParts['tables']) ?: 'foo');
526
527 foreach ($parameters as $parameterPlaceholder => $parameter) {
528 if ($parameter instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
529 $parameter = $parameter->_loadRealInstance();
530 }
531
532 if ($parameter instanceof \DateTime) {
533 $parameter = $parameter->format('U');
534 } elseif ($parameter instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
535 $parameter = (int)$parameter->getUid();
536 } elseif (is_array($parameter)) {
537 $subParameters = array();
538 foreach ($parameter as $subParameter) {
539 $subParameters[] = $this->databaseHandle->fullQuoteStr($subParameter, $tableNameForEscape);
540 }
541 $parameter = implode(',', $subParameters);
542 } elseif ($parameter === NULL) {
543 $parameter = 'NULL';
544 } elseif (is_bool($parameter)) {
545 $parameter = (int)$parameter;
546 } else {
547 $parameter = $this->databaseHandle->fullQuoteStr((string)$parameter, $tableNameForEscape);
548 }
549
550 $statementParts['where'] = str_replace($parameterPlaceholder, $parameter, $statementParts['where']);
551 }
552
553 return $statementParts;
554 }
555
556 /**
557 * Checks if a Value Object equal to the given Object exists in the data base
558 *
559 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object The Value Object
560 * @return mixed The matching uid if an object was found, else FALSE
561 * @todo this is the last monster in this persistence series. refactor!
562 */
563 public function getUidOfAlreadyPersistedValueObject(\TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object) {
564 $fields = array();
565 $parameters = array();
566 $dataMap = $this->dataMapper->getDataMap(get_class($object));
567 $properties = $object->_getProperties();
568 foreach ($properties as $propertyName => $propertyValue) {
569 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
570 if ($dataMap->isPersistableProperty($propertyName) && $propertyName !== 'uid' && $propertyName !== 'pid' && $propertyName !== 'isClone') {
571 if ($propertyValue === NULL) {
572 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
573 } else {
574 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
575 $parameters[] = $this->getPlainValue($propertyValue);
576 }
577 }
578 }
579 $sql = array();
580 $sql['additionalWhereClause'] = array();
581 $tableName = $dataMap->getTableName();
582 $this->addVisibilityConstraintStatement(new \TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings(), $tableName, $sql);
583 $statement = 'SELECT * FROM ' . $tableName;
584 $statement .= ' WHERE ' . implode(' AND ', $fields);
585 if (!empty($sql['additionalWhereClause'])) {
586 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
587 }
588 $this->replacePlaceholders($statement, $parameters, $tableName);
589 // debug($statement,-2);
590 $res = $this->databaseHandle->sql_query($statement);
591 $this->checkSqlErrors($statement);
592 $row = $this->databaseHandle->sql_fetch_assoc($res);
593 if ($row !== FALSE) {
594 return (int)$row['uid'];
595 } else {
596 return FALSE;
597 }
598 }
599
600 /**
601 * Returns a plain value, i.e. objects are flattened out if possible.
602 *
603 * @param mixed $input
604 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException
605 * @return mixed
606 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
607 */
608 protected function getPlainValue($input) {
609 if (is_array($input)) {
610 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
611 }
612 if ($input instanceof \DateTime) {
613 return $input->format('U');
614 } elseif ($input instanceof \TYPO3\CMS\Core\Type\TypeInterface) {
615 return (string) $input;
616 } elseif (is_object($input)) {
617 if ($input instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
618 $realInput = $input->_loadRealInstance();
619 } else {
620 $realInput = $input;
621 }
622 if ($realInput instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
623 return $realInput->getUid();
624 } else {
625 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);
626 }
627 } elseif (is_bool($input)) {
628 return (int)$input;
629 } else {
630 return $input;
631 }
632 }
633
634 /**
635 * Replace query placeholders in a query part by the given
636 * parameters.
637 *
638 * @param string &$sqlString The query part with placeholders
639 * @param array $parameters The parameters
640 * @param string $tableName
641 *
642 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
643 * @deprecated since 6.2, will be removed two versions later
644 * @todo add deprecation notice after getUidOfAlreadyPersistedValueObject is adjusted
645 */
646 protected function replacePlaceholders(&$sqlString, array $parameters, $tableName = 'foo') {
647 // TODO profile this method again
648 if (substr_count($sqlString, '?') !== count($parameters)) {
649 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
650 }
651 $offset = 0;
652 foreach ($parameters as $parameter) {
653 $markPosition = strpos($sqlString, '?', $offset);
654 if ($markPosition !== FALSE) {
655 if ($parameter === NULL) {
656 $parameter = 'NULL';
657 } elseif (is_array($parameter) || $parameter instanceof \ArrayAccess || $parameter instanceof \Traversable) {
658 $items = array();
659 foreach ($parameter as $item) {
660 $items[] = $this->databaseHandle->fullQuoteStr($item, $tableName);
661 }
662 $parameter = '(' . implode(',', $items) . ')';
663 } else {
664 $parameter = $this->databaseHandle->fullQuoteStr($parameter, $tableName);
665 }
666 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, ($markPosition + 1));
667 }
668 $offset = $markPosition + strlen($parameter);
669 }
670 }
671
672 /**
673 * Adds enableFields and deletedClause to the query if necessary
674 *
675 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings
676 * @param string $tableName The database table name
677 * @param array &$sql The query parts
678 * @return void
679 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
680 */
681 protected function addVisibilityConstraintStatement(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, array &$sql) {
682 $statement = '';
683 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
684 $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
685 $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
686 $includeDeleted = $querySettings->getIncludeDeleted();
687 if ($this->environmentService->isEnvironmentInFrontendMode()) {
688 $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
689 } else {
690 // TYPO3_MODE === 'BE'
691 $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
692 }
693 if (!empty($statement)) {
694 $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
695 $sql['additionalWhereClause'][] = $statement;
696 }
697 }
698 }
699
700 /**
701 * Returns constraint statement for frontend context
702 *
703 * @param string $tableName
704 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
705 * @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.
706 * @param bool $includeDeleted A flag indicating whether deleted records should be included
707 * @return string
708 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException
709 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
710 */
711 protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, array $enableFieldsToBeIgnored = array(), $includeDeleted) {
712 $statement = '';
713 if ($ignoreEnableFields && !$includeDeleted) {
714 if (count($enableFieldsToBeIgnored)) {
715 // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
716 $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
717 } else {
718 $statement .= $this->getPageRepository()->deleteClause($tableName);
719 }
720 } elseif (!$ignoreEnableFields && !$includeDeleted) {
721 $statement .= $this->getPageRepository()->enableFields($tableName);
722 } elseif (!$ignoreEnableFields && $includeDeleted) {
723 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);
724 }
725 return $statement;
726 }
727
728 /**
729 * Returns constraint statement for backend context
730 *
731 * @param string $tableName
732 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
733 * @param bool $includeDeleted A flag indicating whether deleted records should be included
734 * @return string
735 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
736 */
737 protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted) {
738 $statement = '';
739 if (!$ignoreEnableFields) {
740 $statement .= BackendUtility::BEenableFields($tableName);
741 }
742 if (!$includeDeleted) {
743 $statement .= BackendUtility::deleteClause($tableName);
744 }
745 return $statement;
746 }
747
748 /**
749 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
750 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
751 *
752 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source (selector od join)
753 * @param array $rows
754 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
755 * @param null|integer $workspaceUid
756 * @return array
757 */
758 protected function doLanguageAndWorkspaceOverlay(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array $rows, \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $workspaceUid = NULL) {
759 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
760 $tableName = $source->getSelectorName();
761 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
762 $tableName = $source->getRight()->getSelectorName();
763 } else {
764 // No proper source, so we do not have a table name here
765 // we cannot do an overlay and return the original rows instead.
766 return $rows;
767 }
768
769 $pageRepository = $this->getPageRepository();
770 if (is_object($GLOBALS['TSFE'])) {
771 if ($workspaceUid !== NULL) {
772 $pageRepository->versioningWorkspaceId = $workspaceUid;
773 }
774 } else {
775 if ($workspaceUid === NULL) {
776 $workspaceUid = $GLOBALS['BE_USER']->workspace;
777 }
778 $pageRepository->versioningWorkspaceId = $workspaceUid;
779 }
780
781 $overlaidRows = array();
782 foreach ($rows as $row) {
783 // If current row is a translation select its parent
784 if (isset($tableName) && isset($GLOBALS['TCA'][$tableName])
785 && isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
786 && isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
787 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
788 ) {
789 if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
790 && $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
791 ) {
792 $row = $this->databaseHandle->exec_SELECTgetSingleRow(
793 $tableName . '.*',
794 $tableName,
795 $tableName . '.uid=' . (int)$row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
796 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
797 );
798 }
799 }
800 $pageRepository->versionOL($tableName, $row, TRUE);
801 if ($pageRepository->versioningPreview && isset($row['_ORIG_uid'])) {
802 $row['uid'] = $row['_ORIG_uid'];
803 }
804 if ($tableName == 'pages') {
805 $row = $pageRepository->getPageOverlay($row, $querySettings->getLanguageUid());
806 } elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
807 && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
808 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
809 ) {
810 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1, 0))) {
811 $overlayMode = $querySettings->getLanguageMode() === 'strict' ? 'hideNonTranslated' : '';
812 $row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getLanguageUid(), $overlayMode);
813 }
814 }
815 if ($row !== NULL && is_array($row)) {
816 $overlaidRows[] = $row;
817 }
818 }
819 return $overlaidRows;
820 }
821
822 /**
823 * @return \TYPO3\CMS\Frontend\Page\PageRepository
824 */
825 protected function getPageRepository() {
826 if (!$this->pageRepository instanceof \TYPO3\CMS\Frontend\Page\PageRepository) {
827 if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
828 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
829 } else {
830 $this->pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
831 }
832 }
833
834 return $this->pageRepository;
835 }
836
837 /**
838 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
839 *
840 * @return void
841 * @param string $sql The SQL statement
842 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException
843 */
844 protected function checkSqlErrors($sql = '') {
845 $error = $this->databaseHandle->sql_error();
846 if ($error !== '') {
847 $error .= $sql ? ': ' . $sql : '';
848 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException($error, 1247602160);
849 }
850 }
851
852 /**
853 * Clear the TYPO3 page cache for the given record.
854 * If the record lies on a page, then we clear the cache of this page.
855 * If the record has no PID column, we clear the cache of the current page as best-effort.
856 *
857 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
858 *
859 * @param string $tableName Table name of the record
860 * @param integer $uid UID of the record
861 * @return void
862 */
863 protected function clearPageCache($tableName, $uid) {
864 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
865 if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
866 } else {
867 // if disabled, return
868 return;
869 }
870 $pageIdsToClear = array();
871 $storagePage = NULL;
872 $columns = $this->databaseHandle->admin_get_fields($tableName);
873 if (array_key_exists('pid', $columns)) {
874 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid=' . (int)$uid);
875 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
876 $storagePage = $row['pid'];
877 $pageIdsToClear[] = $storagePage;
878 }
879 } elseif (isset($GLOBALS['TSFE'])) {
880 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
881 $storagePage = $GLOBALS['TSFE']->id;
882 $pageIdsToClear[] = $storagePage;
883 }
884 if ($storagePage === NULL) {
885 return;
886 }
887 if (!isset($this->pageTSConfigCache[$storagePage])) {
888 $this->pageTSConfigCache[$storagePage] = BackendUtility::getPagesTSconfig($storagePage);
889 }
890 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
891 $clearCacheCommands = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']), TRUE);
892 $clearCacheCommands = array_unique($clearCacheCommands);
893 foreach ($clearCacheCommands as $clearCacheCommand) {
894 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($clearCacheCommand)) {
895 $pageIdsToClear[] = $clearCacheCommand;
896 }
897 }
898 }
899
900 foreach ($pageIdsToClear as $pageIdToClear) {
901 $this->cacheService->getPageIdStack()->push($pageIdToClear);
902 }
903 }
904
905 /**
906 * Finds and returns a variable value from the query cache.
907 *
908 * @param string $entryIdentifier Identifier of the cache entry to fetch
909 * @return mixed The value
910 */
911 protected function getQueryCacheEntry($entryIdentifier) {
912 if (!isset($this->queryRuntimeCache[$entryIdentifier])) {
913 $this->queryRuntimeCache[$entryIdentifier] = $this->queryCache->get($entryIdentifier);
914 }
915 return $this->queryRuntimeCache[$entryIdentifier];
916 }
917
918 /**
919 * Saves the value of a PHP variable in the query cache.
920 *
921 * @param string $entryIdentifier An identifier used for this cache entry
922 * @param mixed $variable The query to cache
923 * @return void
924 */
925 protected function setQueryCacheEntry($entryIdentifier, $variable) {
926 $this->queryRuntimeCache[$entryIdentifier] = $variable;
927 $this->queryCache->set($entryIdentifier, $variable, array(), 0);
928 }
929 }