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