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