[~CONFIGURATION] Extbase: Set lockType to empty string instead of 'system'.
[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 $uid The uid of the row to be deleted
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, $uid, $isRelation = FALSE) {
150 $sqlString = 'DELETE FROM ' . $tableName . ' WHERE uid=?';
151 $this->replacePlaceholders($sqlString, array((int)$uid));
152 if (!$isRelation) {
153 $this->clearPageCache($tableName, $uid, $isRelation);
154 }
155 $returnValue = $this->databaseHandle->sql_query($sqlString);
156 $this->checkSqlErrors();
157 return $returnValue;
158 }
159
160 /**
161 * Returns an array with tuples matching the query.
162 *
163 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
164 * @return array The matching tuples
165 */
166 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
167 $statement = $this->parseQuery($query);
168 // debug($statement, -2); // FIXME remove debug code
169 $result = $this->databaseHandle->sql_query($statement);
170 $this->checkSqlErrors();
171 if ($result) {
172 $tuples = $this->getRowsFromResult($query->getSource(), $result);
173 }
174
175 return $tuples;
176 }
177
178 /**
179 * Returns an array with tuples matching the query.
180 *
181 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
182 * @return array The matching tuples
183 */
184 public function parseQuery(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
185 $statement = '';
186 $parameters = array();
187 $constraint = $query->getConstraint();
188 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface) {
189 if ($constraint->getLanguage() === Tx_Extbase_Persistence_QOM_QueryObjectModelInterface::TYPO3_SQL_MYSQL) {
190 $statement = $constraint->getStatement();
191 $parameters= $query->getBoundVariableValues();
192 } else {
193 throw new Tx_Extbase_Persistence_Exception('Unsupported query language.', 1248701951);
194 }
195 } else {
196 $sql = array();
197 $sql['tables'] = array();
198 $sql['fields'] = array();
199 $sql['where'] = array();
200 $sql['additionalWhereClause'] = array();
201 $sql['orderings'] = array();
202 $sql['limit'] = array();
203 $tuples = array();
204
205 $source = $query->getSource();
206 $this->parseSource($query, $source, $sql, $parameters);
207
208 $statement = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
209
210 $this->parseConstraint($constraint, $source, $sql, $parameters, $query->getBoundVariableValues());
211
212 if (!empty($sql['where'])) {
213 $statement .= ' WHERE ' . implode('', $sql['where']);
214 if (!empty($sql['additionalWhereClause'])) {
215 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
216 }
217 } elseif (!empty($sql['additionalWhereClause'])) {
218 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
219 }
220
221 $this->parseOrderings($query->getOrderings(), $source, $sql);
222 if (!empty($sql['orderings'])) {
223 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
224 }
225
226 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
227 if (!empty($sql['limit'])) {
228 $statement .= ' LIMIT ' . $sql['limit'];
229 }
230 }
231
232 $this->replacePlaceholders($statement, $parameters);
233 // debug($statement,-2);
234 return $statement;
235 }
236
237 /**
238 * Checks if a Value Object equal to the given Object exists in the data base
239 *
240 * @param array $properties The properties of the Value Object
241 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
242 * @return array The matching uid
243 */
244 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap $dataMap) {
245 $fields = array();
246 $parameters = array();
247 foreach ($properties as $propertyName => $propertyValue) {
248 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
249 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
250 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
251 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
252 }
253 }
254 $sql = array();
255 $sql['additionalWhereClause'] = array();
256
257 $tableName = $dataMap->getTableName();
258 $this->addEnableFieldsStatement($tableName, $sql);
259
260 $statement = 'SELECT * FROM ' . $tableName;
261 $statement .= ' WHERE ' . implode(' AND ', $fields);
262 if (!empty($sql['additionalWhereClause'])) {
263 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
264 }
265 $this->replacePlaceholders($statement, $parameters);
266 $res = $this->databaseHandle->sql_query($statement);
267 $this->checkSqlErrors();
268 $row = $this->databaseHandle->sql_fetch_assoc($res);
269 if ($row !== FALSE) {
270 return $row['uid'];
271 } else {
272 return FALSE;
273 }
274 }
275
276 /**
277 * Transforms a Query Source into SQL and parameter arrays
278 *
279 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
280 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
281 * @param array &$sql
282 * @param array &$parameters
283 * @return void
284 */
285 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
286 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
287 $tableName = $source->getSelectorName();
288 $sql['fields'][] = $tableName . '.*';
289 $sql['tables'][] = $tableName;
290 $querySettings = $query->getQuerySettings();
291 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
292 if ($querySettings->getRespectEnableFields()) {
293 $this->addEnableFieldsStatement($tableName, $sql);
294 }
295 if ($querySettings->getRespectStoragePage()) {
296 $this->addPageIdStatement($tableName, $sql);
297 }
298 }
299 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
300 $this->parseJoin($query, $source, $sql);
301 }
302 }
303
304 /**
305 * Transforms a Join into SQL and parameter arrays
306 *
307 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query The Query Object Model
308 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
309 * @param array &$sql The query parts
310 * @return void
311 */
312 protected function parseJoin(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query, Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql) {
313 $leftSource = $join->getLeft();
314 $leftTableName = $leftSource->getSelectorName();
315 $rightSource = $join->getRight();
316 $rightTableName = $rightSource->getSelectorName();
317
318 $sql['fields'][] = $leftTableName . '.*';
319 $sql['fields'][] = $rightTableName . '.*';
320
321 // TODO Implement support for different join types and nested joins
322 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
323
324 $joinCondition = $join->getJoinCondition();
325 // TODO Check the parsing of the join
326 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
327 // TODO Discuss, if we should use $leftSource instead of $selector1Name
328 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
329 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
330 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
331 }
332 // TODO Implement childtableWhere
333
334 $querySettings = $query->getQuerySettings();
335 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
336 if ($querySettings->getRespectEnableFields()) {
337 $this->addEnableFieldsStatement($leftTableName, $sql);
338 $this->addEnableFieldsStatement($rightTableName, $sql);
339 }
340 if ($querySettings->getRespectStoragePage()) {
341 $this->addPageIdStatement($leftTableName, $sql);
342 $this->addPageIdStatement($rightTableName, $sql);
343 }
344 }
345 }
346
347 /**
348 * Transforms a constraint into SQL and parameter arrays
349 *
350 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
351 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
352 * @param array &$sql The query parts
353 * @param array &$parameters The parameters that will replace the markers
354 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
355 * @return void
356 */
357 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
358 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
359 $sql['where'][] = '(';
360 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
361 $sql['where'][] = ' AND ';
362 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
363 $sql['where'][] = ')';
364 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
365 $sql['where'][] = '(';
366 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters, $boundVariableValues);
367 $sql['where'][] = ' OR ';
368 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters, $boundVariableValues);
369 $sql['where'][] = ')';
370 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
371 $sql['where'][] = 'NOT (';
372 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters, $boundVariableValues);
373 $sql['where'][] = ')';
374 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
375 $this->parseComparison($constraint, $source, $sql, $parameters, $boundVariableValues);
376 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface) {
377 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
378 }
379 }
380
381 /**
382 * Parse a Comparison into SQL and parameter arrays.
383 *
384 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
385 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
386 * @param array &$sql SQL query parts to add to
387 * @param array &$parameters Parameters to bind to the SQL
388 * @param array $boundVariableValues The bound variables in the query and their values
389 * @return void
390 */
391 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, array $boundVariableValues) {
392 if (!($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface)) throw new Tx_Extbase_Persistence_Exception('Type of operand is not supported', 1247581135);
393
394 $value = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
395 $operator = $comparison->getOperator();
396 if ($value === NULL) {
397 if ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO) {
398 $operator = self::OPERATOR_EQUAL_TO_NULL;
399 } elseif ($operator === Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO) {
400 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
401 } else {
402 // TODO Throw exception
403 }
404 }
405 $parameters[] = $value;
406
407 $this->parseDynamicOperand($comparison->getOperand1(), $operator, $source, $sql, $parameters);
408 }
409
410 /**
411 * Parse a DynamicOperand into SQL and parameter arrays.
412 *
413 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
414 * @param string $operator One of the JCR_OPERATOR_* constants
415 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
416 * @param array &$sql The query parts
417 * @param array &$parameters The parameters that will replace the markers
418 * @param string $valueFunction an optional SQL function to apply to the operand value
419 * @return void
420 */
421 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL) {
422 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
423 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
424 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
425 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
426 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
427 $tableName = $operand->getSelectorName();
428 // FIXME Discuss the translation from propertyName to columnName
429 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
430 $className = $source->getNodeTypeName();
431 } else {
432 $className = '';
433 }
434 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
435 $operator = $this->resolveOperator($operator);
436
437 if ($valueFunction === NULL) {
438 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
439 } else {
440 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
441 }
442
443 $sql['where'][] = $constraintSQL;
444 }
445 }
446
447 /**
448 * Returns the SQL operator for the given JCR operator type.
449 *
450 * @param string $operator One of the JCR_OPERATOR_* constants
451 * @return string an SQL operator
452 */
453 protected function resolveOperator($operator) {
454 switch ($operator) {
455 case self::OPERATOR_EQUAL_TO_NULL:
456 $operator = 'IS';
457 break;
458 case self::OPERATOR_NOT_EQUAL_TO_NULL:
459 $operator = 'IS NOT';
460 break;
461 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO:
462 $operator = '=';
463 break;
464 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO:
465 $operator = '!=';
466 break;
467 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN:
468 $operator = '<';
469 break;
470 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO:
471 $operator = '<=';
472 break;
473 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN:
474 $operator = '>';
475 break;
476 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO:
477 $operator = '>=';
478 break;
479 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LIKE:
480 $operator = 'LIKE';
481 break;
482 default:
483 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
484 }
485
486 return $operator;
487 }
488
489 /**
490 * Replace query placeholders in a query part by the given
491 * parameters.
492 *
493 * @param string $sqlString The query part with placeholders
494 * @param array $parameters The parameters
495 * @return string The query part with replaced placeholders
496 */
497 protected function replacePlaceholders(&$sqlString, array $parameters) {
498 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);
499 $offset = 0;
500 foreach ($parameters as $parameter) {
501 $markPosition = strpos($sqlString, '?', $offset);
502 if ($markPosition !== FALSE) {
503 if ($parameter === NULL) {
504 $parameter = 'NULL';
505 } else {
506 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
507 }
508 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition + 1);
509 }
510 $offset = $markPosition + strlen($parameter);
511 }
512 }
513
514 /**
515 * Builds the enable fields statement
516 *
517 * @param string $tableName The database table name
518 * @param array &$sql The query parts
519 * @return void
520 */
521 protected function addEnableFieldsStatement($tableName, array &$sql) {
522 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
523 if (TYPO3_MODE === 'FE') {
524 $statement = $GLOBALS['TSFE']->sys_page->enableFields($tableName);
525 } else { // TYPO3_MODE === 'BE'
526 $statement = t3lib_BEfunc::deleteClause($tableName);
527 $statement .= t3lib_BEfunc::BEenableFields($tableName);
528 }
529 if(!empty($statement)) {
530 $statement = substr($statement, 5);
531 $sql['additionalWhereClause'][] = $statement;
532 }
533 }
534 }
535
536 /**
537 * Builds the page ID checking statement
538 *
539 * @param string $tableName The database table name
540 * @param array &$sql The query parts
541 * @return void
542 */
543 protected function addPageIdStatement($tableName, array &$sql) {
544 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
545 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
546 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
547 }
548 }
549
550 /**
551 * Transforms orderings into SQL.
552 *
553 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
554 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
555 * @param array &$sql The query parts
556 * @return void
557 */
558 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
559 foreach ($orderings as $ordering) {
560 $operand = $ordering->getOperand();
561 $order = $ordering->getOrder();
562 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue) {
563 switch ($order) {
564 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
565 $order = 'ASC';
566 break;
567 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
568 $order = 'DESC';
569 break;
570 default:
571 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
572 }
573 $tableName = $operand->getSelectorName();
574 if ((strlen($tableName) == 0) && (source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface)) {
575 $tableName = $source->getSelectorName();
576 }
577 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $tableName);
578 if (strlen($tableName) > 0) {
579 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
580 } else {
581 $sql['orderings'][] = $columnName . ' ' . $order;
582 }
583 }
584 }
585 }
586
587 /**
588 * Transforms limit and offset into SQL
589 *
590 * @param int $limit
591 * @param int $offset
592 * @param array &$sql
593 * @return void
594 */
595 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
596 if ($limit !== NULL && $offset !== NULL) {
597 $sql['limit'] = $offset . ', ' . $limit;
598 } elseif ($limit !== NULL) {
599 $sql['limit'] = $limit;
600 }
601 }
602
603 /**
604 * Transforms a Resource from a database query to an array of rows. Performs the language and
605 * workspace overlay before.
606 *
607 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
608 * @param resource &$sql The resource
609 * @return array The result as an array of rows (tuples)
610 */
611 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $res) {
612 $rows = array();
613 while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
614 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
615 // FIXME The overlay is only performed if we query a single table; no joins
616 $row = $this->doLanguageAndWorkspaceOverlay($source->getSelectorName(), $row);
617 }
618 if (is_array($row)) {
619 // TODO Check if this is necessary, maybe the last line is enough
620 $arrayKeys = range(0,count($row));
621 array_fill_keys($arrayKeys, $row);
622 $rows[] = $row;
623 }
624 }
625 return $rows;
626 }
627
628 /**
629 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
630 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
631 *
632 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
633 * @param array $row The row array (as reference)
634 * @param string $languageUid The language id
635 * @param string $workspaceUidUid The workspace id
636 * @return void
637 */
638 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
639 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
640 if (TYPO3_MODE == 'FE') {
641 if (is_object($GLOBALS['TSFE'])) {
642 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
643 if ($languageUid === NULL) {
644 $languageUid = $GLOBALS['TSFE']->sys_language_content;
645 }
646 } else {
647 require_once(PATH_t3lib . 'class.t3lib_page.php');
648 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
649 if ($languageUid === NULL) {
650 $languageUid = intval(t3lib_div::_GP('L'));
651 }
652 }
653 if ($workspaceUid !== NULL) {
654 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
655 }
656 } else {
657 require_once(PATH_t3lib . 'class.t3lib_page.php');
658 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
659 if ($workspaceUid === NULL) {
660 $workspaceUid = $GLOBALS['BE_USER']->workspace;
661 }
662 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
663 }
664 }
665
666 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
667 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
668 // TODO Skip if empty languageoverlay (languagevisibility)
669 return $row;
670 }
671
672 /**
673 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
674 *
675 * @return void
676 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
677 */
678 protected function checkSqlErrors() {
679 $error = $this->databaseHandle->sql_error();
680 if ($error !== '') {
681 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
682 }
683 }
684
685 /**
686 * Clear the TYPO3 page cache for the given record.
687 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
688 *
689 * @param $tableName Table name of the record
690 * @param $uid UID of the record
691 * @return void
692 */
693 protected function clearPageCache($tableName, $uid) {
694 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
695 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
696 } else {
697 // if disabled, return
698 return;
699 }
700
701 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
702
703 $pageIdsToClear = array();
704 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
705 $storagePage = $row['pid'];
706 $pageIdsToClear[] = $storagePage;
707 }
708 if (!$storagePage) {
709 return;
710 }
711
712 $pageTSConfig = t3lib_BEfunc::getPagesTSconfig($storagePage);
713 if (isset($pageTSConfig['TCEMAIN.']['clearCacheCmd'])) {
714 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($pageTSConfig['TCEMAIN.']['clearCacheCmd']),1);
715 $clearCacheCommands = array_unique($clearCacheCommands);
716 foreach ($clearCacheCommands as $clearCacheCommand) {
717 if (t3lib_div::testInt($clearCacheCommand)) {
718 $pageIdsToClear[] = $clearCacheCommand;
719 }
720 }
721 }
722
723 Tx_Extbase_Utility_Cache::clearPageCache($pageIdsToClear);
724 }
725 }
726
727 ?>