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