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