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) {
219 $properties = $object->_getProperties();
220 $dataMap = $this->getDataMap(get_class($object));
221 $relations = $this->getRelations($dataMap, $properties);
222 $row = $this->getRow($dataMap, $properties);
223
224 if ($parentObject instanceof TX_EXTMVC_DomainObject_AbstractDomainObject && $parentPropertyName !== NULL) {
225 $parentDataMap = $this->getDataMap(get_class($parentObject));
226 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
227 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
228 if ($parentKeyFieldName !== NULL) {
229 $row[$parentKeyFieldName] = $parentObject->getUid();
230 }
231 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
232 if ($parentTableFieldName !== NULL) {
233 $row[$parentTableFieldName] = $parentDataMap->getTableName();
234 }
235 }
236
237 unset($row['uid']);
238 // TODO Check if there is a pid field/tstamp field
239 $row['pid'] = !empty($this->cObj->data['pages']) ? $this->cObj->data['pages'] : $GLOBALS['TSFE']->id;
240 $row['tstamp'] = time();
241
242 $tableName = $dataMap->getTableName();
243 $res = $GLOBALS['TYPO3_DB']->exec_INSERTquery(
244 $tableName,
245 $row
246 );
247 $object->_reconstituteProperty('uid', $GLOBALS['TYPO3_DB']->sql_insert_id());
248
249 $recurseIntoRelations = TRUE; // TODO Make this configurable
250 if ($recurseIntoRelations === TRUE) {
251 $this->persistRelations($object, $propertyName, $relations);
252 }
253 }
254
255 /**
256 * Updates a modified object in the database
257 *
258 * @return void
259 */
260 // SK: I need to check this more thorougly
261 protected function updateObject(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $parentObject = NULL, $parentPropertyName = NULL) {
262 $properties = $object->_getDirtyProperties();
263 $dataMap = $this->getDataMap(get_class($object));
264 $relations = $this->getRelations($dataMap, $properties);
265 $row = $this->getRow($dataMap, $properties);
266 unset($row['uid']);
267 $row['crdate'] = time();
268 if (!empty($GLOBALS['TSFE']->fe_user->user['uid'])) {
269 $row['cruser_id'] = $GLOBALS['TSFE']->fe_user->user['uid'];
270 }
271 if ($parentObject instanceof TX_EXTMVC_DomainObject_AbstractDomainObject && $parentPropertyName !== NULL) {
272 $parentDataMap = $this->getDataMap(get_class($parentObject));
273 $parentColumnMap = $parentDataMap->getColumnMap($parentPropertyName);
274 $parentKeyFieldName = $parentColumnMap->getParentKeyFieldName();
275 if ($parentKeyFieldName !== NULL) {
276 $row[$parentKeyFieldName] = $parentObject->getUid();
277 }
278 $parentTableFieldName = $parentColumnMap->getParentTableFieldName();
279 if ($parentTableFieldName !== NULL) {
280 $row[$parentTableFieldName] = $parentDataMap->getTableName();
281 }
282 }
283
284 $tableName = $dataMap->getTableName();
285 $res = $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
286 $tableName,
287 'uid=' . $object->getUid(),
288 $row
289 );
290
291 $recurseIntoRelations = TRUE; // TODO make parametric
292 if ($recurseIntoRelations === TRUE) {
293 $this->persistRelations($object, $propertyName, $relations);
294 }
295 }
296
297 /**
298 * Deletes an object, it's 1:n related objects, and the m:n relations in relation tables (but not the m:n related objects!)
299 *
300 * @return void
301 */
302 // SK: I need to check this more thorougly
303 protected function deleteObject(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $parentObject = NULL, $parentPropertyName = NULL, $recurseIntoRelations = FALSE, $onlySetDeleted = TRUE) {
304 $relations = array();
305 $properties = $object->_getDirtyProperties();
306 $dataMap = $this->getDataMap(get_class($object));
307 $relations = $this->getRelations($dataMap, $properties);
308
309 $tableName = $dataMap->getTableName();
310 if ($onlySetDeleted === TRUE && !empty($deletedColumnName)) {
311 $deletedColumnName = $dataMap->getDeletedColumnName();
312 $res = $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
313 $tableName,
314 'uid=' . $object->getUid(),
315 array($deletedColumnName => 1)
316 );
317 } else {
318 $res = $GLOBALS['TYPO3_DB']->exec_DELETEquery(
319 $tableName,
320 'uid=' . $object->getUid()
321 );
322 }
323
324 if ($recurseIntoRelations === TRUE) {
325 $this->processRelations($object, $propertyName, $relations);
326 }
327 }
328
329 /**
330 * Returns a table row to be inserted or updated in the database
331 *
332 * @param TX_EXTMVC_Persistence_Mapper_DataMap $dataMap The appropriate data map representing a database table
333 * @param array $properties The properties of the object
334 * @return array A single row to be inserted in the database
335 */
336 // SK: I need to check this more thorougly
337 protected function getRow(TX_EXTMVC_Persistence_Mapper_DataMap $dataMap, $properties) {
338 $relations = array();
339 foreach ($dataMap->getColumnMaps() as $columnMap) {
340 $propertyName = $columnMap->getPropertyName();
341 $columnName = $columnMap->getColumnName();
342 if ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_MANY) {
343 $row[$columnName] = count($properties[$propertyName]);
344 } elseif ($columnMap->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
345 // TODO Check if this elseif is needed or could be merged with the above
346 $row[$columnName] = count($properties[$propertyName]);
347 } else {
348 if ($properties[$propertyName] !== NULL) {
349 $row[$columnName] = $dataMap->convertPropertyValueToFieldValue($properties[$propertyName]);
350 }
351 }
352 }
353 return $row;
354 }
355
356 /**
357 * Returns all property values holding child objects
358 *
359 * @param TX_EXTMVC_Persistence_Mapper_DataMap $dataMap The data map
360 * @param string $properties The object properties
361 * @return array An array of properties with related child objects
362 */
363 protected function getRelations(TX_EXTMVC_Persistence_Mapper_DataMap $dataMap, $properties) {
364 $relations = array();
365 foreach ($dataMap->getColumnMaps() as $columnMap) {
366 $propertyName = $columnMap->getPropertyName();
367 $columnName = $columnMap->getColumnName();
368 if ($columnMap->isRelation()) {
369 $relations[$propertyName] = $properties[$propertyName];
370 }
371 }
372 return $relations;
373 }
374
375 /**
376 * Inserts and updates all relations of an object. It also inserts and updates data in relation tables.
377 *
378 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $object The object for which the relations should be updated
379 * @param string $propertyName The name of the property holding the related child objects
380 * @param array $relations The queued relations
381 * @return void
382 */
383 protected function persistRelations(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $propertyName, array $relations) {
384 $dataMap = $this->getDataMap(get_class($object));
385 foreach ($relations as $propertyName => $relatedObjects) {
386 if (!empty($relatedObjects)) {
387 $typeOfRelation = $dataMap->getColumnMap($propertyName)->getTypeOfRelation();
388 foreach ($relatedObjects as $relatedObject) {
389 if (!$this->persistenceSession->isReconstitutedObject($relatedObject)) {
390 $this->insertObject($relatedObject, $object, $propertyName);
391 if ($typeOfRelation === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
392 $this->insertRelationInRelationTable($relatedObject, $object, $propertyName);
393 }
394 } elseif ($this->persistenceSession->isReconstitutedObject($relatedObject) && $relatedObject->_isDirty()) {
395 $this->updateObject($relatedObject, $object, $propertyName);
396 }
397 }
398 }
399 }
400 }
401
402 /**
403 * Deletes all relations of an object.
404 *
405 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $object The object for which the relations should be updated
406 * @param string $propertyName The name of the property holding the related child objects
407 * @param array $relations The queued relations
408 * @return void
409 */
410 protected function deleteRelations(TX_EXTMVC_DomainObject_AbstractDomainObject $object, $propertyName, array $relations) {
411 $dataMap = $this->getDataMap(get_class($object));
412 foreach ($relations as $propertyName => $relatedObjects) {
413 if (is_array($relatedObjects)) {
414 foreach ($relatedObjects as $relatedObject) {
415 $this->deleteObject($relatedObject, $object, $propertyName);
416 if ($dataMap->getColumnMap($propertyName)->getTypeOfRelation() === TX_EXTMVC_Persistence_Mapper_ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
417 $this->deleteRelationInRelationTable($relatedObject, $object, $propertyName);
418 }
419 }
420 }
421 }
422 }
423
424 /**
425 * Inserts relation to a relation table
426 *
427 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $relatedObject The related object
428 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject The parent object
429 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
430 * @return void
431 */
432 protected function insertRelationInRelationTable(TX_EXTMVC_DomainObject_AbstractDomainObject $relatedObject, TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject, $parentPropertyName) {
433 $dataMap = $this->getDataMap(get_class($parentObject));
434 $rowToInsert = array(
435 'uid_local' => $parentObject->getUid(),
436 'uid_foreign' => $relatedObject->getUid(),
437 'tablenames' => $dataMap->getTableName(),
438 'sorting' => 9999 // TODO sorting of mm table items
439 );
440 $tableName = $dataMap->getColumnMap($parentPropertyName)->getRelationTableName();
441 $res = $GLOBALS['TYPO3_DB']->exec_INSERTquery(
442 $tableName,
443 $rowToInsert
444 );
445 }
446
447 /**
448 * Update relations in a relation table
449 *
450 * @param array $relatedObjects An array of related objects
451 * @param TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject The parent object
452 * @param string $parentPropertyName The name of the parent object's property where the related objects are stored in
453 * @return void
454 */
455 protected function deleteRelationInRelationTable($relatedObject, TX_EXTMVC_DomainObject_AbstractDomainObject $parentObject, $parentPropertyName) {
456 $dataMap = $this->getDataMap(get_class($parentObject));
457 $tableName = $dataMap->getColumnMap($parentPropertyName)->getRelationTableName();
458 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
459 'uid_foreign',
460 $tableName,
461 'uid_local=' . $parentObject->getUid()
462 );
463 $existingRelations = array();
464 while($row = mysql_fetch_assoc($res)) {
465 $existingRelations[current($row)] = current($row);
466 }
467 $relationsToDelete = $existingRelations;
468 if (is_array($relatedObject)) {
469 foreach ($relatedObject as $relatedObject) {
470 $relatedObjectUid = $relatedObject->getUid();
471 if (array_key_exists($relatedObjectUid, $relationsToDelete)) {
472 unset($relationsToDelete[$relatedObjectUid]);
473 }
474 }
475 }
476 if (count($relationsToDelete) > 0) {
477 $relationsToDeleteList = implode(',', $relationsToDelete);
478 $res = $GLOBALS['TYPO3_DB']->exec_DELETEquery(
479 $tableName,
480 'uid_local=' . $parentObject->getUid() . ' AND uid_foreign IN (' . $relationsToDeleteList . ')'
481 );
482 }
483 }
484
485 /**
486 * Delegates the call to the Data Map.
487 * Returns TRUE if the property is persistable (configured in $TCA)
488 *
489 * @param string $className The property name
490 * @param string $propertyName The property name
491 * @return boolean TRUE if the property is persistable (configured in $TCA)
492 */
493 public function isPersistableProperty($className, $propertyName) {
494 $dataMap = new TX_EXTMVC_Persistence_Mapper_DataMap($className);
495 $dataMap->initialize();
496 return $dataMap->isPersistableProperty($propertyName);
497 }
498
499 /**
500 * Returns a data map for a given class name
501 *
502 * @return TX_EXTMVC_Persistence_Mapper_DataMap The data map
503 */
504 protected function getDataMap($className) {
505 // TODO Cache data maps
506 if (empty($this->dataMaps[$className])) {
507 $dataMap = new TX_EXTMVC_Persistence_Mapper_DataMap($className);
508 $dataMap->initialize();
509 $this->dataMaps[$className] = $dataMap;
510 }
511 return $this->dataMaps[$className];
512 }
513
514 }
515 ?>