[~TASK] Extbase: Refactored Dispatcher. Moved initialization of cache and reflection...
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Storage / Typo3DbBackend.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
6 * All rights reserved
7 *
8 * This class is a backport of the corresponding class of FLOW3.
9 * All credits go to the v5 team.
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 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27
28 /**
29 * A Storage backend
30 *
31 * @package Extbase
32 * @subpackage Persistence\Storage
33 * @version $Id: $
34 */
35 class Tx_Extbase_Persistence_Storage_Typo3DbBackend implements Tx_Extbase_Persistence_Storage_BackendInterface, t3lib_Singleton {
36
37 const OPERATOR_EQUAL_TO_NULL = 'operatorEqualToNull';
38 const OPERATOR_NOT_EQUAL_TO_NULL = 'operatorNotEqualToNull';
39
40 /**
41 * The TYPO3 database object
42 *
43 * @var t3lib_db
44 */
45 protected $databaseHandle;
46
47 /**
48 * @var Tx_Extbase_Persistence_DataMapper
49 */
50 protected $dataMapper;
51
52 /**
53 * The TYPO3 page select object. Used for language and workspace overlay
54 *
55 * @var t3lib_pageSelect
56 */
57 protected $pageSelectObject;
58
59 /**
60 * Constructs this Storage Backend instance
61 *
62 * @param t3lib_db $databaseHandle The database handle
63 */
64 public function __construct($databaseHandle) {
65 $this->databaseHandle = $databaseHandle;
66 }
67
68 /**
69 * Injects the DataMapper to map nodes to objects
70 *
71 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
72 * @return void
73 */
74 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper) {
75 $this->dataMapper = $dataMapper;
76 }
77
78 /**
79 * Adds a row to the storage
80 *
81 * @param string $tableName The database table name
82 * @param array $row The row to be inserted
83 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
84 * @return int The uid of the inserted row
85 */
86 public function addRow($tableName, array $row, $isRelation = FALSE) {
87 $fields = array();
88 $values = array();
89 $parameters = array();
90 if (isset($row['uid'])) {
91 unset($row['uid']);
92 }
93 foreach ($row as $columnName => $value) {
94 $fields[] = $columnName;
95 $values[] = '?';
96 $parameters[] = $value;
97 }
98
99 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
100 $this->replacePlaceholders($sqlString, $parameters);
101 $this->databaseHandle->sql_query($sqlString);
102 $this->checkSqlErrors();
103 $uid = $this->databaseHandle->sql_insert_id();
104 if (!$isRelation) {
105 $this->clearPageCache($tableName, $uid);
106 }
107 return $uid;
108 }
109
110 /**
111 * Updates a row in the storage
112 *
113 * @param string $tableName The database table name
114 * @param array $row The row to be updated
115 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
116 * @return void
117 */
118 public function updateRow($tableName, array $row, $isRelation = FALSE) {
119 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
120 $uid = (int)$row['uid'];
121 unset($row['uid']);
122 $fields = array();
123 $parameters = array();
124 foreach ($row as $columnName => $value) {
125 $fields[] = $columnName . '=?';
126 $parameters[] = $value;
127 }
128 $parameters[] = $uid;
129
130 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
131 $this->replacePlaceholders($sqlString, $parameters);
132
133 $returnValue = $this->databaseHandle->sql_query($sqlString);
134 $this->checkSqlErrors();
135 if (!$isRelation) {
136 $this->clearPageCache($tableName, $uid);
137 }
138 return $returnValue;
139 }
140
141 /**
142 * Deletes a row in the storage
143 *
144 * @param string $tableName The database table name
145 * @param array $identifyer An array of identifyer array('fieldname' => value). This array will be transformed to a WHERE clause
146 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
147 * @return void
148 */
149 public function removeRow($tableName, array $identifyer, $isRelation = FALSE) {
150 $fieldNames = array_keys($identifyer);
151 $suffixedFieldNames = array();
152 foreach ($fieldNames as $fieldName) {
153 $suffixedFieldNames[] = $fieldName . '=?';
154 }
155 $parameters = array_values($identifyer);
156 $statement = 'DELETE FROM ' . $tableName;
157 $statement .= ' WHERE ' . implode(' AND ', $suffixedFieldNames);
158 $this->replacePlaceholders($statement, $parameters);
159 if (!$isRelation) {
160 $this->clearPageCache($tableName, $uid, $isRelation);
161 }
162 $returnValue = $this->databaseHandle->sql_query($statement);
163 $this->checkSqlErrors();
164 return $returnValue;
165 }
166
167 /**
168 * Returns an array with tuples matching the query.
169 *
170 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
171 * @return array The matching tuples
172 */
173 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
174 $statement = $this->parseQuery($query);
175 // debug($statement, -2); // FIXME remove debug code
176 $result = $this->databaseHandle->sql_query($statement);
177 $this->checkSqlErrors();
178 if ($result) {
179 $tuples = $this->getRowsFromResult($query->getSource(), $result);
180 }
181
182 return $tuples;
183 }
184
185 /**
186 * Returns an array with tuples matching the query.
187 *
188 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
189 * @return array The matching tuples
190 */
191 public function parseQuery(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
192 $statement = '';
193 $parameters = array();
194 $constraint = $query->getConstraint();
195 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface) {
196 if ($constraint->getLanguage() === Tx_Extbase_Persistence_QOM_QueryObjectModelInterface::TYPO3_SQL_MYSQL) {
197 $statement = $constraint->getStatement();
198 $parameters= $query->getBoundVariableValues();
199 } else {
200 throw new Tx_Extbase_Persistence_Exception('Unsupported query language.', 1248701951);
201 }
202 } else {
203 $sql = array();
204 $sql['tables'] = array();
205 $sql['fields'] = array();
206 $sql['where'] = array();
207 $sql['additionalWhereClause'] = array();
208 $sql['orderings'] = array();
209 $sql['limit'] = array();
210 $tuples = array();
211
212 $source = $query->getSource();
213 $this->parseSource($query, $source, $sql, $parameters);
214
215 $statement = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
216
217 $this->parseConstraint($constraint, $source, $sql, $parameters, $query->getBoundVariableValues());
218
219 if (!empty($sql['where'])) {
220 $statement .= ' WHERE ' . implode('', $sql['where']);
221 if (!empty($sql['additionalWhereClause'])) {
222 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
223 }
224 } elseif (!empty($sql['additionalWhereClause'])) {
225 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
226 }
227
228 $this->parseOrderings($query->getOrderings(), $source, $sql);
229 if (!empty($sql['orderings'])) {
230 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
231 }
232
233 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
234 if (!empty($sql['limit'])) {
235 $statement .= ' LIMIT ' . $sql['limit'];
236 }
237 }
238
239 $this->replacePlaceholders($statement, $parameters);
240 // debug($statement,-2);
241 return $statement;
242 }
243
244 /**
245 * Checks if a Value Object equal to the given Object exists in the data base
246 *
247 * @param array $properties The properties of the Value Object
248 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
249 * @return array The matching uid
250 */
251 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap $dataMap) {
252 $fields = array();
253 $parameters = array();
254 foreach ($properties as $propertyName => $propertyValue) {
255 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
256 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
257 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
258 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
259 }
260 }
261 $sql = array();
262 $sql['additionalWhereClause'] = array();
263
264 $tableName = $dataMap->getTableName();
265 $this->addEnableFieldsStatement($tableName, $sql);
266
267 $statement = 'SELECT * FROM ' . $tableName;
268 $statement .= ' WHERE ' . implode(' AND ', $fields);
269 if (!empty($sql['additionalWhereClause'])) {
270 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
271 }
272 $this->replacePlaceholders($statement, $parameters);
273 $res = $this->databaseHandle->sql_query($statement);
274 $this->checkSqlErrors();
275 $row = $this->databaseHandle->sql_fetch_assoc($res);
276 if ($row !== FALSE) {
277 return $row['uid'];
278 } else {
279 return FALSE;
280 }
281 }
282
283 /**
284 * Transforms a Query Source into SQL and parameter arrays
285 *
286 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
287 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
288 * @param array &$sql
289 * @param array &$parameters
290 * @return void
291 */
292 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
293 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
294 $tableName = $source->getSelectorName();
295 $sql['fields'][] = $tableName . '.*';
296 $sql['tables'][] = $tableName;
297 $querySettings = $query->getQuerySettings();
298 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
299 if ($querySettings->getRespectEnableFields()) {
300 $this->addEnableFieldsStatement($tableName, $sql);
301 }
302 if ($querySettings->getRespectStoragePage()) {
303 $this->addPageIdStatement($tableName, $sql);
304 }
305 }
306 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
307 $this->parseJoin($query, $source, $sql);
308 }
309 }
310
311 /**
312 * Transforms a Join into SQL and parameter arrays
313 *
314 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query The Query Object Model
315 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
316 * @param array &$sql The query parts
317 * @return void
318 */
319 protected function parseJoin(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql) {
320 $leftSource = $join->getLeft();
321 $leftTableName = $leftSource->getSelectorName();
322 $rightSource = $join->getRight();
323 $rightTableName = $rightSource->getSelectorName();
324
325 $sql['fields'][] = $leftTableName . '.*';
326 $sql['fields'][] = $rightTableName . '.*';
327
328 // TODO Implement support for different join types and nested joins
329 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
330
331 $joinCondition = $join->getJoinCondition();
332 // TODO Check the parsing of the join
333 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
334 // TODO Discuss, if we should use $leftSource instead of $selector1Name
335 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
336 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
337 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
338 }
339 // TODO Implement childtableWhere
340
341 $querySettings = $query->getQuerySettings();
342 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
343 if ($querySettings->getRespectEnableFields()) {
344 $this->addEnableFieldsStatement($leftTableName, $sql);
345 $this->addEnableFieldsStatement($rightTableName, $sql);
346 }
347 if ($querySettings->getRespectStoragePage()) {
348 $this->addPageIdStatement($leftTableName, $sql);
349 $this->addPageIdStatement($rightTableName, $sql);
350 }
351 }
352 }
353
354 /**
355 * Transforms a constraint into SQL and parameter arrays
356 *
357 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
358 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
359 * @param array &$sql The query parts
360 * @param array &$parameters The parameters that will replace the markers
361 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
362 * @return void
363 */
364 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
365 if ($constraint === NULL) return;
366 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
367 $sql['where'][] = '(';
368 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
369 $sql['where'][] = ' AND ';
370 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
371 $sql['where'][] = ')';
372 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
373 $sql['where'][] = '(';
374 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
375 $sql['where'][] = ' OR ';
376 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
377 $sql['where'][] = ')';
378 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
379 $sql['where'][] = 'NOT (';
380 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters, $boundVariableValues);
381 $sql['where'][] = ')';
382 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
383 $this->parseComparison($constraint, $source, $sql, $parameters, $boundVariableValues);
384 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface) {
385 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
386 }
387 }
388
389 /**
390 * Parse a Comparison into SQL and parameter arrays.
391 *
392 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
393 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
394 * @param array &$sql SQL query parts to add to
395 * @param array &$parameters Parameters to bind to the SQL
396 * @param array $boundVariableValues The bound variables in the query and their values
397 * @return void
398 */
399 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
400 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
401
402 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
403 $operator = $comparison->getOperator();
404 if ($value === NULL) {
405 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO) {
406 $operator = self::OPERATOR_EQUAL_TO_NULL;
407 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO) {
408 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
409 } else {
410 // TODO Throw exception
411 }
412 }
413 $parameters[] = $value;
414
415 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $source, $sql, $parameters);
416 }
417
418 /**
419 * Parse a DynamicOperand into SQL and parameter arrays.
420 *
421 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
422 * @param string $operator One of the JCR_OPERATOR_* constants
423 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
424 * @param array &$sql The query parts
425 * @param array &$parameters The parameters that will replace the markers
426 * @param string $valueFunction an optional SQL function to apply to the operand value
427 * @return void
428 */
429 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL) {
430 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
431 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
432 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
433 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
434 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
435 $tableName = $operand->getSelectorName();
436 // FIXME Discuss the translation from propertyName to columnName
437 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
438 $className = $source->getNodeTypeName();
439 } else {
440 $className = '';
441 }
442 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
443 $operator = $this->resolveOperator($operator);
444
445 if ($valueFunction === NULL) {
446 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
447 } else {
448 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
449 }
450
451 $sql['where'][] = $constraintSQL;
452 }
453 }
454
455 /**
456 * Returns the SQL operator for the given JCR operator type.
457 *
458 * @param string $operator One of the JCR_OPERATOR_* constants
459 * @return string an SQL operator
460 */
461 protected function resolveOperator($operator) {
462 switch ($operator) {
463 case self::OPERATOR_EQUAL_TO_NULL:
464 $operator = 'IS';
465 break;
466 case self::OPERATOR_NOT_EQUAL_TO_NULL:
467 $operator = 'IS NOT';
468 break;
469 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO:
470 $operator = '=';
471 break;
472 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO:
473 $operator = '!=';
474 break;
475 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN:
476 $operator = '<';
477 break;
478 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO:
479 $operator = '<=';
480 break;
481 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN:
482 $operator = '>';
483 break;
484 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO:
485 $operator = '>=';
486 break;
487 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LIKE:
488 $operator = 'LIKE';
489 break;
490 default:
491 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
492 }
493
494 return $operator;
495 }
496
497 /**
498 * Replace query placeholders in a query part by the given
499 * parameters.
500 *
501 * @param string $sqlString The query part with placeholders
502 * @param array $parameters The parameters
503 * @return string The query part with replaced placeholders
504 */
505 protected function replacePlaceholders(&$sqlString, array $parameters) {
506 if (substr_count($sqlString, '?') !== count($parameters)) throw new Tx_Extbase_Persistence_Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
507 $offset = 0;
508 foreach ($parameters as $parameter) {
509 $markPosition = strpos($sqlString, '?', $offset);
510 if ($markPosition !== FALSE) {
511 if ($parameter === NULL) {
512 $parameter = 'NULL';
513 } else {
514 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
515 }
516 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition + 1);
517 }
518 $offset = $markPosition + strlen($parameter);
519 }
520 }
521
522 /**
523 * Builds the enable fields statement
524 *
525 * @param string $tableName The database table name
526 * @param array &$sql The query parts
527 * @return void
528 */
529 protected function addEnableFieldsStatement($tableName, array &$sql) {
530 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
531 if (TYPO3_MODE === 'FE') {
532 $statement = $GLOBALS['TSFE']->sys_page->enableFields($tableName);
533 } else { // TYPO3_MODE === 'BE'
534 $statement = t3lib_BEfunc::deleteClause($tableName);
535 $statement .= t3lib_BEfunc::BEenableFields($tableName);
536 }
537 if(!empty($statement)) {
538 $statement = substr($statement, 5);
539 $sql['additionalWhereClause'][] = $statement;
540 }
541 }
542 }
543
544 /**
545 * Builds the page ID checking statement
546 *
547 * @param string $tableName The database table name
548 * @param array &$sql The query parts
549 * @return void
550 */
551 protected function addPageIdStatement($tableName, array &$sql) {
552 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
553 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
554 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
555 }
556 }
557
558 /**
559 * Transforms orderings into SQL.
560 *
561 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
562 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
563 * @param array &$sql The query parts
564 * @return void
565 */
566 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
567 foreach ($orderings as $ordering) {
568 $operand = $ordering->getOperand();
569 $order = $ordering->getOrder();
570 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue) {
571 switch ($order) {
572 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
573 $order = 'ASC';
574 break;
575 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
576 $order = 'DESC';
577 break;
578 default:
579 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
580 }
581 $tableName = $operand->getSelectorName();
582 $className = '';
583 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
584 $className = $source->getNodeTypeName();
585 }
586 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
587 if (strlen($tableName) > 0) {
588 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
589 } else {
590 $sql['orderings'][] = $columnName . ' ' . $order;
591 }
592 }
593 }
594 }
595
596 /**
597 * Transforms limit and offset into SQL
598 *
599 * @param int $limit
600 * @param int $offset
601 * @param array &$sql
602 * @return void
603 */
604 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
605 if ($limit !== NULL && $offset !== NULL) {
606 $sql['limit'] = $offset . ', ' . $limit;
607 } elseif ($limit !== NULL) {
608 $sql['limit'] = $limit;
609 }
610 }
611
612 /**
613 * Transforms a Resource from a database query to an array of rows. Performs the language and
614 * workspace overlay before.
615 *
616 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
617 * @param resource &$sql The resource
618 * @return array The result as an array of rows (tuples)
619 */
620 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $res) {
621 $rows = array();
622 while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
623 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
624 // FIXME The overlay is only performed if we query a single table; no joins
625 $row = $this->doLanguageAndWorkspaceOverlay($source->getSelectorName(), $row);
626 }
627 if (is_array($row)) {
628 // TODO Check if this is necessary, maybe the last line is enough
629 $arrayKeys = range(0,count($row));
630 array_fill_keys($arrayKeys, $row);
631 $rows[] = $row;
632 }
633 }
634 return $rows;
635 }
636
637 /**
638 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
639 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
640 *
641 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
642 * @param array $row The row array (as reference)
643 * @param string $languageUid The language id
644 * @param string $workspaceUidUid The workspace id
645 * @return void
646 */
647 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
648 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
649 if (TYPO3_MODE == 'FE') {
650 if (is_object($GLOBALS['TSFE'])) {
651 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
652 if ($languageUid === NULL) {
653 $languageUid = $GLOBALS['TSFE']->sys_language_content;
654 }
655 } else {
656 require_once(PATH_t3lib . 'class.t3lib_page.php');
657 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
658 if ($languageUid === NULL) {
659 $languageUid = intval(t3lib_div::_GP('L'));
660 }
661 }
662 if ($workspaceUid !== NULL) {
663 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
664 }
665 } else {
666 require_once(PATH_t3lib . 'class.t3lib_page.php');
667 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
668 if ($workspaceUid === NULL) {
669 $workspaceUid = $GLOBALS['BE_USER']->workspace;
670 }
671 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
672 }
673 }
674
675 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
676 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
677 // TODO Skip if empty languageoverlay (languagevisibility)
678 return $row;
679 }
680
681 /**
682 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
683 *
684 * @return void
685 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
686 */
687 protected function checkSqlErrors() {
688 $error = $this->databaseHandle->sql_error();
689 if ($error !== '') {
690 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
691 }
692 }
693
694 /**
695 * Clear the TYPO3 page cache for the given record.
696 * If the record lies on a page, then we clear the cache of this page.
697 * If the record has no PID column, we clear the cache of the current page as best-effort.
698 *
699 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
700 *
701 * @param $tableName Table name of the record
702 * @param $uid UID of the record
703 * @return void
704 */
705 protected function clearPageCache($tableName, $uid) {
706 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
707 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
708 } else {
709 // if disabled, return
710 return;
711 }
712
713 $pageIdsToClear = array();
714 $storagePage = NULL;
715
716 if ($this->dataMapper->getDataMap($tableName)->hasPidColumn()) {
717 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
718 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
719 $storagePage = $row['pid'];
720 $pageIdsToClear[] = $storagePage;
721 }
722 } elseif (isset($GLOBALS['TSFE'])) {
723 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
724 $storagePage = $GLOBALS['TSFE']->id;
725 $pageIdsToClear[] = $storagePage;
726 }
727
728
729 if ($storagePage === NULL) {
730 return;
731 }
732
733 $pageTSConfig = t3lib_BEfunc::getPagesTSconfig($storagePage);
734 if (isset($pageTSConfig['TCEMAIN.']['clearCacheCmd'])) {
735 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($pageTSConfig['TCEMAIN.']['clearCacheCmd']),1);
736 $clearCacheCommands = array_unique($clearCacheCommands);
737 foreach ($clearCacheCommands as $clearCacheCommand) {
738 if (t3lib_div::testInt($clearCacheCommand)) {
739 $pageIdsToClear[] = $clearCacheCommand;
740 }
741 }
742 }
743
744 Tx_Extbase_Utility_Cache::clearPageCache($pageIdsToClear);
745 }
746 }
747
748 ?>