[+BUGFIX] Extbase (Persistence): Fixed a problem where Objects are deleted from the...
[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 instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
366 $sql['where'][] = '(';
367 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
368 $sql['where'][] = ' AND ';
369 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
370 $sql['where'][] = ')';
371 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
372 $sql['where'][] = '(';
373 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
374 $sql['where'][] = ' OR ';
375 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
376 $sql['where'][] = ')';
377 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
378 $sql['where'][] = 'NOT (';
379 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters, $boundVariableValues);
380 $sql['where'][] = ')';
381 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
382 $this->parseComparison($constraint, $source, $sql, $parameters, $boundVariableValues);
383 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface) {
384 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
385 }
386 }
387
388 /**
389 * Parse a Comparison into SQL and parameter arrays.
390 *
391 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
392 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
393 * @param array &$sql SQL query parts to add to
394 * @param array &$parameters Parameters to bind to the SQL
395 * @param array $boundVariableValues The bound variables in the query and their values
396 * @return void
397 */
398 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
399 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
400
401 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
402 $operator = $comparison->getOperator();
403 if ($value === NULL) {
404 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO) {
405 $operator = self::OPERATOR_EQUAL_TO_NULL;
406 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO) {
407 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
408 } else {
409 // TODO Throw exception
410 }
411 }
412 $parameters[] = $value;
413
414 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $source, $sql, $parameters);
415 }
416
417 /**
418 * Parse a DynamicOperand into SQL and parameter arrays.
419 *
420 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
421 * @param string $operator One of the JCR_OPERATOR_* constants
422 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
423 * @param array &$sql The query parts
424 * @param array &$parameters The parameters that will replace the markers
425 * @param string $valueFunction an optional SQL function to apply to the operand value
426 * @return void
427 */
428 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL) {
429 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
430 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
431 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
432 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
433 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
434 $tableName = $operand->getSelectorName();
435 // FIXME Discuss the translation from propertyName to columnName
436 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
437 $className = $source->getNodeTypeName();
438 } else {
439 $className = '';
440 }
441 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
442 $operator = $this->resolveOperator($operator);
443
444 if ($valueFunction === NULL) {
445 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
446 } else {
447 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
448 }
449
450 $sql['where'][] = $constraintSQL;
451 }
452 }
453
454 /**
455 * Returns the SQL operator for the given JCR operator type.
456 *
457 * @param string $operator One of the JCR_OPERATOR_* constants
458 * @return string an SQL operator
459 */
460 protected function resolveOperator($operator) {
461 switch ($operator) {
462 case self::OPERATOR_EQUAL_TO_NULL:
463 $operator = 'IS';
464 break;
465 case self::OPERATOR_NOT_EQUAL_TO_NULL:
466 $operator = 'IS NOT';
467 break;
468 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO:
469 $operator = '=';
470 break;
471 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO:
472 $operator = '!=';
473 break;
474 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN:
475 $operator = '<';
476 break;
477 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO:
478 $operator = '<=';
479 break;
480 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN:
481 $operator = '>';
482 break;
483 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO:
484 $operator = '>=';
485 break;
486 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LIKE:
487 $operator = 'LIKE';
488 break;
489 default:
490 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
491 }
492
493 return $operator;
494 }
495
496 /**
497 * Replace query placeholders in a query part by the given
498 * parameters.
499 *
500 * @param string $sqlString The query part with placeholders
501 * @param array $parameters The parameters
502 * @return string The query part with replaced placeholders
503 */
504 protected function replacePlaceholders(&$sqlString, array $parameters) {
505 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);
506 $offset = 0;
507 foreach ($parameters as $parameter) {
508 $markPosition = strpos($sqlString, '?', $offset);
509 if ($markPosition !== FALSE) {
510 if ($parameter === NULL) {
511 $parameter = 'NULL';
512 } else {
513 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
514 }
515 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition + 1);
516 }
517 $offset = $markPosition + strlen($parameter);
518 }
519 }
520
521 /**
522 * Builds the enable fields statement
523 *
524 * @param string $tableName The database table name
525 * @param array &$sql The query parts
526 * @return void
527 */
528 protected function addEnableFieldsStatement($tableName, array &$sql) {
529 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
530 if (TYPO3_MODE === 'FE') {
531 $statement = $GLOBALS['TSFE']->sys_page->enableFields($tableName);
532 } else { // TYPO3_MODE === 'BE'
533 $statement = t3lib_BEfunc::deleteClause($tableName);
534 $statement .= t3lib_BEfunc::BEenableFields($tableName);
535 }
536 if(!empty($statement)) {
537 $statement = substr($statement, 5);
538 $sql['additionalWhereClause'][] = $statement;
539 }
540 }
541 }
542
543 /**
544 * Builds the page ID checking statement
545 *
546 * @param string $tableName The database table name
547 * @param array &$sql The query parts
548 * @return void
549 */
550 protected function addPageIdStatement($tableName, array &$sql) {
551 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
552 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
553 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
554 }
555 }
556
557 /**
558 * Transforms orderings into SQL.
559 *
560 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
561 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
562 * @param array &$sql The query parts
563 * @return void
564 */
565 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
566 foreach ($orderings as $ordering) {
567 $operand = $ordering->getOperand();
568 $order = $ordering->getOrder();
569 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue) {
570 switch ($order) {
571 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
572 $order = 'ASC';
573 break;
574 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
575 $order = 'DESC';
576 break;
577 default:
578 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
579 }
580 $tableName = $operand->getSelectorName();
581 if ((strlen($tableName) == 0) && (source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface)) {
582 $tableName = $source->getSelectorName();
583 }
584 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $tableName);
585 if (strlen($tableName) > 0) {
586 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
587 } else {
588 $sql['orderings'][] = $columnName . ' ' . $order;
589 }
590 }
591 }
592 }
593
594 /**
595 * Transforms limit and offset into SQL
596 *
597 * @param int $limit
598 * @param int $offset
599 * @param array &$sql
600 * @return void
601 */
602 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
603 if ($limit !== NULL && $offset !== NULL) {
604 $sql['limit'] = $offset . ', ' . $limit;
605 } elseif ($limit !== NULL) {
606 $sql['limit'] = $limit;
607 }
608 }
609
610 /**
611 * Transforms a Resource from a database query to an array of rows. Performs the language and
612 * workspace overlay before.
613 *
614 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
615 * @param resource &$sql The resource
616 * @return array The result as an array of rows (tuples)
617 */
618 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $res) {
619 $rows = array();
620 while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
621 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
622 // FIXME The overlay is only performed if we query a single table; no joins
623 $row = $this->doLanguageAndWorkspaceOverlay($source->getSelectorName(), $row);
624 }
625 if (is_array($row)) {
626 // TODO Check if this is necessary, maybe the last line is enough
627 $arrayKeys = range(0,count($row));
628 array_fill_keys($arrayKeys, $row);
629 $rows[] = $row;
630 }
631 }
632 return $rows;
633 }
634
635 /**
636 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
637 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
638 *
639 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
640 * @param array $row The row array (as reference)
641 * @param string $languageUid The language id
642 * @param string $workspaceUidUid The workspace id
643 * @return void
644 */
645 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
646 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
647 if (TYPO3_MODE == 'FE') {
648 if (is_object($GLOBALS['TSFE'])) {
649 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
650 if ($languageUid === NULL) {
651 $languageUid = $GLOBALS['TSFE']->sys_language_content;
652 }
653 } else {
654 require_once(PATH_t3lib . 'class.t3lib_page.php');
655 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
656 if ($languageUid === NULL) {
657 $languageUid = intval(t3lib_div::_GP('L'));
658 }
659 }
660 if ($workspaceUid !== NULL) {
661 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
662 }
663 } else {
664 require_once(PATH_t3lib . 'class.t3lib_page.php');
665 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
666 if ($workspaceUid === NULL) {
667 $workspaceUid = $GLOBALS['BE_USER']->workspace;
668 }
669 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
670 }
671 }
672
673 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
674 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
675 // TODO Skip if empty languageoverlay (languagevisibility)
676 return $row;
677 }
678
679 /**
680 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
681 *
682 * @return void
683 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
684 */
685 protected function checkSqlErrors() {
686 $error = $this->databaseHandle->sql_error();
687 if ($error !== '') {
688 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
689 }
690 }
691
692 /**
693 * Clear the TYPO3 page cache for the given record.
694 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
695 *
696 * @param $tableName Table name of the record
697 * @param $uid UID of the record
698 * @return void
699 */
700 protected function clearPageCache($tableName, $uid) {
701 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
702 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
703 } else {
704 // if disabled, return
705 return;
706 }
707
708 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
709
710 $pageIdsToClear = array();
711 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
712 $storagePage = $row['pid'];
713 $pageIdsToClear[] = $storagePage;
714 }
715 if (!$storagePage) {
716 return;
717 }
718
719 $pageTSConfig = t3lib_BEfunc::getPagesTSconfig($storagePage);
720 if (isset($pageTSConfig['TCEMAIN.']['clearCacheCmd'])) {
721 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($pageTSConfig['TCEMAIN.']['clearCacheCmd']),1);
722 $clearCacheCommands = array_unique($clearCacheCommands);
723 foreach ($clearCacheCommands as $clearCacheCommand) {
724 if (t3lib_div::testInt($clearCacheCommand)) {
725 $pageIdsToClear[] = $clearCacheCommand;
726 }
727 }
728 }
729
730 Tx_Extbase_Utility_Cache::clearPageCache($pageIdsToClear);
731 }
732 }
733
734 ?>