Extbase:
[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 /**
38 * The TYPO3 database object
39 *
40 * @var t3lib_db
41 */
42 protected $databaseHandle;
43
44 /**
45 * The TYPO3 page select object. Used for language and workspace overlay
46 *
47 * @var t3lib_pageSelect
48 */
49 protected $pageSelectObject;
50
51 /**
52 * TRUE if the framework should add the "enable fields" (e.g. checking for hidden or deleted records)
53 *
54 * @var boolean
55 */
56 protected $useEnableFields = TRUE;
57
58 /**
59 * TRUE if automatic cache clearing in TCEMAIN should be done on insert/update/delete, FALSE otherwise.
60 *
61 * @var boolean
62 */
63 protected $automaticCacheClearing = FALSE;
64
65 /**
66 * Constructs this Storage Backend instance
67 *
68 * @param t3lib_db $databaseHandle The database handle
69 */
70 public function __construct($databaseHandle) {
71 $this->databaseHandle = $databaseHandle;
72 }
73
74 /**
75 * Set the automatic cache clearing flag.
76 * If TRUE, then inserted/updated/deleted records trigger a TCEMAIN cache clearing.
77 *
78 * @param $automaticCacheClearing boolean if TRUE, enables automatic cache clearing
79 * @return void
80 * @internal
81 */
82 public function setAutomaticCacheClearing($automaticCacheClearing) {
83 $this->automaticCacheClearing = (boolean)$automaticCacheClearing;
84 }
85
86 /**
87 * Adds a row to the storage
88 *
89 * @param string $tableName The database table name
90 * @param array $row The row to be inserted
91 * @return int The uid of the inserted row
92 */
93 public function addRow($tableName, array $row) {
94 $fields = array();
95 $values = array();
96 $parameters = array();
97 unset($row['uid']); // TODO Check if the offset exists
98 foreach ($row as $columnName => $value) {
99 $fields[] = $columnName;
100 $values[] = '?';
101 $parameters[] = $value;
102 }
103
104 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
105 $this->replacePlaceholders($sqlString, $parameters);
106
107 $this->databaseHandle->sql_query($sqlString);
108 $uid = $this->databaseHandle->sql_insert_id();
109 $this->clearPageCache($tableName, $uid);
110 return $uid;
111 }
112
113 /**
114 * Updates a row in the storage
115 *
116 * @param string $tableName The database table name
117 * @param array $row The row to be updated
118 * @return void
119 */
120 public function updateRow($tableName, array $row) {
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->clearPageCache($tableName, $uid);
137 return $returnValue;
138 }
139
140 /**
141 * Deletes a row in the storage
142 *
143 * @param string $tableName The database table name
144 * @param array $uid The uid of the row to be deleted
145 * @return void
146 */
147 public function removeRow($tableName, $uid) {
148 $sqlString = 'DELETE FROM ' . $tableName . ' WHERE uid=?';
149 $this->replacePlaceholders($sqlString, array((int)$uid));
150 $this->clearPageCache($tableName, $uid);
151 $returnValue = $this->databaseHandle->sql_query($sqlString);
152 return $returnValue;
153 }
154
155 /**
156 * Returns an array with tuples matching the query.
157 *
158 * @param Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query
159 * @return array The matching tuples
160 */
161 public function getRows(Tx_Extbase_Persistence_QOM_QueryObjectModelInterface $query) {
162 $sql = array();
163 $sql['tables'] = array();
164 $sql['fields'] = array();
165 $sql['where'] = array();
166 $sql['enableFields'] = array();
167 $sql['orderings'] = array();
168 $parameters = array();
169 $tuples = array();
170
171 $this->parseSource($query, $sql, $parameters);
172 $sqlString = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
173
174 $this->parseConstraint($query->getConstraint(), $sql, $parameters, $query->getBoundVariableValues());
175 if (!empty($sql['where'])) {
176 $sqlString .= ' WHERE ' . implode('', $sql['where']);
177 if (!empty($sql['enableFields'])) {
178 $sqlString .= ' AND ' . implode(' AND ', $sql['enableFields']);
179 }
180 } elseif (!empty($sql['enableFields'])) {
181 $sqlString .= ' WHERE ' . implode(' AND ', $sql['enableFields']);
182 }
183
184 $this->parseOrderings($query->getOrderings(), $sql, $parameters, $query->getBoundVariableValues());
185 if (!empty($sql['orderings'])) {
186 $sqlString .= ' ORDER BY ' . implode(', ', $sql['orderings']);
187 }
188
189 $this->replacePlaceholders($sqlString, $parameters);
190
191 $result = $this->databaseHandle->sql_query($sqlString);
192 if ($result) {
193 // TODO Check for selector name
194 $tuples = $this->getRowsFromResult($query->getSelectorName(), $result);
195 }
196
197 return $tuples;
198 }
199
200 /**
201 * Checks if a Value Object equal to the given Object exists in the data base
202 *
203 * @param array $properties The properties of the Value Object
204 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
205 * @return array The matching tuples
206 */
207 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap $dataMap) {
208 $fields = array();
209 $parameters = array();
210 foreach ($properties as $propertyName => $propertyValue) {
211 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid')) {
212 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
213 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
214 }
215 }
216
217 $sqlString = 'SELECT * FROM ' . $dataMap->getTableName() . ' WHERE ' . implode('', $fields);
218 $this->replacePlaceholders($sqlString, $parameters);
219 $res = $this->databaseHandle->sql_query($sqlString);
220 $row = $this->databaseHandle->sql_fetch_assoc($res);
221 if ($row !== FALSE) {
222 return $row['uid'];
223 } else {
224 return FALSE;
225 }
226 }
227
228 /**
229 * Transforms a Query Source into SQL and parameter arrays
230 *
231 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
232 * @param array &$sql
233 * @param array &$parameters
234 * @return void
235 */
236 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModel $query, array &$sql, array &$parameters) {
237 $source = $query->getSource();
238 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
239 $selectorName = $source->getSelectorName();
240 $sql['fields'][] = $selectorName . '.*';
241 $sql['tables'][] = $selectorName;
242 // TODO Should we make the usage of enableFields configurable? And how? Because the Query object and even the QOM should be abstracted from the storage backend.
243 if ($this->useEnableFields === TRUE) {
244 $this->addEnableFieldsStatement($selectorName, $sql);
245 }
246 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
247 $this->parseJoin($source, $sql, $parameters);
248 }
249 }
250
251 /**
252 * Transforms a Join into SQL and parameter arrays
253 *
254 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join
255 * @param array &$sql
256 * @param array &$parameters
257 * @return void
258 */
259 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql, array &$parameters) {
260 $leftSelectorName = $join->getLeft()->getSelectorName();
261 $rightSelectorName = $join->getRight()->getSelectorName();
262
263 $sql['fields'][] = $leftSelectorName . '.*';
264 $sql['fields'][] = $rightSelectorName . '.*';
265
266 // TODO Implement support for different join types and nested joins
267 $sql['tables'][] = $leftSelectorName . ' LEFT JOIN ' . $rightSelectorName;
268
269 $joinCondition = $join->getJoinCondition();
270 // TODO Check the parsing of the join
271 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
272 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $joinCondition->getProperty1Name() . ' = ' . $joinCondition->getSelector2Name() . '.' . $joinCondition->getProperty2Name();
273 }
274 // TODO Implement childtableWhere
275
276 $this->addEnableFieldsStatement($leftSelectorName, $sql);
277 $this->addEnableFieldsStatement($rightSelectorName, $sql);
278 }
279
280 /**
281 * Transforms a constraint into SQL and parameter arrays
282 *
283 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint
284 * @param array &$sql
285 * @param array &$parameters
286 * @param array $boundVariableValues
287 * @return void
288 */
289 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
290 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
291 $sql['where'][] = '(';
292 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
293 $sql['where'][] = ' AND ';
294 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
295 $sql['where'][] = ')';
296 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
297 $sql['where'][] = '(';
298 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
299 $sql['where'][] = ' OR ';
300 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
301 $sql['where'][] = ')';
302 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
303 $sql['where'][] = '(NOT ';
304 $this->parseConstraint($constraint->getConstraint(), $sql, $parameters, $boundVariableValues);
305 $sql['where'][] = ')';
306 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
307 $this->parseComparison($constraint, $sql, $parameters, $boundVariableValues);
308 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface) {
309 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
310 }
311 }
312
313 /**
314 * Parse a Comparison into SQL and parameter arrays.
315 *
316 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
317 * @param array &$sql SQL query parts to add to
318 * @param array &$parameters Parameters to bind to the SQL
319 * @param array $boundVariableValues The bound variables in the query and their values
320 * @return void
321 */
322 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, array &$sql, array &$parameters, array $boundVariableValues) {
323 $this->parseDynamicOperand($comparison->getOperand1(), $comparison->getOperator(), $sql, $parameters);
324
325 if ($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface) {
326 $parameters[] = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
327 }
328 }
329
330 /**
331 * Parse a DynamicOperand into SQL and parameter arrays.
332 *
333 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
334 * @param string $operator One of the JCR_OPERATOR_* constants
335 * @param array $boundVariableValues
336 * @param array &$parameters
337 * @param string $valueFunction an aoptional SQL function to apply to the operand value
338 * @return void
339 */
340 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, array &$sql, array &$parameters, $valueFunction = NULL) {
341 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
342 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'LOWER');
343 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
344 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'UPPER');
345 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
346 $selectorName = $operand->getSelectorName();
347 $operator = $this->resolveOperator($operator);
348
349 $constraintSQL = '(';
350 if ($valueFunction === NULL) {
351 $constraintSQL .= (!empty($selectorName) ? $selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
352 } else {
353 $constraintSQL .= $valueFunction . '(' . (!empty($selectorName) ? $selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
354 }
355 $constraintSQL .= ') ';
356
357 $sql['where'][] = $constraintSQL;
358 }
359 }
360
361 /**
362 * Returns the SQL operator for the given JCR operator type.
363 *
364 * @param string $operator One of the JCR_OPERATOR_* constants
365 * @return string an SQL operator
366 */
367 protected function resolveOperator($operator) {
368 switch ($operator) {
369 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO:
370 $operator = '=';
371 break;
372 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO:
373 $operator = '!=';
374 break;
375 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN:
376 $operator = '<';
377 break;
378 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO:
379 $operator = '<=';
380 break;
381 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN:
382 $operator = '>';
383 break;
384 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO:
385 $operator = '>=';
386 break;
387 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LIKE:
388 $operator = 'LIKE';
389 break;
390 default:
391 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
392 }
393
394 return $operator;
395 }
396
397 /**
398 * Replace query placeholders in a query part by the given
399 * parameters.
400 *
401 * @param string $queryPart The query part with placeholders
402 * @param array $parameters The parameters
403 * @return string The query part with replaced placeholders
404 */
405 protected function replacePlaceholders(&$sqlString, array $parameters) {
406 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);
407 foreach ($parameters as $parameter) {
408 $markPosition = strpos($sqlString, '?');
409 if ($markPosition !== FALSE) {
410 $sqlString = substr($sqlString, 0, $markPosition) . '"' . $parameter . '"' . substr($sqlString, $markPosition + 1);
411 }
412 }
413 }
414
415 /**
416 * Builds the enable fields statement
417 *
418 * @param string $selectorName The selector name (= database table name)
419 * @param array &$sql The query parts
420 * @return void
421 */
422 protected function addEnableFieldsStatement($selectorName, array &$sql) {
423 // TODO We have to call the appropriate API method if we are in TYPO3BE mode
424 if (is_array($GLOBALS['TCA'][$selectorName]['ctrl'])) {
425 $statement = substr($GLOBALS['TSFE']->sys_page->enableFields($selectorName), 4);
426 if(!empty($statement)) {
427 $sql['enableFields'][] = $statement;
428 }
429 }
430 }
431
432 /**
433 * Transforms orderings into SQL
434 *
435 * @param array $orderings
436 * @param array &$sql
437 * @param array &$parameters
438 * @param array $boundVariableValues
439 * @return void
440 */
441 protected function parseOrderings(array $orderings = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
442 if (is_array($orderings)) {
443 foreach ($orderings as $propertyName => $ordering) {
444 // TODO Implement
445 }
446 }
447 }
448
449 /**
450 * Transforms a Resource from a database query to an array of rows. Performs the language and
451 * workspace overlay before.
452 *
453 * @return array The result as an array of rows (tuples)
454 */
455 protected function getRowsFromResult($tableName, $res) {
456 $rows = array();
457 while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
458 $row = $this->doLanguageAndWorkspaceOverlay($tableName, $row);
459 if (is_array($row)) {
460 // TODO Check if this is necessary, maybe the last line is enough
461 $arrayKeys = range(0,count($row));
462 array_fill_keys($arrayKeys, $row);
463 $rows[] = $row;
464 }
465 }
466 return $rows;
467 }
468
469 /**
470 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
471 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
472 *
473 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
474 * @param array $row The row array (as reference)
475 * @param string $languageUid The language id
476 * @param string $workspaceUidUid The workspace id
477 * @return void
478 */
479 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
480 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
481 if (TYPO3_MODE == 'FE') {
482 if (is_object($GLOBALS['TSFE'])) {
483 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
484 if ($languageUid === NULL) {
485 $languageUid = $GLOBALS['TSFE']->sys_language_content;
486 }
487 } else {
488 require_once(PATH_t3lib . 'class.t3lib_page.php');
489 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
490 if ($languageUid === NULL) {
491 $languageUid = intval(t3lib_div::_GP('L'));
492 }
493 }
494 if ($workspaceUid !== NULL) {
495 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
496 }
497 } else {
498 require_once(PATH_t3lib . 'class.t3lib_page.php');
499 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
500 //$this->pageSelectObject->versioningPreview = TRUE;
501 if ($workspaceUid === NULL) {
502 $workspaceUid = $GLOBALS['BE_USER']->workspace;
503 }
504 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
505 }
506 }
507
508 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
509 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
510 // TODO Skip if empty languageoverlay (languagevisibility)
511 return $row;
512 }
513
514 /**
515 * Clear the TYPO3 page cache for the given record.
516 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
517 *
518 * @param $tableName Table name of the record
519 * @param $uid UID of the record
520 * @return void
521 */
522 protected function clearPageCache($tableName, $uid) {
523 if ($this->automaticCacheClearing !== TRUE) return;
524
525 $pageCache = $GLOBALS['typo3CacheManager']->getCache('cache_pages');
526 $pageSectionCache = $GLOBALS['typo3CacheManager']->getCache('cache_pagesection');
527
528 $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $tableName, 'uid='.intval($uid));
529
530 $pageIdsToClear = array();
531 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
532 $storagePage = $row['pid'];
533 $pageIdsToClear[] = $storagePage;
534 }
535 if (!$storagePage) {
536 return;
537 }
538
539 $pageTSConfig = t3lib_BEfunc::getPagesTSconfig($storagePage);
540
541 if ($pageTSConfig['clearCacheCmd']) {
542 $clearCacheCommands = t3lib_div::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
543 $clearCacheCommands = array_unique($clearCacheCommands);
544 foreach ($clearCacheCommands as $clearCacheCommand) {
545 if (t3lib_div::testInt($clearCacheCommand)) {
546 $pageIdsToClear[] = $clearCacheCommand;
547 }
548 }
549 }
550
551 foreach ($pageIdsToClear as $pageIdToClear) {
552 $pageCache->flushByTag('pageId_' . $pageIdToClear);
553 $pageSectionCache->flushByTag('pageId_' . $pageIdToClear);
554 }
555 }
556 }
557
558 ?>