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