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 * @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
134 $this->parseSource($query, $sql, $parameters);
135 $this->parseConstraint($query->getConstraint(), $sql, $parameters, $query->getBoundVariableValues());
136 $this->parseOrderings($query->getOrderings(), $sql, $parameters, $query->getBoundVariableValues());
137
138 $sqlString = 'SELECT ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']);
139 if (!empty($sql['where'])) {
140 $sqlString .= ' WHERE ' . implode(' AND ', $sql['where']);
141 }
142 if (!empty($sql['orderings'])) {
143 $sqlString .= ' ORDER BY ' . implode(', ', $sql['orderings']);
144 }
145 $this->replacePlaceholders($sqlString, $parameters);
146 $result = $this->databaseHandle->sql_query($sqlString);
147 if ($result) {
148 $tuples = $this->getRowsFromResult($query->getSelectorName(), $result);
149 }
150 return $tuples;
151 }
152
153 /**
154 * Checks if a Value Object equal to the given Object exists in the data base
155 *
156 * @param array $properties The properties of the Value Object
157 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap The Data Map
158 * @return array The matching tuples
159 */
160 public function hasValueObject(array $properties, Tx_Extbase_Persistence_Mapper_DataMap $dataMap) {
161 $fields = array();
162 $parameters = array();
163 foreach ($properties as $propertyName => $propertyValue) {
164 if ($dataMap->isPersistableProperty($propertyName) && ($propertyName !== 'uid')) {
165 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
166 $parameters[] = $dataMap->convertPropertyValueToFieldValue($propertyValue);
167 }
168 }
169
170 $sqlString = 'SELECT * FROM ' . $dataMap->getTableName() . ' WHERE ' . implode(' AND ', $fields);
171 $this->replacePlaceholders($sqlString, $parameters);
172 $res = $this->databaseHandle->sql_query($sqlString);
173 $row = $this->databaseHandle->sql_fetch_assoc($res);
174 if ($row !== FALSE) {
175 return $row['uid'];
176 } else {
177 return FALSE;
178 }
179 }
180
181 /**
182 * Transforms a Query Source into SQL and parameter arrays
183 *
184 * @param Tx_Extbase_Persistence_QOM_QueryObjectModel $query
185 * @param array &$sql
186 * @param array &$parameters
187 * @return void
188 */
189 protected function parseSource(Tx_Extbase_Persistence_QOM_QueryObjectModel $query, array &$sql, array &$parameters) {
190 $source = $query->getSource();
191 $sql['where'] = array();
192 if ($source instanceof Tx_Extbase_Persistence_QOM_SelectorInterface) {
193 $selectorName = $source->getSelectorName();
194 $sql['fields'][] = $selectorName . '.*';
195 $sql['tables'][] = $selectorName;
196 // 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.
197 $this->addEnableFieldsStatement($selectorName, $sql);
198 } elseif ($source instanceof Tx_Extbase_Persistence_QOM_JoinInterface) {
199 $this->parseJoin($source, $sql, $parameters);
200 }
201 }
202
203 /**
204 * Transforms a Join into SQL and parameter arrays
205 *
206 * @param Tx_Extbase_Persistence_QOM_JoinInterface $join
207 * @param array &$sql
208 * @param array &$parameters
209 * @return void
210 */
211 protected function parseJoin(Tx_Extbase_Persistence_QOM_JoinInterface $join, array &$sql, array &$parameters) {
212 $leftSelectorName = $join->getLeft()->getSelectorName();
213 $rightSelectorName = $join->getRight()->getSelectorName();
214
215 $sql['fields'][] = $leftSelectorName . '.*';
216 $sql['fields'][] = $rightSelectorName . '.*';
217
218 // TODO Implement support for different join types and nested joins
219 $sql['tables'][] = $leftSelectorName . ' INNER JOIN ' . $rightSelectorName;
220
221 $joinCondition = $join->getJoinCondition();
222 // TODO Check the parsing of the join
223 if ($joinCondition instanceof Tx_Extbase_Persistence_QOM_EquiJoinCondition) {
224 $sql['tables'][] = 'ON ' . $joinCondition->getSelector1Name() . '.' . $joinCondition->getProperty1Name() . ' = ' . $joinCondition->getSelector2Name() . '.' . $joinCondition->getProperty2Name();
225 }
226 // TODO Implement childtableWhere
227 }
228
229 /**
230 * Transforms a constraint into SQL and parameter arrays
231 *
232 * @param Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint
233 * @param array &$sql
234 * @param array &$parameters
235 * @param array $boundVariableValues
236 * @return void
237 */
238 protected function parseConstraint(Tx_Extbase_Persistence_QOM_ConstraintInterface $constraint = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
239 if ($constraint instanceof Tx_Extbase_Persistence_QOM_AndInterface) {
240 $sql['where'][] = '(';
241 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
242 $sql['where'][] = ' AND ';
243 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
244 $sql['where'][] = ') ';
245 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_OrInterface) {
246 $sql['where'][] = '(';
247 $this->parseConstraint($constraint->getConstraint1(), $sql, $parameters, $boundVariableValues);
248 $sql['where'][] = ' OR ';
249 $this->parseConstraint($constraint->getConstraint2(), $sql, $parameters, $boundVariableValues);
250 $sql['where'][] = ') ';
251 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_NotInterface) {
252 $sql['where'][] = '(NOT ';
253 $this->parseConstraint($constraint->getConstraint(), $sql, $parameters, $boundVariableValues);
254 $sql['where'][] = ') ';
255 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_ComparisonInterface) {
256 $this->parseComparison($constraint, $sql, $parameters, $boundVariableValues);
257 } elseif ($constraint instanceof Tx_Extbase_Persistence_QOM_RelatedInterface) {
258 $this->parseRelated($constraint, $sql, $parameters, $boundVariableValues);
259 }
260 }
261
262 /**
263 * Parse a Comparison into SQL and parameter arrays.
264 *
265 * @param Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison The comparison to parse
266 * @param array &$sql SQL query parts to add to
267 * @param array &$parameters Parameters to bind to the SQL
268 * @param array $boundVariableValues The bound variables in the query and their values
269 * @return void
270 */
271 protected function parseComparison(Tx_Extbase_Persistence_QOM_ComparisonInterface $comparison, array &$sql, array &$parameters, array $boundVariableValues) {
272 $this->parseDynamicOperand($comparison->getOperand1(), $comparison->getOperator(), $sql, $parameters);
273
274 if ($comparison->getOperand2() instanceof Tx_Extbase_Persistence_QOM_BindVariableValueInterface) {
275 $parameters[] = $boundVariableValues[$comparison->getOperand2()->getBindVariableName()];
276 }
277 }
278
279 /**
280 * Parse a DynamicOperand into SQL and parameter arrays.
281 *
282 * @param Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand
283 * @param string $operator One of the JCR_OPERATOR_* constants
284 * @param array $boundVariableValues
285 * @param array &$parameters
286 * @param string $valueFunction an aoptional SQL function to apply to the operand value
287 * @return void
288 */
289 protected function parseDynamicOperand(Tx_Extbase_Persistence_QOM_DynamicOperandInterface $operand, $operator, array &$sql, array &$parameters, $valueFunction = NULL) {
290 if ($operand instanceof Tx_Extbase_Persistence_QOM_LowerCaseInterface) {
291 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'LOWER');
292 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_UpperCaseInterface) {
293 $this->parseDynamicOperand($operand->getOperand(), $operator, $sql, $parameters, 'UPPER');
294 } elseif ($operand instanceof Tx_Extbase_Persistence_QOM_PropertyValueInterface) {
295 $selectorName = $operand->getSelectorName();
296 $operator = $this->resolveOperator($operator);
297
298 $constraintSQL = '(';
299 if ($valueFunction === NULL) {
300 $constraintSQL .= (!empty($selectorName) ? $selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
301 } else {
302 $constraintSQL .= $valueFunction . '(' . (!empty($selectorName) ? $selectorName . '.' : '') . $operand->getPropertyName() . ' ' . $operator . ' ?';
303 }
304 $constraintSQL .= ') ';
305
306 $sql['where'][] = $constraintSQL;
307 }
308 }
309
310 /**
311 * Returns the SQL operator for the given JCR operator type.
312 *
313 * @param string $operator One of the JCR_OPERATOR_* constants
314 * @return string an SQL operator
315 */
316 protected function resolveOperator($operator) {
317 switch ($operator) {
318 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_EQUAL_TO:
319 $operator = '=';
320 break;
321 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_NOT_EQUAL_TO:
322 $operator = '!=';
323 break;
324 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN:
325 $operator = '<';
326 break;
327 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO:
328 $operator = '<=';
329 break;
330 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN:
331 $operator = '>';
332 break;
333 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO:
334 $operator = '>=';
335 break;
336 case Tx_Extbase_Persistence_QOM_QueryObjectModelConstantsInterface::JCR_OPERATOR_LIKE:
337 $operator = 'LIKE';
338 break;
339 default:
340 throw new Tx_Extbase_Persistence_Exception('Unsupported operator encountered.', 1242816073);
341 }
342
343 return $operator;
344 }
345
346 /**
347 * Replace query placeholders in a query part by the given
348 * parameters.
349 *
350 * @param string $queryPart The query part with placeholders
351 * @param array $parameters The parameters
352 * @return string The query part with replaced placeholders
353 */
354 protected function replacePlaceholders(&$sqlString, array $parameters) {
355 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);
356 foreach ($parameters as $parameter) {
357 $markPosition = strpos($sqlString, '?');
358 if ($markPosition !== FALSE) {
359 $sqlString = substr($sqlString, 0, $markPosition) . '"' . $parameter . '"' . substr($sqlString, $markPosition + 1);
360 }
361 }
362 }
363
364 /**
365 * Returns the enable fields part of a WHERE query
366 * @param string $selectorName The selector name (= database table name)
367 * @param array &$sql The query parts
368 *
369 * @return void
370 */
371 protected function addEnableFieldsStatement($selectorName, array &$sql) {
372 // TODO We have to call the appropriate API method if we are in TYPO3BE mode
373 $statement = substr($GLOBALS['TSFE']->sys_page->enableFields($selectorName), 4);
374 if (!empty($statement)) {
375 $sql['where'][] = $statement;
376 }
377 }
378
379 /**
380 * Transforms orderings into SQL
381 *
382 * @param array $orderings
383 * @param array &$sql
384 * @param array &$parameters
385 * @param array $boundVariableValues
386 * @return void
387 */
388 protected function parseOrderings(array $orderings = NULL, array &$sql, array &$parameters, array $boundVariableValues) {
389 if (is_array($orderings)) {
390 foreach ($orderings as $propertyName => $ordering) {
391 // TODO Implement
392 }
393 }
394 }
395
396 /**
397 * Transforms a Resource from a database query to an array of rows. Performs the language and
398 * workspace overlay before.
399 *
400 * @return array The result as an array of rows (tuples)
401 */
402 protected function getRowsFromResult($tableName, $res) {
403 $rows = array();
404 while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
405 $row = $this->doLanguageAndWorkspaceOverlay($tableName, $row);
406 if (is_array($row)) {
407 // TODO Check if this is necessary, maybe the last line is enough
408 $arrayKeys = range(0,count($row));
409 array_fill_keys($arrayKeys, $row);
410 $rows[] = $row;
411 }
412 }
413 return $rows;
414 }
415
416 /**
417 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
418 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
419 *
420 * @param Tx_Extbase_Persistence_Mapper_DataMap $dataMap
421 * @param array $row The row array (as reference)
422 * @param string $languageUid The language id
423 * @param string $workspaceUidUid The workspace id
424 * @return void
425 */
426 protected function doLanguageAndWorkspaceOverlay($tableName, array $row, $languageUid = NULL, $workspaceUid = NULL) {
427 if (!($this->pageSelectObject instanceof t3lib_pageSelect)) {
428 if (TYPO3_MODE == 'FE') {
429 if (is_object($GLOBALS['TSFE'])) {
430 $this->pageSelectObject = $GLOBALS['TSFE']->sys_page;
431 if ($languageUid === NULL) {
432 $languageUid = $GLOBALS['TSFE']->sys_language_content;
433 }
434 } else {
435 require_once(PATH_t3lib . 'class.t3lib_page.php');
436 $this->pageSelectObject = t3lib_div::makeInstance('t3lib_pageSelect');
437 if ($languageUid === NULL) {
438 $languageUid = intval(t3lib_div::_GP('L'));
439 }
440 }
441 if ($workspaceUid !== NULL) {
442 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
443 }
444 } else {
445 require_once(PATH_t3lib . 'class.t3lib_page.php');
446 $this->pageSelectObject = t3lib_div::makeInstance( 't3lib_pageSelect' );
447 //$this->pageSelectObject->versioningPreview = TRUE;
448 if ($workspaceUid === NULL) {
449 $workspaceUid = $GLOBALS['BE_USER']->workspace;
450 }
451 $this->pageSelectObject->versioningWorkspaceId = $workspaceUid;
452 }
453 }
454
455 $this->pageSelectObject->versionOL($tableName, $row, TRUE);
456 $row = $this->pageSelectObject->getRecordOverlay($tableName, $row, $languageUid, ''); //'hideNonTranslated'
457 // TODO Skip if empty languageoverlay (languagevisibility)
458 return $row;
459 }
460
461 }
462
463 ?>