[+BUGFIX] Extbase (Persistence): Replaced $dateTime->getTimestamp() with $dateTime...
[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 * A first-level TypoScript configuration cache
61 *
62 * @var array
63 */
64 protected $pageTSConfigCache = array();
65
66 /**
67 * Caches information about tables (esp. the existing column names)
68 *
69 * @var array
70 */
71 protected $tableInformationCache = array();
72
73 /**
74 * Constructs this Storage Backend instance
75 *
76 * @param t3lib_db $databaseHandle The database handle
77 */
78 public function __construct($databaseHandle) {
79 $this->databaseHandle = $databaseHandle;
80 }
81
82 /**
83 * Injects the DataMapper to map nodes to objects
84 *
85 * @param Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper
86 * @return void
87 */
88 public function injectDataMapper(Tx_Extbase_Persistence_Mapper_DataMapper $dataMapper) {
89 $this->dataMapper = $dataMapper;
90 }
91
92 /**
93 * Adds a row to the storage
94 *
95 * @param string $tableName The database table name
96 * @param array $row The row to be inserted
97 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
98 * @return int The uid of the inserted row
99 */
100 public function addRow($tableName, array $row, $isRelation = FALSE) {
101 $fields = array();
102 $values = array();
103 $parameters = array();
104 if (isset($row['uid'])) {
105 unset($row['uid']);
106 }
107 foreach ($row as $columnName => $value) {
108 $fields[] = $columnName;
109 $values[] = '?';
110 $parameters[] = $value;
111 }
112
113 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
114 $this->replacePlaceholders($sqlString, $parameters);
115 // debug($sqlString,-2);
116 $this->databaseHandle->sql_query($sqlString);
117 $this->checkSqlErrors();
118 $uid = $this->databaseHandle->sql_insert_id();
119 if (!$isRelation) {
120 $this->clearPageCache($tableName, $uid);
121 }
122 return (int)$uid;
123 }
124
125 /**
126 * Updates a row in the storage
127 *
128 * @param string $tableName The database table name
129 * @param array $row The row to be updated
130 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
131 * @return void
132 */
133 public function updateRow($tableName, array $row, $isRelation = FALSE) {
134 if (!isset($row['uid'])) throw new InvalidArgumentException('The given row must contain a value for "uid".');
135 $uid = (int)$row['uid'];
136 unset($row['uid']);
137 $fields = array();
138 $parameters = array();
139 foreach ($row as $columnName => $value) {
140 $fields[] = $columnName . '=?';
141 $parameters[] = $value;
142 }
143 $parameters[] = $uid;
144
145 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
146 $this->replacePlaceholders($sqlString, $parameters);
147 // debug($sqlString,-2);
148 $returnValue = $this->databaseHandle->sql_query($sqlString);
149 $this->checkSqlErrors();
150 if (!$isRelation) {
151 $this->clearPageCache($tableName, $uid);
152 }
153 return $returnValue;
154 }
155
156 /**
157 * Deletes a row in the storage
158 *
159 * @param string $tableName The database table name
160 * @param array $identifier An array of identifier array('fieldname' => value). This array will be transformed to a WHERE clause
161 * @param boolean $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
162 * @return void
163 */
164 public function removeRow($tableName, array $identifier, $isRelation = FALSE) {
165 $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
166 $this->replacePlaceholders($statement, $identifier);
167 if (!$isRelation) {
168 $this->clearPageCache($tableName, $uid, $isRelation);
169 }
170 $returnValue = $this->databaseHandle->sql_query($statement);
171 $this->checkSqlErrors();
172 return $returnValue;
173 }
174
175 /**
176 * Fetches row data from the database
177 *
178 * @param string $identifier The Identifier of the row to fetch
179 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
180 * @return array|FALSE
181 */
182 public function getRowByIdentifier($tableName, array $identifier) {
183 $statement = 'SELECT * FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
184 $this->replacePlaceholders($statement, $identifier);
185 // debug($statement,-2);
186 $res = $this->databaseHandle->sql_query($statement);
187 $this->checkSqlErrors();
188 $row = $this->databaseHandle->sql_fetch_assoc($res);
189 if ($row !== FALSE) {
190 return $row;
191 } else {
192 return FALSE;
193 }
194 }
195
196 protected function parseIdentifier(array $identifier) {
197 $fieldNames = array_keys($identifier);
198 $suffixedFieldNames = array();
199 foreach ($fieldNames as $fieldName) {
200 $suffixedFieldNames[] = $fieldName . '=?';
201 }
202 return implode(' AND ', $suffixedFieldNames);
203 }
204
205 /**
206 * Returns the object data matching the $query.
207 *
208 * @param Tx_Extbase_Persistence_QueryInterface $query
209 * @return array
210 * @author Karsten Dambekalns <karsten@typo3.org>
211 */
212 public function getObjectDataByQuery(Tx_Extbase_Persistence_QueryInterface $query) {
213 $parameters = array();
214
215 $statement = $query->getStatement();
216 if($statement instanceof Tx_Extbase_Persistence_QOM_Statement) {
217 $sql = $statement->getStatement();
218 $parameters = $statement->getBoundVariables();
219 } else {
220 $parameters = array();
221 $statementParts = $this->parseQuery($query, $parameters);
222 $sql = $this->buildQuery($statementParts, $parameters);
223 }
224 $this->replacePlaceholders($sql, $parameters);
225 // debug($sql,-2);
226 $result = $this->databaseHandle->sql_query($sql);
227 $this->checkSqlErrors();
228 $rows = $this->getRowsFromResult($query->getSource(), $result);
229 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows);
230
231 // $objectData = $this->processObjectRecords($statementHandle);
232 return $rows;
233 }
234
235 /**
236 * Returns the number of tuples matching the query.
237 *
238 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
239 * @return int The number of matching tuples
240 */
241 public function getObjectCountByQuery(Tx_Extbase_Persistence_QueryInterface $query) {
242 $constraint = $query->getConstraint();
243 if($constraint instanceof Tx_Extbase_Persistence_QOM_StatementInterface) throw new Tx_Extbase_Persistence_Storage_Exception_BadConstraint('Could not execute count on queries with a constraint of type Tx_Extbase_Persistence_QOM_StatementInterface', 1256661045);
244 $parameters = array();
245 $statementParts = $this->parseQuery($query, $parameters);
246 $statementParts['fields'] = array('COUNT(*)');
247 $statement = $this->buildQuery($statementParts, $parameters);
248 $this->replacePlaceholders($statement, $parameters);
249 // debug($sql,-2);
250 $result = $this->databaseHandle->sql_query($statement);
251 $this->checkSqlErrors();
252 $rows = $this->getRowsFromResult($query->getSource(), $result);
253 return current(current($rows));
254 }
255
256 /**
257 * Parses the query and returns the SQL statement parts.
258 *
259 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
260 * @return array The SQL statement parts
261 */
262 public function parseQuery(Tx_Extbase_Persistence_Query $query, array &$parameters) {
263 $sql = array();
264 $sql['tables'] = array();
265 $sql['fields'] = array();
266 $sql['where'] = array();
267 $sql['additionalWhereClause'] = array();
268 $sql['orderings'] = array();
269 $sql['limit'] = array();
270
271 $source = $query->getSource();
272
273 $this->parseSource($query, $source, $sql, $parameters);
274 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters);
275 $this->parseOrderings($query->getOrderings(), $source, $sql);
276 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
277
278 return $sql;
279 }
280
281 /**
282 * Returns the statement, ready to be executed.
283 *
284 * @param array $sql The SQL statement parts
285 * @return string The SQL statement
286 */
287 public function buildQuery(array $sql) {
288 $statement = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
289 if (!empty($sql['where'])) {
290 $statement .= ' WHERE ' . implode('', $sql['where']);
291 if (!empty($sql['additionalWhereClause'])) {
292 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
293 }
294 } elseif (!empty($sql['additionalWhereClause'])) {
295 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
296 }
297 if (!empty($sql['orderings'])) {
298 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
299 }
300 if (!empty($sql['limit'])) {
301 $statement .= ' LIMIT ' . $sql['limit'];
302 }
303 return $statement;
304 }
305
306 /**
307 * Checks if a Value Object equal to the given Object exists in the data base
308 *
309 * @param Tx_Extbase_DomainObject_AbstractValueObject $object The Value Object
310 * @return array The matching uid
311 */
312 public function getUidOfAlreadyPersistedValueObject(Tx_Extbase_DomainObject_AbstractValueObject $object) {
313 $fields = array();
314 $parameters = array();
315 $dataMap = $this->dataMapper->getDataMap(get_class($object));
316 $properties = $object->_getProperties();
317 foreach ($properties as $propertyName => $propertyValue) {
318 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
319 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid') && ($propertyName !== 'pid') && ($propertyName !== 'isClone')) {
320 if ($propertyValue === NULL) {
321 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
322 } else {
323 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
324 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
325 }
326 }
327 }
328 $sql = array();
329 $sql['additionalWhereClause'] = array();
330
331 $tableName = $dataMap->getTableName();
332 $this->addEnableFieldsStatement($tableName, $sql);
333
334 $statement = 'SELECT * FROM ' . $tableName;
335 $statement .= ' WHERE ' . implode(' AND ', $fields);
336 if (!empty($sql['additionalWhereClause'])) {
337 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
338 }
339 $this->replacePlaceholders($statement, $parameters);
340 // debug($statement,-2);
341 $res = $this->databaseHandle->sql_query($statement);
342 $this->checkSqlErrors();
343 $row = $this->databaseHandle->sql_fetch_assoc($res);
344 if ($row !== FALSE) {
345 return (int)$row['uid'];
346 } else {
347 return FALSE;
348 }
349 }
350
351 /**
352 * Transforms a Query Source into SQL and parameter arrays
353 *
354 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
355 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
356 * @param array &$sql
357 * @param array &$parameters
358 * @return void
359 */
360 protected function parseSource(Tx_Extbase_Persistence_Query $query, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
361 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
362 $tableName = $source->getSelectorName();
363 $sql['fields'][] = $tableName . '.*';
364 $sql['tables'][] = $tableName;
365 $querySettings = $query->getQuerySettings();
366 if ($querySettings instanceof Tx_Extbase_Persistence_QuerySettingsInterface) {
367 if ($querySettings->getRespectEnableFields()) {
368 $this->addEnableFieldsStatement($tableName, $sql);
369 }
370 if ($querySettings->getRespectSysLanguage()) {
371 $this->addSysLanguageStatement($tableName, $sql);
372 }
373 if ($querySettings->getRespectStoragePage()) {
374 $this->addPageIdStatement($tableName, $sql);
375 }
376 }
377 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
378 $this->parseJoin($query, $source, $sql);
379 }
380 }
381
382 /**
383 * Transforms a Join into SQL and parameter arrays
384 *
385 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query The Query Object Model
386 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join The join
387 * @param array &$sql The query parts
388 * @return void
389 */
390 protected function parseJoin(Tx_Extbase_Persistence_QueryInterface $query, Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql) {
391 $leftSource = $join->getLeft();
392 $leftTableName = $leftSource->getSelectorName();
393 $rightSource = $join->getRight();
394 $rightTableName = $rightSource->getSelectorName();
395
396 $sql['fields'][] = $leftTableName . '.*';
397 $sql['fields'][] = $rightTableName . '.*';
398
399 // TODO Implement support for different join types and nested joins
400 $sql['tables'][] = $leftTableName . ' LEFT JOIN ' . $rightTableName;
401
402 $joinCondition = $join->getJoinCondition();
403 // TODO Check the parsing of the join
404 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
405 // TODO Discuss, if we should use $leftSource instead of $selector1Name
406 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftSource->getNodeTypeName());
407 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightSource->getNodeTypeName());
408 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
409 }
410 // TODO Implement childtableWhere
411
412 $querySettings = $query->getQuerySettings();
413 if ($querySettings instanceof Tx_Extbase_Persistence_Typo3QuerySettingsInterface) {
414 if ($querySettings->getRespectEnableFields()) {
415 $this->addEnableFieldsStatement($leftTableName, $sql);
416 $this->addEnableFieldsStatement($rightTableName, $sql);
417 }
418 if ($querySettings->getRespectSysLanguage()) {
419 $this->addSysLanguageStatement($leftTableName, $sql);
420 $this->addSysLanguageStatement($rightTableName, $sql);
421 }
422 if ($querySettings->getRespectStoragePage()) {
423 $this->addPageIdStatement($leftTableName, $sql);
424 $this->addPageIdStatement($rightTableName, $sql);
425 }
426 }
427 }
428
429 /**
430 * Transforms a constraint into SQL and parameter arrays
431 *
432 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint The constraint
433 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
434 * @param array &$sql The query parts
435 * @param array &$parameters The parameters that will replace the markers
436 * @param array $boundVariableValues The bound variables in the query (key) and their values (value)
437 * @return void
438 */
439 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
440 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
441 $sql['where'][] = '(';
442 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
443 $sql['where'][] = ' AND ';
444 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
445 $sql['where'][] = ')';
446 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
447 $sql['where'][] = '(';
448 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
449 $sql['where'][] = ' OR ';
450 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
451 $sql['where'][] = ')';
452 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
453 $sql['where'][] = 'NOT (';
454 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
455 $sql['where'][] = ')';
456 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
457 $this->parseComparison($constraint, $source, $sql, $parameters);
458 }
459 }
460
461 /**
462 * Parse a Comparison into SQL and parameter arrays.
463 *
464 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
465 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
466 * @param array &$sql SQL query parts to add to
467 * @param array &$parameters Parameters to bind to the SQL
468 * @param array $boundVariableValues The bound variables in the query and their values
469 * @return void
470 */
471 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters) {
472 $operand1 = $comparison->getOperand1();
473 $operator = $comparison->getOperator();
474 $operand2 = $comparison->getOperand2();
475 if (($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO) && (is_array($operand2) || ($operand2 instanceof ArrayAccess) || ($operand2 instanceof Traversable))) {
476 // FIXME this else branch enables equals() to behave like in(). This behavior is deprecated and will be removed in future. Use in() instead.
477 $operator = Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN;
478 }
479
480 if ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN) {
481 $items = array();
482 $hasValue = FALSE;
483 foreach ($operand2 as $value) {
484 $value = $this->getPlainValue($value);
485 if ($value !== NULL) {
486 $items[] = $value;
487 $hasValue = TRUE;
488 }
489 }
490 if ($hasValue === FALSE) {
491 $sql['where'][] = '1<>1';
492 } else {
493 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
494 $items = array();
495 foreach ($operand2 as $value) {
496 $items[] = $this->getPlainValue($value);
497 }
498 $parameters[] = $items;
499 }
500 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_CONTAINS) {
501 if ($operand2 === NULL) {
502 $sql['where'][] = '1<>1';
503 } else {
504 $dataMap = $this->dataMapper->getDataMap($source->getNodeTypeName());
505 $columnMap = $dataMap->getColumnMap($operand1->getPropertyName());
506 $typeOfRelation = $columnMap->getTypeOfRelation();
507 if ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
508 $relationTableName = $columnMap->getRelationTableName();
509 $sql['where'][] = 'uid IN (SELECT uid_local FROM ' . $relationTableName . ' WHERE uid_foreign=' . $this->getPlainValue($operand2) . ')';
510 } elseif ($typeOfRelation === Tx_Extbase_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
511 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
512 if (isset($parentKeyFieldName)) {
513 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand1->getPropertyName(), $source->getNodeTypeName());
514 $childTableName = $columnMap->getChildTableName();
515 $sql['where'][] = 'uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
516 } else {
517 $tableName = $operand1->getSelectorName();
518 $statement = '(' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . ',%\'';
519 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'%,' . $this->getPlainValue($operand2) . '\'';
520 $statement .= ' OR ' . $tableName . '.' . $operand1->getPropertyName() . ' LIKE \'' . $this->getPlainValue($operand2) . ',%\')';
521 $sql['where'][] = $statement;
522 }
523 } else {
524 throw new Tx_Extbase_Persistence_Exception_RepositoryException('Unsupported relation for contains().', 1267832524);
525 }
526 }
527 } else {
528 if ($operand2 === NULL) {
529 if ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO) {
530 $operator = self::OPERATOR_EQUAL_TO_NULL;
531 } elseif ($operator === Tx_Extbase_Persistence_QueryInterface::OPERATOR_NOT_EQUAL_TO) {
532 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
533 }
534 }
535 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
536 $parameters[] = $this->getPlainValue($operand2);
537 }
538 }
539
540 /**
541 * Returns a plain value, i.e. objects are flattened out if possible.
542 *
543 * @param mixed $input
544 * @return mixed
545 */
546 protected function getPlainValue($input) {
547 if ($input instanceof DateTime) {
548 return $input->format('U');
549 } elseif ($input instanceof Tx_Extbase_DomainObject_DomainObjectInterface) {
550 return $input->getUid();
551 } elseif (is_bool($input)) {
552 return $input === TRUE ? 1 : 0;
553 } else {
554 return $input;
555 }
556 }
557
558 /**
559 * Parse a DynamicOperand into SQL and parameter arrays.
560 *
561 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
562 * @param string $operator One of the JCR_OPERATOR_* constants
563 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
564 * @param array &$sql The query parts
565 * @param array &$parameters The parameters that will replace the markers
566 * @param string $valueFunction an optional SQL function to apply to the operand value
567 * @return void
568 */
569 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL, $operand2 = NULL) {
570 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
571 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
572 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
573 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
574 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
575 $tableName = $operand->getSelectorName();
576 // FIXME Discuss the translation from propertyName to columnName
577 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
578 $className = $source->getNodeTypeName();
579 } else {
580 $className = '';
581 }
582 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
583 $operator = $this->resolveOperator($operator);
584 if ($valueFunction === NULL) {
585 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
586 } else {
587 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
588 }
589
590 $sql['where'][] = $constraintSQL;
591 }
592 }
593
594 /**
595 * Returns the SQL operator for the given JCR operator type.
596 *
597 * @param string $operator One of the JCR_OPERATOR_* constants
598 * @return string an SQL operator
599 */
600 protected function resolveOperator($operator) {
601 switch ($operator) {
602 case self::OPERATOR_EQUAL_TO_NULL:
603 $operator = 'IS';
604 break;
605 case self::OPERATOR_NOT_EQUAL_TO_NULL:
606 $operator = 'IS NOT';
607 break;
608 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_IN:
609 $operator = 'IN';
610 break;
611 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_EQUAL_TO:
612 $operator = '=';
613 break;
614 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_NOT_EQUAL_TO:
615 $operator = '!=';
616 break;
617 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LESS_THAN:
618 $operator = '<';
619 break;
620 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
621 $operator = '<=';
622 break;
623 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_GREATER_THAN:
624 $operator = '>';
625 break;
626 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
627 $operator = '>=';
628 break;
629 case Tx_Extbase_Persistence_QueryInterface::OPERATOR_LIKE:
630 $operator = 'LIKE';
631 break;
632 default:
633 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
634 }
635
636 return $operator;
637 }
638
639 /**
640 * Replace query placeholders in a query part by the given
641 * parameters.
642 *
643 * @param string $sqlString The query part with placeholders
644 * @param array $parameters The parameters
645 * @return string The query part with replaced placeholders
646 */
647 protected function replacePlaceholders(&$sqlString, array $parameters) {
648 // TODO profile this method again
649 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);
650 $offset = 0;
651 foreach ($parameters as $parameter) {
652 $markPosition = strpos($sqlString, '?', $offset);
653 if ($markPosition !== FALSE) {
654 if ($parameter === NULL) {
655 $parameter = 'NULL';
656 } elseif (is_array($parameter) || ($parameter instanceof ArrayAccess) || ($parameter instanceof Traversable)) {
657 $items = array();
658 foreach ($parameter as $item) {
659 $items[] = $this->databaseHandle->fullQuoteStr($item, 'foo');
660 }
661 $parameter = '(' . implode(',', $items) . ')';
662 } else {
663 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo'); // FIXME This may not work with DBAL; check this
664 }
665 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, $markPosition + 1);
666 }
667 $offset = $markPosition + strlen($parameter);
668 }
669 }
670
671 /**
672 * Builds the enable fields statement
673 *
674 * @param string $tableName The database table name
675 * @param array &$sql The query parts
676 * @return void
677 */
678 protected function addEnableFieldsStatement($tableName, array &$sql) {
679 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
680 if (TYPO3_MODE === 'FE') {
681 $statement = $GLOBALS['TSFE']->sys_page->enableFields($tableName);
682 } else { // TYPO3_MODE === 'BE'
683 $statement = t3lib_BEfunc::deleteClause($tableName);
684 $statement .= t3lib_BEfunc::BEenableFields($tableName);
685 }
686 if(!empty($statement)) {
687 $statement = substr($statement, 5);
688 $sql['additionalWhereClause'][] = $statement;
689 }
690 }
691 }
692
693 /**
694 * Builds the language field statement
695 *
696 * @param string $tableName The database table name
697 * @param array &$sql The query parts
698 * @return void
699 */
700 protected function addSysLanguageStatement($tableName, array &$sql) {
701 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
702 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== NULL) {
703 $sql['additionalWhereClause'][] = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (0,-1)';
704 }
705 }
706 }
707
708 /**
709 * Builds the page ID checking statement
710 *
711 * @param string $tableName The database table name
712 * @param array &$sql The query parts
713 * @return void
714 */
715 protected function addPageIdStatement($tableName, array &$sql) {
716 if (empty($this->tableInformationCache[$tableName]['columnNames'])) {
717 $this->tableInformationCache[$tableName]['columnNames'] = $this->databaseHandle->admin_get_fields($tableName);
718 }
719 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $this->tableInformationCache[$tableName]['columnNames'])) {
720 $extbaseFrameworkConfiguration = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
721 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', t3lib_div::intExplode(',', $extbaseFrameworkConfiguration['persistence']['storagePid'])) . ')';
722 }
723 }
724
725 /**
726 * Transforms orderings into SQL.
727 *
728 * @param array $orderings Ann array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
729 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source
730 * @param array &$sql The query parts
731 * @return void
732 */
733 protected function parseOrderings(array $orderings, Tx_Extbase_Persistence_QOM_SourceInterface $source, array &$sql) {
734 foreach ($orderings as $ordering) {
735 $operand = $ordering->getOperand();
736 $order = $ordering->getOrder();
737 if ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValue) {
738 switch ($order) {
739 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
740 $order = 'ASC';
741 break;
742 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
743 $order = 'DESC';
744 break;
745 default:
746 throw new Tx_Extbase_Persistence_Exception_UnsupportedOrder('Unsupported order encountered.', 1242816074);
747 }
748 $tableName = $operand->getSelectorName();
749 $className = '';
750 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
751 $className = $source->getNodeTypeName();
752 }
753 $columnName = $this->dataMapper->convertPropertyNameToColumnName($operand->getPropertyName(), $className);
754 if (strlen($tableName) > 0) {
755 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
756 } else {
757 $sql['orderings'][] = $columnName . ' ' . $order;
758 }
759 }
760 }
761 }
762
763 /**
764 * Transforms limit and offset into SQL
765 *
766 * @param int $limit
767 * @param int $offset
768 * @param array &$sql
769 * @return void
770 */
771 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
772 if ($limit !== NULL && $offset !== NULL) {
773 $sql['limit'] = $offset . ', ' . $limit;
774 } elseif ($limit !== NULL) {
775 $sql['limit'] = $limit;
776 }
777 }
778
779 /**
780 * Transforms a Resource from a database query to an array of rows.
781 *
782 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
783 * @param resource $result The result
784 * @return array The result as an array of rows (tuples)
785 */
786 protected function getRowsFromResult(Tx_Extbase_Persistence_QOM_SourceInterface $source, $result) {
787 $rows = array();
788 while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
789 if (is_array($row)) {
790 // TODO Check if this is necessary, maybe the last line is enough
791 $arrayKeys = range(0, count($row));
792 array_fill_keys($arrayKeys, $row);
793 $rows[] = $row;
794 }
795 }
796 return $rows;
797 }
798
799 /**
800 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
801 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
802 *
803 * @param Tx_Extbase_Persistence_QOM_SourceInterface $source The source (selector od join)
804 * @param array $row The row array (as reference)
805 * @param string $languageUid The language id
806 * @param string $workspaceUidUid The workspace id
807 * @return void
808 */
809 protected function doLanguageAndWorkspaceOverlay(Tx_Extbase_Persistence_QOM_SourceInterface $source, array $rows, $languageUid = NULL, $workspaceUid = NULL) {
810 $overlayedRows = array();
811 foreach ($rows as $row) {
812 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
813 if (TYPO3_MODE == 'FE') {
814 if (is_object($GLOBALS['TSFE'])) {
815 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
816 } else {
817 require_once(PATH_t3lib . 'class.t3lib_page.php');
818 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
819 }
820 } else {
821 require_once(PATH_t3lib . 'class.t3lib_page.php');
822 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
823 }
824 }
825 if (is_object($GLOBALS['TSFE'])) {
826 if ($languageUid === NULL) {
827 $languageUid = $GLOBALS['TSFE']->sys_language_uid;
828 }
829 if ($workspaceUid !== NULL) {
830 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
831 }
832 } else {
833 if ($languageUid === NULL) {
834 $languageUid = intval(t3lib_div::_GP('L'));
835 }
836 if ($workspaceUid === NULL) {
837 $workspaceUid = $GLOBALS['BE_USER']->workspace;
838 }
839 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
840 }
841 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
842 $tableName = $source->getSelectorName();
843 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
844 $tableName = $source->getLeft()->getSelectorName();
845 }
846 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
847 if(isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField']) && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== '') {
848 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1,0))) {
849 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid);
850 }
851 }
852 $overlayedRows[] = $row;
853 }
854 return $overlayedRows;
855 }
856
857 /**
858 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
859 *
860 * @return void
861 * @throws Tx_Extbase_Persistence_Storage_Exception_SqlError
862 */
863 protected function checkSqlErrors() {
864 $error = $this->databaseHandle->sql_error();
865 if ($error !== '') {
866 throw new Tx_Extbase_Persistence_Storage_Exception_SqlError($error, 1247602160);
867 }
868 }
869
870 /**
871 * Clear the TYPO3 page cache for the given record.
872 * If the record lies on a page, then we clear the cache of this page.
873 * If the record has no PID column, we clear the cache of the current page as best-effort.
874 *
875 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
876 *
877 * @param $tableName Table name of the record
878 * @param $uid UID of the record
879 * @return void
880 */
881 protected function clearPageCache($tableName, $uid) {
882 $extbaseSettings = Tx_Extbase_Dispatcher::getExtbaseFrameworkConfiguration();
883 if (isset($extbaseSettings['persistence']['enableAutomaticCacheClearing']) && $extbaseSettings['persistence']['enableAutomaticCacheClearing'] === '1') {
884 } else {
885 // if disabled, return
886 return;
887 }
888
889 $pageIdsToClear = array();
890 $storagePage = NULL;
891
892 $columns = $this->databaseHandle->admin_get_fields($tableName);
893 if (array_key_exists('pid', $columns)) {
894 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
895 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
896 $storagePage = $row['pid'];
897 $pageIdsToClear[] = $storagePage;
898 }
899 } elseif (isset($GLOBALS['TSFE'])) {
900 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
901 $storagePage = $GLOBALS['TSFE']->id;
902 $pageIdsToClear[] = $storagePage;
903 }
904
905 if ($storagePage === NULL) {
906 return;
907 }
908 if (!isset($this->pageTSConfigCache[$storagePage])) {
909 $this->pageTSConfigCache[$storagePage] = t3lib_BEfunc::getPagesTSconfig($storagePage);
910 }
911 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
912 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']),1);
913 $clearCacheCommands = array_unique($clearCacheCommands);
914 foreach ($clearCacheCommands as $clearCacheCommand) {
915 if (t3lib_div::testInt($clearCacheCommand)) {
916 $pageIdsToClear[] = $clearCacheCommand;
917 }
918 }
919 }
920
921 // TODO check if we can hand this over to the Dispatcher to clear the page only once, this will save around 10% time while inserting and updating
922 Tx_Extbase_Utility_Cache::clearPageCache($pageIdsToClear);
923 }
924 }
925
926 ?>