EXTMVC:
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Mapper / ObjectRelationalMapper.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009 Jochen Rau <jochen.rau@typoplanet.de>
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 *
17 * This script is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * This copyright notice MUST APPEAR in all copies of the script!
23 ***************************************************************/
24
25 require_once(PATH_t3lib . 'interfaces/interface.t3lib_singleton.php');
26 require_once(PATH_tslib . 'class.tslib_content.php');
27
28 /**
29 * A mapper to map database tables configured in $TCA on domain objects.
30 *
31 * @package TYPO3
32 * @subpackage extmvc
33 * @version $ID:$
34 */
35 class TX_EXTMVC_Persistence_Mapper_ObjectRelationalMapper implements t3lib_Singleton {
36
37 /**
38 * The persistence session
39 *
40 * @var TX_EXTMVC_Persistence_Session
41 **/
42 protected $persistenceSession;
43
44 /**
45 * Cached data maps
46 *
47 * @var array
48 **/
49 protected $dataMaps = array();
50
51 /**
52 * Constructs a new mapper
53 *
54 */
55 public function __construct() {
56 $this->persistenceSession = t3lib_div::makeInstance('TX_EXTMVC_Persistence_Session');
57 $GLOBALS['TSFE']->includeTCA();
58 }
59
60 /**
61 * Fetches rows from the database by given SQL statement snippets
62 *
63 * @param string $className the className
64 * @param string $where WHERE statement
65 * @param string $groupBy GROUP BY statement
66 * @param string $orderBy ORDER BY statement
67 * @param string $limit LIMIT statement
68 * @return array The matched rows
69 */
70 public function fetch($className, $where = '1=1', $groupBy = '', $orderBy = '', $limit = '', $useEnableFields = TRUE) {
71 $dataMap = $this->getDataMap($className);
72 if ($useEnableFields === TRUE) {
73 $enableFields = $GLOBALS['TSFE']->sys_page->enableFields($dataMap->getTableName());
74 } else {
75 $enableFields = '';
76 }
77 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
78 '*', // TODO limit fetched fields
79 $dataMap->getTableName(),
80 $where . $enableFields,
81 $groupBy,
82 $orderBy,
83 $limit
84 );
85 // SK: Do we want to make it possible to ignore "enableFields"?
86 // TODO language overlay; workspace overlay
87 $objects = array();
88 if (is_array($rows)) {
89 if (count($rows) > 0) {
90 $objects = $this->reconstituteObjects($dataMap, $rows);
91 }
92 }
93 return $objects;
94 }
95
96 /**
97 * Fetches a rows from the database by given SQL statement snippets taking a relation table into account
98 *
99 * @param string Optional WHERE clauses put in the end of the query, defaults to '1=1. NOTICE: You must escape values in this argument with $this->fullQuoteStr() yourself!
100 * @param string Optional GROUP BY field(s), defaults to blank string.
101 * @param string Optional ORDER BY field(s), defaults to blank string.
102 * @param string Optional LIMIT value ([begin,]max), defaults to blank string.
103 */
104 // SK: Are SQL injections possible here? Can we somehow prevent them? I did not check it thoroughly yet, but I think they are possible
105 public function fetchWithRelationTable($parentObject, $columnMap, $where = '1=1', $groupBy = '', $orderBy = '', $limit = '', $useEnableFields = TRUE) {
106 if ($useEnableFields === TRUE) {
107 $enableFields = $GLOBALS['TSFE']->sys_page->enableFields($columnMap->getChildTableName());
108 } else {
109 $enableFields = '';
110 }
111 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
112 $columnMap->getChildTableName() . '.*, ' . $columnMap->getRelationTableName() . '.*',
113 $columnMap->getChildTableName() . ' LEFT JOIN ' . $columnMap->getRelationTableName() . ' ON (' . $columnMap->getChildTableName() . '.uid=' . $columnMap->getRelationTableName() . '.uid_foreign)',
114 $where . ' AND ' . $columnMap->getRelationTableName() . '.uid_local=' . t3lib_div::intval_positive($parentObject->getUid()) . $enableFields,
115 $groupBy,
116 $orderBy,
117 $limit
118 );
119 // TODO language overlay; workspace overlay; sorting
120 return $rows ? $rows : array();
121 }
122
123 /**
124 * reconstitutes domain objects from $rows (array)
125 *
126 * @param TX_EXTMVC_Persistence_Mapper_DataMap $dataMap The data map corresponding to the domain object
127 * @param array $rows The rows array fetched from the database
128 * @return array An array of reconstituted domain objects
129 */
130 // SK: I Need to check this method more thoroughly.
131 // SK: Are loops detected during reconstitution?
132 // SK: What about "1:1" relations?
133 protected function reconstituteObjects($dataMap, array $rows) {
134 $objects = array();
135 foreach ($rows as $row) {
136 $properties = array();
137 foreach ($dataMap->getColumnMaps() as $columnMap) {
138 $properties[$columnMap->getPropertyName()] = $dataMap->convertFieldValueToPropertyValue($columnMap->getPropertyName(), $row[$columnMap->getColumnName()]);
139 }
140 $object = $this->reconstituteObject($dataMap->getClassName(), $properties);
141 foreach ($dataMap->getColumnMaps() as $columnMap) {
142 if ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
143 $where = $columnMap->getParentKeyFieldName() . '=' . intval($object->getUid());
144 $relatedDataMap = $this->getDataMap($columnMap->getChildClassName());
145 $relatedObjects = $this->fetch($columnMap->getChildClassName(), $where);
146 $object->_reconstituteProperty($columnMap->getPropertyName(), $relatedObjects);
147 } elseif ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
148 $relatedDataMap = $this->getDataMap($columnMap->getChildClassName());
149 $relatedObjects = $this->fetchWithRelationTable($object, $columnMap);
150 $object->_reconstituteProperty($columnMap->getPropertyName(), $relatedObjects);
151 }
152 }
153 $this->persistenceSession->registerReconstitutedObject($object);
154 $objects[] = $object;
155 }
156 return $objects;
157 }
158
159 /**
160 * Reconstitutes the specified object and fills it with the given properties.
161 *
162 * @param string $objectName Name of the object to reconstitute
163 * @param array $properties The names of properties and their values which should be set during the reconstitution
164 * @return object The reconstituted object
165 */
166 protected function reconstituteObject($className, array $properties = array()) {
167 // those objects will be fetched from within the __wakeup() method of the object...
168 $GLOBALS['EXTMVC']['reconstituteObject']['properties'] = $properties;
169 $object = unserialize('O:' . strlen($className) . ':"' . $className . '":0:{};');
170 unset($GLOBALS['EXTMVC']['reconstituteObject']);
171 return $object;
172 }
173
174 /**
175 * Persists all objects of a persistence session
176 *
177 * @return void
178 */
179 public function persistAll() {
180 // first, persit all aggregate root objects
181 $aggregateRootClassNames = $this->persistenceSession->getAggregateRootClassNames();
182 foreach ($aggregateRootClassNames as $className) {
183 $this->persistObjects($className);
184 }
185 // persist all remaining objects registered manually
186 // $this->persistObjects();
187 }
188
189 /**
190 * Persists all objects of a persitance persistence session that are of a given class. If there
191 * is no class specified, it persits all objects of a persistence session.
192 *
193 * @param string $className Name of the class of the objects to be persisted
194 */
195 protected function persistObjects($className = NULL) {
196 foreach ($this->persistenceSession->getAddedObjects($className) as $object) {
197 $this->insertObject($object);
198 $this->persistenceSession->unregisterObject($object);
199 $this->persistenceSession->registerReconstitutedObject($object);
200 }
201 foreach ($this->persistenceSession->getDirtyObjects($className) as $object) {
202 $this->updateObject($object);
203 $this->persistenceSession->unregisterObject($object);
204 $this->persistenceSession->registerReconstitutedObject($object);
205 }
206 foreach ($this->persistenceSession->getRemovedObjects($className) as $object) {
207 $this->deleteObject($object);
208 $this->persistenceSession->unregisterObject($object);
209 }
210 }
211
212 /**
213 * Inserts an object to the database.
214 *
215 * @return void
216 */
217 // SK: I need to check this more thorougly
218 protected function insertObject(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $parentObject = NULL, $parentPropertyName = NULL, $recurseIntoRelations = TRUE) {
219 $properties = $object->_getProperties();
220 $dataMap = $this->getDataMap(get_class($object));
221 $row = $this->getRow($dataMap, $properties);
222
223 if ($parentObject instanceof TX_EXTMVC_DomainObject_AbstractDomainObject && $parentPropertyName !== NULL) {
224 $parentDataMap = $this->getDataMap(get_class($parentObject));
225 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
226 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
227 if ($parentKeyFieldName !== NULL) {
228 $row[$parentKeyFieldName] = $parentObject->getUid();
229 }
230 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
231 if ($parentTableFieldName !== NULL) {
232 $row[$parentTableFieldName] = $parentDataMap->getTableName();
233 }
234 }
235
236 unset($row['uid']);
237
238 $row['pid'] = !empty($this->cObj->data['pages']) ? $this->cObj->data['pages'] : $GLOBALS['TSFE']->id;
239 $row['tstamp'] = time();
240
241 $tableName = $dataMap->getTableName();
242 $res = $GLOBALS['TYPO3_DB']->exec_INSERTquery(
243 $tableName,
244 $row
245 );
246 $object->_reconstituteProperty('uid', $GLOBALS['TYPO3_DB']->sql_insert_id());
247
248 $this->persistRelations($object, $propertyName, $this->getRelations($dataMap, $properties));
249 }
250
251 /**
252 * Updates a modified object in the database
253 *
254 * @return void
255 */
256 // SK: I need to check this more thorougly
257 protected function updateObject(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $parentObject = NULL, $parentPropertyName = NULL, $recurseIntoRelations = TRUE) {
258 $properties = $object->_getDirtyProperties();
259 $dataMap = $this->getDataMap(get_class($object));
260 $row = $this->getRow($dataMap, $properties);
261 unset($row['uid']);
262 // TODO Check for crdate column
263 $row['crdate'] = time();
264 if (!empty($GLOBALS['TSFE']->fe_user->user['uid'])) {
265 $row['cruser_id'] = $GLOBALS['TSFE']->fe_user->user['uid'];
266 }
267 if ($parentObject instanceof TX_EXTMVC_DomainObject_AbstractDomainObject && $parentPropertyName !== NULL) {
268 $parentDataMap = $this->getDataMap(get_class($parentObject));
269 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
270 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
271 if ($parentKeyFieldName !== NULL) {
272 $row[$parentKeyFieldName] = $parentObject->getUid();
273 }
274 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
275 if ($parentTableFieldName !== NULL) {
276 $row[$parentTableFieldName] = $parentDataMap->getTableName();
277 }
278 }
279
280 $tableName = $dataMap->getTableName();
281 $res = $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
282 $tableName,
283 'uid=' . $object->getUid(),
284 $row
285 );
286
287 $this->persistRelations($object, $propertyName, $this->getRelations($dataMap, $properties));
288 }
289
290 /**
291 * Deletes an object, it's 1:n related objects, and the m:n relations in relation tables (but not the m:n related objects!)
292 *
293 * @return void
294 */
295 // SK: I need to check this more thorougly
296 protected function deleteObject(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $parentObject = NULL, $parentPropertyName = NULL, $recurseIntoRelations = FALSE, $onlySetDeleted = TRUE) {
297 $relations = array();
298 $properties = $object->_getDirtyProperties();
299 $dataMap = $this->getDataMap(get_class($object));
300 $relations = $this->getRelations($dataMap, $properties);
301
302 $tableName = $dataMap->getTableName();
303 if ($onlySetDeleted === TRUE && !empty($deletedColumnName)) {
304 $deletedColumnName = $dataMap->getDeletedColumnName();
305 $res = $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
306 $tableName,
307 'uid=' . $object->getUid(),
308 array($deletedColumnName => 1)
309 );
310 } else {
311 $res = $GLOBALS['TYPO3_DB']->exec_DELETEquery(
312 $tableName,
313 'uid=' . $object->getUid()
314 );
315 }
316
317 if ($recurseIntoRelations === TRUE) {
318 $this->processRelations($object, $propertyName, $relations);
319 }
320 }
321
322 /**
323 * Returns a table row to be inserted or updated in the database
324 *
325 * @param TX_EXTMVC_Persistence_Mapper_DataMap $dataMap The appropriate data map representing a database table
326 * @param array $properties The properties of the object
327 * @return array A single row to be inserted in the database
328 */
329 // SK: I need to check this more thorougly
330 protected function getRow(TX_EXTMVC_Persistence_Mapper_DataMap $dataMap, $properties) {
331 $relations = array();
332 foreach ($dataMap->getColumnMaps() as $columnMap) {
333 $propertyName = $columnMap->getPropertyName();
334 $columnName = $columnMap->getColumnName();
335 if ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
336 $row[$columnName] = count($properties[$propertyName]);
337 } elseif ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
338 // TODO Check if this elseif is needed or could be merged with the lines above
339 $row[$columnName] = count($properties[$propertyName]);
340 } else {
341 if ($properties[$propertyName] !== NULL) {
342 $row[$columnName] = $dataMap->convertPropertyValueToFieldValue($properties[$propertyName]);
343 }
344 }
345 }
346 return $row;
347 }
348
349 /**
350 * Returns all property values holding child objects
351 *
352 * @param TX_EXTMVC_Persistence_Mapper_DataMap $dataMap The data map
353 * @param string $properties The object properties
354 * @return array An array of properties with related child objects
355 */
356 protected function getRelations(TX_EXTMVC_Persistence_Mapper_DataMap $dataMap, $properties) {
357 $relations = array();
358 foreach ($dataMap->getColumnMaps() as $columnMap) {
359 $propertyName = $columnMap->getPropertyName();
360 $columnName = $columnMap->getColumnName();
361 if ($columnMap->isRelation()) {
362 $relations[$propertyName] = $properties[$propertyName];
363 }
364 }
365 return $relations;
366 }
367
368 /**
369 * Inserts and updates all relations of an object. It also inserts and updates data in relation tables.
370 *
371 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $object The object for which the relations should be updated
372 * @param string $propertyName The name of the property holding the related child objects
373 * @param array $relations The queued relations
374 * @return void
375 */
376 protected function persistRelations(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $propertyName, array $relations) {
377 $dataMap = $this->getDataMap(get_class($object));
378 foreach ($relations as $propertyName => $relatedObjects) {
379 if (!empty($relatedObjects)) {
380 $typeOfRelation = $dataMap->getColumnMap($propertyName)->getTypeOfRelation();
381 foreach ($relatedObjects as $relatedObject) {
382 if (!$this->persistenceSession->isReconstitutedObject($relatedObject)) {
383 $this->insertObject($relatedObject, $object, $propertyName);
384 if ($typeOfRelation === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
385 $this->insertRelationInRelationTable($relatedObject, $object, $propertyName);
386 }
387 } elseif ($this->persistenceSession->isReconstitutedObject($relatedObject) && $relatedObject->_isDirty()) {
388 $this->updateObject($relatedObject, $object, $propertyName);
389 }
390 }
391 }
392 }
393 }
394
395 /**
396 * Deletes all relations of an object.
397 *
398 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $object The object for which the relations should be updated
399 * @param string $propertyName The name of the property holding the related child objects
400 * @param array $relations The queued relations
401 * @return void
402 */
403 protected function deleteRelations(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $propertyName, array $relations) {
404 $dataMap = $this->getDataMap(get_class($object));
405 foreach ($relations as $propertyName => $relatedObjects) {
406 if (is_array($relatedObjects)) {
407 foreach ($relatedObjects as $relatedObject) {
408 $this->deleteObject($relatedObject, $object, $propertyName);
409 if ($dataMap->getColumnMap($propertyName)->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
410 $this->deleteRelationInRelationTable($relatedObject, $object, $propertyName);
411 }
412 }
413 }
414 }
415 }
416
417 /**
418 * Inserts relation to a relation table
419 *
420 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $relatedObject The related object
421 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject The parent object
422 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
423 * @return void
424 */
425 protected function insertRelationInRelationTable(TX_EXTMVC_DomainObject_AbstractDomainObject $relatedObject, TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject, $parentPropertyName) {
426 $dataMap = $this->getDataMap(get_class($parentObject));
427 $rowToInsert = array(
428 'uid_local' => $parentObject->getUid(),
429 'uid_foreign' => $relatedObject->getUid(),
430 'tablenames' => $dataMap->getTableName(),
431 'sorting' => 9999 // TODO sorting of mm table items
432 );
433 $tableName = $dataMap->getColumnMap($parentPropertyName)->getRelationTableName();
434 $res = $GLOBALS['TYPO3_DB']->exec_INSERTquery(
435 $tableName,
436 $rowToInsert
437 );
438 }
439
440 /**
441 * Update relations in a relation table
442 *
443 * @param array $relatedObjects An array of related objects
444 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject The parent object
445 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
446 * @return void
447 */
448 protected function deleteRelationInRelationTable($relatedObject, TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject, $parentPropertyName) {
449 $dataMap = $this->getDataMap(get_class($parentObject));
450 $tableName = $dataMap->getColumnMap($parentPropertyName)->getRelationTableName();
451 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
452 'uid_foreign',
453 $tableName,
454 'uid_local=' . $parentObject->getUid()
455 );
456 $existingRelations = array();
457 while($row = mysql_fetch_assoc($res)) {
458 $existingRelations[current($row)] = current($row);
459 }
460 $relationsToDelete = $existingRelations;
461 if (is_array($relatedObject)) {
462 foreach ($relatedObject as $relatedObject) {
463 $relatedObjectUid = $relatedObject->getUid();
464 if (array_key_exists($relatedObjectUid, $relationsToDelete)) {
465 unset($relationsToDelete[$relatedObjectUid]);
466 }
467 }
468 }
469 if (count($relationsToDelete) > 0) {
470 $relationsToDeleteList = implode(',', $relationsToDelete);
471 $res = $GLOBALS['TYPO3_DB']->exec_DELETEquery(
472 $tableName,
473 'uid_local=' . $parentObject->getUid() . ' AND uid_foreign IN (' . $relationsToDeleteList . ')'
474 );
475 }
476 }
477
478 /**
479 * Delegates the call to the Data Map.
480 * Returns TRUE if the property is persistable (configured in $TCA)
481 *
482 * @param string $className The property name
483 * @param string $propertyName The property name
484 * @return boolean TRUE if the property is persistable (configured in $TCA)
485 */
486 public function isPersistableProperty($className, $propertyName) {
487 $dataMap = new TX_EXTMVC_Persistence_Mapper_DataMap($className);
488 $dataMap->initialize();
489 return $dataMap->isPersistableProperty($propertyName);
490 }
491
492 /**
493 * Returns a data map for a given class name
494 *
495 * @return TX_EXTMVC_Persistence_Mapper_DataMap The data map
496 */
497 protected function getDataMap($className) {
498 // TODO Cache data maps
499 if (empty($this->dataMaps[$className])) {
500 $dataMap = new TX_EXTMVC_Persistence_Mapper_DataMap($className);
501 $dataMap->initialize();
502 $this->dataMaps[$className] = $dataMap;
503 }
504 return $this->dataMaps[$className];
505 }
506
507 }
508 ?>