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