[!!!][TASK] Remove magic setter for $fromTC
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Database / RelationHandler.php
1 <?php
2 namespace TYPO3\CMS\Core\Database;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19 use TYPO3\CMS\Core\Utility\MathUtility;
20 use TYPO3\CMS\Core\Versioning\VersionState;
21
22 /**
23 * Load database groups (relations)
24 * Used to process the relations created by the TCA element types "group" and "select" for database records.
25 * Manages MM-relations as well.
26 *
27 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
28 */
29 class RelationHandler {
30
31 /**
32 * $fetchAllFields if false getFromDB() fetches only uid, pid, thumbnail and label fields (as defined in TCA)
33 *
34 * @var boolean
35 */
36 protected $fetchAllFields = FALSE;
37
38 /**
39 * If set, values that are not ids in tables are normally discarded. By this options they will be preserved.
40 * @todo Define visibility
41 */
42 public $registerNonTableValues = 0;
43
44 /**
45 * Contains the table names as keys. The values are the id-values for each table.
46 * Should ONLY contain proper table names.
47 *
48 * @var array
49 * @todo Define visibility
50 */
51 public $tableArray = array();
52
53 /**
54 * Contains items in an numeric array (table/id for each). Tablenames here might be "_NO_TABLE"
55 *
56 * @var array
57 * @todo Define visibility
58 */
59 public $itemArray = array();
60
61 /**
62 * Array for NON-table elements
63 *
64 * @var array
65 * @todo Define visibility
66 */
67 public $nonTableArray = array();
68
69 /**
70 * @var array
71 * @todo Define visibility
72 */
73 public $additionalWhere = array();
74
75 /**
76 * Deleted-column is added to additionalWhere... if this is set...
77 *
78 * @var boolean
79 * @todo Define visibility
80 */
81 public $checkIfDeleted = TRUE;
82
83 /**
84 * @var array
85 * @todo Define visibility
86 */
87 public $dbPaths = array();
88
89 /**
90 * Will contain the first table name in the $tablelist (for positive ids)
91 *
92 * @var string
93 * @todo Define visibility
94 */
95 public $firstTable = '';
96
97 /**
98 * Will contain the second table name in the $tablelist (for negative ids)
99 *
100 * @var string
101 * @todo Define visibility
102 */
103 public $secondTable = '';
104
105 /**
106 * If TRUE, uid_local and uid_foreign are switched, and the current table
107 * is inserted as tablename - this means you display a foreign relation "from the opposite side"
108 *
109 * @var boolean
110 * @todo Define visibility
111 */
112 public $MM_is_foreign = FALSE;
113
114 /**
115 * Field name at the "local" side of the MM relation
116 *
117 * @var string
118 * @todo Define visibility
119 */
120 public $MM_oppositeField = '';
121
122 /**
123 * Only set if MM_is_foreign is set
124 *
125 * @var string
126 * @todo Define visibility
127 */
128 public $MM_oppositeTable = '';
129
130 /**
131 * Only set if MM_is_foreign is set
132 *
133 * @var string
134 * @todo Define visibility
135 */
136 public $MM_oppositeFieldConf = '';
137
138 /**
139 * Is empty by default; if MM_is_foreign is set and there is more than one table
140 * allowed (on the "local" side), then it contains the first table (as a fallback)
141 * @todo Define visibility
142 * @var string
143 */
144 public $MM_isMultiTableRelationship = '';
145
146 /**
147 * Current table => Only needed for reverse relations
148 *
149 * @var string
150 * @todo Define visibility
151 */
152 public $currentTable;
153
154 /**
155 * If a record should be undeleted
156 * (so do not use the $useDeleteClause on \TYPO3\CMS\Backend\Utility\BackendUtility)
157 *
158 * @var boolean
159 * @todo Define visibility
160 */
161 public $undeleteRecord;
162
163 /**
164 * Array of fields value pairs that should match while SELECT
165 * and will be written into MM table if $MM_insert_fields is not set
166 *
167 * @var array
168 * @todo Define visibility
169 */
170 public $MM_match_fields = array();
171
172 /**
173 * This is set to TRUE if the MM table has a UID field.
174 *
175 * @var boolean
176 * @todo Define visibility
177 */
178 public $MM_hasUidField;
179
180 /**
181 * Array of fields and value pairs used for insert in MM table
182 *
183 * @var array
184 * @todo Define visibility
185 */
186 public $MM_insert_fields = array();
187
188 /**
189 * Extra MM table where
190 *
191 * @var string
192 * @todo Define visibility
193 */
194 public $MM_table_where = '';
195
196 /**
197 * Usage of a MM field on the opposite relation.
198 *
199 * @var array
200 */
201 protected $MM_oppositeUsage;
202
203 /**
204 * @var boolean
205 */
206 protected $updateReferenceIndex = TRUE;
207
208 /**
209 * @var bool
210 */
211 protected $useLiveParentIds = TRUE;
212
213 /**
214 * @var bool
215 */
216 protected $useLiveReferenceIds = TRUE;
217
218 /**
219 * @var int
220 */
221 protected $workspaceId;
222
223 /**
224 * @var bool
225 */
226 protected $purged = FALSE;
227
228 /**
229 * This array will be filled by getFromDB().
230 *
231 * @var array
232 */
233 public $results = array();
234
235 /**
236 * Gets the current workspace id.
237 *
238 * @return int
239 */
240 public function getWorkspaceId() {
241 if (!isset($this->workspaceId)) {
242 $this->workspaceId = (int)$GLOBALS['BE_USER']->workspace;
243 }
244 return $this->workspaceId;
245 }
246
247 /**
248 * Sets the current workspace id.
249 *
250 * @param int $workspaceId
251 */
252 public function setWorkspaceId($workspaceId) {
253 $this->workspaceId = (int)$workspaceId;
254 }
255
256 /**
257 * Whether item array has been purged in this instance.
258 *
259 * @return bool
260 */
261 public function isPurged() {
262 return $this->purged;
263 }
264
265 /**
266 * Initialization of the class.
267 *
268 * @param string $itemlist List of group/select items
269 * @param string $tablelist Comma list of tables, first table takes priority if no table is set for an entry in the list.
270 * @param string $MMtable Name of a MM table.
271 * @param integer $MMuid Local UID for MM lookup
272 * @param string $currentTable Current table name
273 * @param array $conf TCA configuration for current field
274 * @return void
275 * @todo Define visibility
276 */
277 public function start($itemlist, $tablelist, $MMtable = '', $MMuid = 0, $currentTable = '', $conf = array()) {
278 $conf = (array)$conf;
279 // SECTION: MM reverse relations
280 $this->MM_is_foreign = (boolean)$conf['MM_opposite_field'];
281 $this->MM_oppositeField = $conf['MM_opposite_field'];
282 $this->MM_table_where = $conf['MM_table_where'];
283 $this->MM_hasUidField = $conf['MM_hasUidField'];
284 $this->MM_match_fields = is_array($conf['MM_match_fields']) ? $conf['MM_match_fields'] : array();
285 $this->MM_insert_fields = is_array($conf['MM_insert_fields']) ? $conf['MM_insert_fields'] : $this->MM_match_fields;
286 $this->currentTable = $currentTable;
287 if (!empty($conf['MM_oppositeUsage']) && is_array($conf['MM_oppositeUsage'])) {
288 $this->MM_oppositeUsage = $conf['MM_oppositeUsage'];
289 }
290 if ($this->MM_is_foreign) {
291 $tmp = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
292 // Normally, $conf['allowed'] can contain a list of tables,
293 // but as we are looking at a MM relation from the foreign side,
294 // it only makes sense to allow one one table in $conf['allowed']
295 $tmp = GeneralUtility::trimExplode(',', $tmp);
296 $this->MM_oppositeTable = $tmp[0];
297 unset($tmp);
298 // Only add the current table name if there is more than one allowed field
299 // We must be sure this has been done at least once before accessing the "columns" part of TCA for a table.
300 $this->MM_oppositeFieldConf = $GLOBALS['TCA'][$this->MM_oppositeTable]['columns'][$this->MM_oppositeField]['config'];
301 if ($this->MM_oppositeFieldConf['allowed']) {
302 $oppositeFieldConf_allowed = explode(',', $this->MM_oppositeFieldConf['allowed']);
303 if (count($oppositeFieldConf_allowed) > 1 || $this->MM_oppositeFieldConf['allowed'] === '*') {
304 $this->MM_isMultiTableRelationship = $oppositeFieldConf_allowed[0];
305 }
306 }
307 }
308 // SECTION: normal MM relations
309 // If the table list is "*" then all tables are used in the list:
310 if (trim($tablelist) === '*') {
311 $tablelist = implode(',', array_keys($GLOBALS['TCA']));
312 }
313 // The tables are traversed and internal arrays are initialized:
314 $tempTableArray = GeneralUtility::trimExplode(',', $tablelist, TRUE);
315 foreach ($tempTableArray as $val) {
316 $tName = trim($val);
317 $this->tableArray[$tName] = array();
318 if ($this->checkIfDeleted && $GLOBALS['TCA'][$tName]['ctrl']['delete']) {
319 $fieldN = $tName . '.' . $GLOBALS['TCA'][$tName]['ctrl']['delete'];
320 $this->additionalWhere[$tName] .= ' AND ' . $fieldN . '=0';
321 }
322 }
323 if (is_array($this->tableArray)) {
324 reset($this->tableArray);
325 } else {
326 // No tables
327 return;
328 }
329 // Set first and second tables:
330 // Is the first table
331 $this->firstTable = key($this->tableArray);
332 next($this->tableArray);
333 // If the second table is set and the ID number is less than zero (later)
334 // then the record is regarded to come from the second table...
335 $this->secondTable = key($this->tableArray);
336 // Now, populate the internal itemArray and tableArray arrays:
337 // If MM, then call this function to do that:
338 if ($MMtable) {
339 if ($MMuid) {
340 $this->readMM($MMtable, $MMuid);
341 $this->purgeItemArray();
342 } else {
343 // Revert to readList() for new records in order to load possible default values from $itemlist
344 $this->readList($itemlist, $conf);
345 $this->purgeItemArray();
346 }
347 } elseif ($MMuid && $conf['foreign_field']) {
348 // If not MM but foreign_field, the read the records by the foreign_field
349 $this->readForeignField($MMuid, $conf);
350 } else {
351 // If not MM, then explode the itemlist by "," and traverse the list:
352 $this->readList($itemlist, $conf);
353 // Do automatic default_sortby, if any
354 if ($conf['foreign_default_sortby']) {
355 $this->sortList($conf['foreign_default_sortby']);
356 }
357 }
358 }
359
360 /**
361 * Sets $fetchAllFields
362 *
363 * @param boolean $allFields enables fetching of all fields in getFromDB()
364 */
365 public function setFetchAllFields($allFields) {
366 $this->fetchAllFields = (boolean)$allFields;
367 }
368
369 /**
370 * Sets whether the reference index shall be updated.
371 *
372 * @param boolean $updateReferenceIndex Whether the reference index shall be updated
373 * @return void
374 */
375 public function setUpdateReferenceIndex($updateReferenceIndex) {
376 $this->updateReferenceIndex = (boolean)$updateReferenceIndex;
377 }
378
379 /**
380 * @param bool $useLiveParentIds
381 */
382 public function setUseLiveParentIds($useLiveParentIds) {
383 $this->useLiveParentIds = (bool)$useLiveParentIds;
384 }
385
386 /**
387 * @param bool $useLiveReferenceIds
388 */
389 public function setUseLiveReferenceIds($useLiveReferenceIds) {
390 $this->useLiveReferenceIds = (bool)$useLiveReferenceIds;
391 }
392
393 /**
394 * Explodes the item list and stores the parts in the internal arrays itemArray and tableArray from MM records.
395 *
396 * @param string $itemlist Item list
397 * @param array $configuration Parent field configuration
398 * @return void
399 * @todo Define visibility
400 */
401 public function readList($itemlist, array $configuration) {
402 if ((string) trim($itemlist) != '') {
403 $tempItemArray = GeneralUtility::trimExplode(',', $itemlist);
404 // Changed to trimExplode 31/3 04; HMENU special type "list" didn't work
405 // if there were spaces in the list... I suppose this is better overall...
406 foreach ($tempItemArray as $key => $val) {
407 // Will be set to "1" if the entry was a real table/id:
408 $isSet = 0;
409 // Extract table name and id. This is un the formular [tablename]_[id]
410 // where table name MIGHT contain "_", hence the reversion of the string!
411 $val = strrev($val);
412 $parts = explode('_', $val, 2);
413 $theID = strrev($parts[0]);
414 // Check that the id IS an integer:
415 if (MathUtility::canBeInterpretedAsInteger($theID)) {
416 // Get the table name: If a part of the exploded string, use that.
417 // Otherwise if the id number is LESS than zero, use the second table, otherwise the first table
418 $theTable = trim($parts[1])
419 ? strrev(trim($parts[1]))
420 : ($this->secondTable && $theID < 0 ? $this->secondTable : $this->firstTable);
421 // If the ID is not blank and the table name is among the names in the inputted tableList
422 if (((string) $theID != '' && $theID) && $theTable && isset($this->tableArray[$theTable])) {
423 // Get ID as the right value:
424 $theID = $this->secondTable ? abs((int)$theID) : (int)$theID;
425 // Register ID/table name in internal arrays:
426 $this->itemArray[$key]['id'] = $theID;
427 $this->itemArray[$key]['table'] = $theTable;
428 $this->tableArray[$theTable][] = $theID;
429 // Set update-flag:
430 $isSet = 1;
431 }
432 }
433 // If it turns out that the value from the list was NOT a valid reference to a table-record,
434 // then we might still set it as a NO_TABLE value:
435 if (!$isSet && $this->registerNonTableValues) {
436 $this->itemArray[$key]['id'] = $tempItemArray[$key];
437 $this->itemArray[$key]['table'] = '_NO_TABLE';
438 $this->nonTableArray[] = $tempItemArray[$key];
439 }
440 }
441
442 // Skip if not dealing with IRRE in a CSV list on a workspace
443 if ($configuration['type'] !== 'inline' || empty($configuration['foreign_table']) || !empty($configuration['foreign_field'])
444 || !empty($configuration['MM']) || count($this->tableArray) !== 1 || empty($this->tableArray[$configuration['foreign_table']])
445 || (int)$GLOBALS['BE_USER']->workspace === 0 || !BackendUtility::isTableWorkspaceEnabled($configuration['foreign_table'])) {
446 return;
447 }
448
449 // Fetch live record data
450 if ($this->useLiveReferenceIds) {
451 foreach ($this->itemArray as &$item) {
452 $item['id'] = $this->getLiveDefaultId($item['table'], $item['id']);
453 }
454 // Directly overlay workspace data
455 } else {
456 $rows = array();
457 $foreignTable = $configuration['foreign_table'];
458 foreach ($this->tableArray[$foreignTable] as $itemId) {
459 $rows[$itemId] = array('uid' => $itemId);
460 }
461 $this->itemArray = array();
462 foreach ($this->getRecordVersionsIds($foreignTable, $rows) as $row) {
463 $this->itemArray[] = array(
464 'id' => $row['uid'],
465 'table' => $foreignTable,
466 );
467 }
468 }
469 }
470 }
471
472 /**
473 * Does a sorting on $this->itemArray depending on a default sortby field.
474 * This is only used for automatic sorting of comma separated lists.
475 * This function is only relevant for data that is stored in comma separated lists!
476 *
477 * @param string $sortby The default_sortby field/command (e.g. 'price DESC')
478 * @return void
479 * @todo Define visibility
480 */
481 public function sortList($sortby) {
482 // Sort directly without fetching addional data
483 if ($sortby == 'uid') {
484 usort(
485 $this->itemArray,
486 function ($a, $b) {
487 return $a['id'] < $b['id'] ? -1 : 1;
488 }
489 );
490 } elseif (count($this->tableArray) == 1) {
491 reset($this->tableArray);
492 $table = key($this->tableArray);
493 $uidList = implode(',', current($this->tableArray));
494 if ($uidList) {
495 $this->itemArray = array();
496 $this->tableArray = array();
497 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'uid IN (' . $uidList . ')', '', $sortby);
498 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
499 $this->itemArray[] = array('id' => $row['uid'], 'table' => $table);
500 $this->tableArray[$table][] = $row['uid'];
501 }
502 $GLOBALS['TYPO3_DB']->sql_free_result($res);
503 }
504 }
505 }
506
507 /**
508 * Reads the record tablename/id into the internal arrays itemArray and tableArray from MM records.
509 * You can call this function after start if you supply no list to start()
510 *
511 * @param string $tableName MM Tablename
512 * @param integer $uid Local UID
513 * @return void
514 * @todo Define visibility
515 */
516 public function readMM($tableName, $uid) {
517 $key = 0;
518 $additionalWhere = '';
519 $theTable = NULL;
520 // In case of a reverse relation
521 if ($this->MM_is_foreign) {
522 $uidLocal_field = 'uid_foreign';
523 $uidForeign_field = 'uid_local';
524 $sorting_field = 'sorting_foreign';
525 if ($this->MM_isMultiTableRelationship) {
526 $additionalWhere .= ' AND ( tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable, $tableName);
527 // Be backwards compatible! When allowing more than one table after
528 // having previously allowed only one table, this case applies.
529 if ($this->currentTable == $this->MM_isMultiTableRelationship) {
530 $additionalWhere .= ' OR tablenames=\'\'';
531 }
532 $additionalWhere .= ' ) ';
533 }
534 $theTable = $this->MM_oppositeTable;
535 } else {
536 // Default
537 $uidLocal_field = 'uid_local';
538 $uidForeign_field = 'uid_foreign';
539 $sorting_field = 'sorting';
540 }
541 if ($this->MM_table_where) {
542 $additionalWhere .= LF . str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where);
543 }
544 foreach ($this->MM_match_fields as $field => $value) {
545 $additionalWhere .= ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $tableName);
546 }
547 // Select all MM relations:
548 $where = $uidLocal_field . '=' . (int)$uid . $additionalWhere;
549 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $tableName, $where, '', $sorting_field);
550 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
551 // Default
552 if (!$this->MM_is_foreign) {
553 // If tablesnames columns exists and contain a name, then this value is the table, else it's the firstTable...
554 $theTable = $row['tablenames'] ?: $this->firstTable;
555 }
556 if (($row[$uidForeign_field] || $theTable == 'pages') && $theTable && isset($this->tableArray[$theTable])) {
557 $this->itemArray[$key]['id'] = $row[$uidForeign_field];
558 $this->itemArray[$key]['table'] = $theTable;
559 $this->tableArray[$theTable][] = $row[$uidForeign_field];
560 } elseif ($this->registerNonTableValues) {
561 $this->itemArray[$key]['id'] = $row[$uidForeign_field];
562 $this->itemArray[$key]['table'] = '_NO_TABLE';
563 $this->nonTableArray[] = $row[$uidForeign_field];
564 }
565 $key++;
566 }
567 $GLOBALS['TYPO3_DB']->sql_free_result($res);
568 }
569
570 /**
571 * Writes the internal itemArray to MM table:
572 *
573 * @param string $MM_tableName MM table name
574 * @param integer $uid Local UID
575 * @param boolean $prependTableName If set, then table names will always be written.
576 * @return void
577 * @todo Define visibility
578 */
579 public function writeMM($MM_tableName, $uid, $prependTableName = FALSE) {
580 // In case of a reverse relation
581 if ($this->MM_is_foreign) {
582 $uidLocal_field = 'uid_foreign';
583 $uidForeign_field = 'uid_local';
584 $sorting_field = 'sorting_foreign';
585 } else {
586 // default
587 $uidLocal_field = 'uid_local';
588 $uidForeign_field = 'uid_foreign';
589 $sorting_field = 'sorting';
590 }
591 // If there are tables...
592 $tableC = count($this->tableArray);
593 if ($tableC) {
594 // Boolean: does the field "tablename" need to be filled?
595 $prep = $tableC > 1 || $prependTableName || $this->MM_isMultiTableRelationship ? 1 : 0;
596 $c = 0;
597 $additionalWhere_tablenames = '';
598 if ($this->MM_is_foreign && $prep) {
599 $additionalWhere_tablenames = ' AND tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable, $MM_tableName);
600 }
601 $additionalWhere = '';
602 // Add WHERE clause if configured
603 if ($this->MM_table_where) {
604 $additionalWhere .= LF . str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where);
605 }
606 // Select, update or delete only those relations that match the configured fields
607 foreach ($this->MM_match_fields as $field => $value) {
608 $additionalWhere .= ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $MM_tableName);
609 }
610 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
611 $uidForeign_field . ($prep ? ', tablenames' : '') . ($this->MM_hasUidField ? ', uid' : ''),
612 $MM_tableName,
613 $uidLocal_field . '=' . $uid . $additionalWhere_tablenames . $additionalWhere,
614 '',
615 $sorting_field
616 );
617 $oldMMs = array();
618 // This array is similar to $oldMMs but also holds the uid of the MM-records, if any (configured by MM_hasUidField).
619 // If the UID is present it will be used to update sorting and delete MM-records.
620 // This is necessary if the "multiple" feature is used for the MM relations.
621 // $oldMMs is still needed for the in_array() search used to look if an item from $this->itemArray is in $oldMMs
622 $oldMMs_inclUid = array();
623 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
624 if (!$this->MM_is_foreign && $prep) {
625 $oldMMs[] = array($row['tablenames'], $row[$uidForeign_field]);
626 } else {
627 $oldMMs[] = $row[$uidForeign_field];
628 }
629 $oldMMs_inclUid[] = array($row['tablenames'], $row[$uidForeign_field], $row['uid']);
630 }
631 $GLOBALS['TYPO3_DB']->sql_free_result($res);
632 // For each item, insert it:
633 foreach ($this->itemArray as $val) {
634 $c++;
635 if ($prep || $val['table'] == '_NO_TABLE') {
636 // Insert current table if needed
637 if ($this->MM_is_foreign) {
638 $tablename = $this->currentTable;
639 } else {
640 $tablename = $val['table'];
641 }
642 } else {
643 $tablename = '';
644 }
645 if (!$this->MM_is_foreign && $prep) {
646 $item = array($val['table'], $val['id']);
647 } else {
648 $item = $val['id'];
649 }
650 if (in_array($item, $oldMMs)) {
651 $oldMMs_index = array_search($item, $oldMMs);
652 // In principle, selecting on the UID is all we need to do
653 // if a uid field is available since that is unique!
654 // But as long as it "doesn't hurt" we just add it to the where clause. It should all match up.
655 $whereClause = $uidLocal_field . '=' . $uid . ' AND ' . $uidForeign_field . '=' . $val['id']
656 . ($this->MM_hasUidField ? ' AND uid=' . (int)$oldMMs_inclUid[$oldMMs_index][2] : '');
657 if ($tablename) {
658 $whereClause .= ' AND tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tablename, $MM_tableName);
659 }
660 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($MM_tableName, $whereClause . $additionalWhere, array($sorting_field => $c));
661 // Remove the item from the $oldMMs array so after this
662 // foreach loop only the ones that need to be deleted are in there.
663 unset($oldMMs[$oldMMs_index]);
664 // Remove the item from the $oldMMs_inclUid array so after this
665 // foreach loop only the ones that need to be deleted are in there.
666 unset($oldMMs_inclUid[$oldMMs_index]);
667 } else {
668 $insertFields = $this->MM_insert_fields;
669 $insertFields[$uidLocal_field] = $uid;
670 $insertFields[$uidForeign_field] = $val['id'];
671 $insertFields[$sorting_field] = $c;
672 if ($tablename) {
673 $insertFields['tablenames'] = $tablename;
674 $insertFields = $this->completeOppositeUsageValues($tablename, $insertFields);
675 }
676 $GLOBALS['TYPO3_DB']->exec_INSERTquery($MM_tableName, $insertFields);
677 if ($this->MM_is_foreign) {
678 $this->updateRefIndex($val['table'], $val['id']);
679 }
680 }
681 }
682 // Delete all not-used relations:
683 if (is_array($oldMMs) && count($oldMMs) > 0) {
684 $removeClauses = array();
685 $updateRefIndex_records = array();
686 foreach ($oldMMs as $oldMM_key => $mmItem) {
687 // If UID field is present, of course we need only use that for deleting.
688 if ($this->MM_hasUidField) {
689 $removeClauses[] = 'uid=' . (int)$oldMMs_inclUid[$oldMM_key][2];
690 } else {
691 if (is_array($mmItem)) {
692 $removeClauses[] = 'tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($mmItem[0], $MM_tableName)
693 . ' AND ' . $uidForeign_field . '=' . $mmItem[1];
694 } else {
695 $removeClauses[] = $uidForeign_field . '=' . $mmItem;
696 }
697 }
698 if ($this->MM_is_foreign) {
699 if (is_array($mmItem)) {
700 $updateRefIndex_records[] = array($mmItem[0], $mmItem[1]);
701 } else {
702 $updateRefIndex_records[] = array($this->firstTable, $mmItem);
703 }
704 }
705 }
706 $deleteAddWhere = ' AND (' . implode(' OR ', $removeClauses) . ')';
707 $where = $uidLocal_field . '=' . (int)$uid . $deleteAddWhere . $additionalWhere_tablenames . $additionalWhere;
708 $GLOBALS['TYPO3_DB']->exec_DELETEquery($MM_tableName, $where);
709 // Update ref index:
710 foreach ($updateRefIndex_records as $pair) {
711 $this->updateRefIndex($pair[0], $pair[1]);
712 }
713 }
714 // Update ref index; In tcemain it is not certain that this will happen because
715 // if only the MM field is changed the record itself is not updated and so the ref-index is not either.
716 // This could also have been fixed in updateDB in tcemain, however I decided to do it here ...
717 $this->updateRefIndex($this->currentTable, $uid);
718 }
719 }
720
721 /**
722 * Remaps MM table elements from one local uid to another
723 * Does NOT update the reference index for you, must be called subsequently to do that!
724 *
725 * @param string $MM_tableName MM table name
726 * @param integer $uid Local, current UID
727 * @param integer $newUid Local, new UID
728 * @param boolean $prependTableName If set, then table names will always be written.
729 * @return void
730 * @todo Define visibility
731 */
732 public function remapMM($MM_tableName, $uid, $newUid, $prependTableName = FALSE) {
733 // In case of a reverse relation
734 if ($this->MM_is_foreign) {
735 $uidLocal_field = 'uid_foreign';
736 } else {
737 // default
738 $uidLocal_field = 'uid_local';
739 }
740 // If there are tables...
741 $tableC = count($this->tableArray);
742 if ($tableC) {
743 // Boolean: does the field "tablename" need to be filled?
744 $prep = $tableC > 1 || $prependTableName || $this->MM_isMultiTableRelationship;
745 $additionalWhere_tablenames = '';
746 if ($this->MM_is_foreign && $prep) {
747 $additionalWhere_tablenames = ' AND tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable, $MM_tableName);
748 }
749 $additionalWhere = '';
750 // Add WHERE clause if configured
751 if ($this->MM_table_where) {
752 $additionalWhere .= LF . str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where);
753 }
754 // Select, update or delete only those relations that match the configured fields
755 foreach ($this->MM_match_fields as $field => $value) {
756 $additionalWhere .= ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $MM_tableName);
757 }
758 $where = $uidLocal_field . '=' . (int)$uid . $additionalWhere_tablenames . $additionalWhere;
759 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($MM_tableName, $where, array($uidLocal_field => $newUid));
760 }
761 }
762
763 /**
764 * Reads items from a foreign_table, that has a foreign_field (uid of the parent record) and
765 * stores the parts in the internal array itemArray and tableArray.
766 *
767 * @param integer $uid The uid of the parent record (this value is also on the foreign_table in the foreign_field)
768 * @param array $conf TCA configuration for current field
769 * @return void
770 * @todo Define visibility
771 */
772 public function readForeignField($uid, $conf) {
773 if ($this->useLiveParentIds) {
774 $uid = $this->getLiveDefaultId($this->currentTable, $uid);
775 }
776
777 $key = 0;
778 $uid = (int)$uid;
779 $foreign_table = $conf['foreign_table'];
780 $foreign_table_field = $conf['foreign_table_field'];
781 $useDeleteClause = !$this->undeleteRecord;
782 $foreign_match_fields = is_array($conf['foreign_match_fields']) ? $conf['foreign_match_fields'] : array();
783 // Search for $uid in foreign_field, and if we have symmetric relations, do this also on symmetric_field
784 if ($conf['symmetric_field']) {
785 $whereClause = '(' . $conf['foreign_field'] . '=' . $uid . ' OR ' . $conf['symmetric_field'] . '=' . $uid . ')';
786 } else {
787 $whereClause = $conf['foreign_field'] . '=' . $uid;
788 }
789 // Use the deleteClause (e.g. "deleted=0") on this table
790 if ($useDeleteClause) {
791 $whereClause .= BackendUtility::deleteClause($foreign_table);
792 }
793 // If it's requested to look for the parent uid AND the parent table,
794 // add an additional SQL-WHERE clause
795 if ($foreign_table_field && $this->currentTable) {
796 $whereClause .= ' AND ' . $foreign_table_field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable, $foreign_table);
797 }
798 // Add additional where clause if foreign_match_fields are defined
799 foreach ($foreign_match_fields as $field => $value) {
800 $whereClause .= ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $foreign_table);
801 }
802 // Select children from the live(!) workspace only
803 if (BackendUtility::isTableWorkspaceEnabled($foreign_table)) {
804 $workspaceList = '0,' . $this->getWorkspaceId();
805 $whereClause .= ' AND ' . $foreign_table . '.t3ver_wsid IN (' . $workspaceList . ') AND ' . $foreign_table . '.pid<>-1';
806 }
807 // Get the correct sorting field
808 // Specific manual sortby for data handled by this field
809 $sortby = '';
810 if ($conf['foreign_sortby']) {
811 if ($conf['symmetric_sortby'] && $conf['symmetric_field']) {
812 // Sorting depends on, from which side of the relation we're looking at it
813 $sortby = '
814 CASE
815 WHEN ' . $conf['foreign_field'] . '=' . $uid . '
816 THEN ' . $conf['foreign_sortby'] . '
817 ELSE ' . $conf['symmetric_sortby'] . '
818 END';
819 } else {
820 // Regular single-side behaviour
821 $sortby = $conf['foreign_sortby'];
822 }
823 } elseif ($conf['foreign_default_sortby']) {
824 // Specific default sortby for data handled by this field
825 $sortby = $conf['foreign_default_sortby'];
826 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) {
827 // Manual sortby for all table records
828 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
829 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby']) {
830 // Default sortby for all table records
831 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby'];
832 }
833 // Strip a possible "ORDER BY" in front of the $sortby value
834 $sortby = $GLOBALS['TYPO3_DB']->stripOrderBy($sortby);
835 // Get the rows from storage
836 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', $foreign_table, $whereClause, '', $sortby, '', 'uid');
837 if (count($rows)) {
838 if (BackendUtility::isTableWorkspaceEnabled($foreign_table) && !$this->useLiveReferenceIds) {
839 $rows = $this->getRecordVersionsIds($foreign_table, $rows);
840 }
841 foreach ($rows as $row) {
842 $this->itemArray[$key]['id'] = $row['uid'];
843 $this->itemArray[$key]['table'] = $foreign_table;
844 $this->tableArray[$foreign_table][] = $row['uid'];
845 $key++;
846 }
847 }
848 }
849
850 /**
851 * Write the sorting values to a foreign_table, that has a foreign_field (uid of the parent record)
852 *
853 * @param array $conf TCA configuration for current field
854 * @param integer $parentUid The uid of the parent record
855 * @param integer $updateToUid If this is larger than zero it will be used as foreign UID instead of the given $parentUid (on Copy)
856 * @param boolean $skipSorting Do not update the sorting columns, this could happen for imported values
857 * @return void
858 * @todo Define visibility
859 */
860 public function writeForeignField($conf, $parentUid, $updateToUid = 0, $skipSorting = FALSE) {
861 if ($this->useLiveParentIds) {
862 $parentUid = $this->getLiveDefaultId($this->currentTable, $parentUid);
863 if (!empty($updateToUid)) {
864 $updateToUid = $this->getLiveDefaultId($this->currentTable, $updateToUid);
865 }
866 }
867
868 $c = 0;
869 $foreign_table = $conf['foreign_table'];
870 $foreign_field = $conf['foreign_field'];
871 $symmetric_field = $conf['symmetric_field'];
872 $foreign_table_field = $conf['foreign_table_field'];
873 $foreign_match_fields = is_array($conf['foreign_match_fields']) ? $conf['foreign_match_fields'] : array();
874 // If there are table items and we have a proper $parentUid
875 if (MathUtility::canBeInterpretedAsInteger($parentUid) && count($this->tableArray)) {
876 // If updateToUid is not a positive integer, set it to '0', so it will be ignored
877 if (!(MathUtility::canBeInterpretedAsInteger($updateToUid) && $updateToUid > 0)) {
878 $updateToUid = 0;
879 }
880 $considerWorkspaces = ($GLOBALS['BE_USER']->workspace !== 0 && BackendUtility::isTableWorkspaceEnabled($foreign_table));
881 $fields = 'uid,pid,' . $foreign_field;
882 // Consider the symmetric field if defined:
883 if ($symmetric_field) {
884 $fields .= ',' . $symmetric_field;
885 }
886 // Consider workspaces if defined and currently used:
887 if ($considerWorkspaces) {
888 $fields .= ',t3ver_wsid,t3ver_state,t3ver_oid';
889 }
890 // Update all items
891 foreach ($this->itemArray as $val) {
892 $uid = $val['id'];
893 $table = $val['table'];
894 $row = array();
895 // Fetch the current (not overwritten) relation record if we should handle symmetric relations
896 if ($symmetric_field || $considerWorkspaces) {
897 $row = BackendUtility::getRecord($table, $uid, $fields, '', FALSE);
898 }
899 $isOnSymmetricSide = FALSE;
900 if ($symmetric_field) {
901 $isOnSymmetricSide = self::isOnSymmetricSide($parentUid, $conf, $row);
902 }
903 $updateValues = $foreign_match_fields;
904 // No update to the uid is requested, so this is the normal behaviour
905 // just update the fields and care about sorting
906 if (!$updateToUid) {
907 // Always add the pointer to the parent uid
908 if ($isOnSymmetricSide) {
909 $updateValues[$symmetric_field] = $parentUid;
910 } else {
911 $updateValues[$foreign_field] = $parentUid;
912 }
913 // If it is configured in TCA also to store the parent table in the child record, just do it
914 if ($foreign_table_field && $this->currentTable) {
915 $updateValues[$foreign_table_field] = $this->currentTable;
916 }
917 // Update sorting columns if not to be skipped
918 if (!$skipSorting) {
919 // Get the correct sorting field
920 // Specific manual sortby for data handled by this field
921 $sortby = '';
922 if ($conf['foreign_sortby']) {
923 $sortby = $conf['foreign_sortby'];
924 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) {
925 // manual sortby for all table records
926 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
927 }
928 // Apply sorting on the symmetric side
929 // (it depends on who created the relation, so what uid is in the symmetric_field):
930 if ($isOnSymmetricSide && isset($conf['symmetric_sortby']) && $conf['symmetric_sortby']) {
931 $sortby = $conf['symmetric_sortby'];
932 } else {
933 $sortby = $GLOBALS['TYPO3_DB']->stripOrderBy($sortby);
934 }
935 if ($sortby) {
936 $updateValues[$sortby] = ++$c;
937 }
938 }
939 } else {
940 if ($isOnSymmetricSide) {
941 $updateValues[$symmetric_field] = $updateToUid;
942 } else {
943 $updateValues[$foreign_field] = $updateToUid;
944 }
945 }
946 // Update accordant fields in the database:
947 if (count($updateValues)) {
948 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$uid, $updateValues);
949 $this->updateRefIndex($table, $uid);
950 }
951 // Update accordant fields in the database for workspaces overlays/placeholders:
952 if ($considerWorkspaces) {
953 // It's the specific versioned record -> update placeholder (if any)
954 if (!empty($row['t3ver_oid']) && VersionState::cast($row['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER_VERSION)) {
955 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . (int)$row['t3ver_oid'], $updateValues);
956 }
957 }
958 }
959 }
960 }
961
962 /**
963 * After initialization you can extract an array of the elements from the object. Use this function for that.
964 *
965 * @param boolean $prependTableName If set, then table names will ALWAYS be prepended (unless its a _NO_TABLE value)
966 * @return array A numeric array.
967 * @todo Define visibility
968 */
969 public function getValueArray($prependTableName = FALSE) {
970 // INIT:
971 $valueArray = array();
972 $tableC = count($this->tableArray);
973 // If there are tables in the table array:
974 if ($tableC) {
975 // If there are more than ONE table in the table array, then always prepend table names:
976 $prep = $tableC > 1 || $prependTableName;
977 // Traverse the array of items:
978 foreach ($this->itemArray as $val) {
979 $valueArray[] = ($prep && $val['table'] != '_NO_TABLE' ? $val['table'] . '_' : '') . $val['id'];
980 }
981 }
982 // Return the array
983 return $valueArray;
984 }
985
986 /**
987 * Converts id numbers from negative to positive.
988 *
989 * @param array $valueArray Array of [table]_[id] pairs.
990 * @param string $fTable Foreign table (the one used for positive numbers)
991 * @param string $nfTable Negative foreign table
992 * @return array The array with ID integer values, converted to positive for those where the table name was set but did NOT match the positive foreign table.
993 * @todo Define visibility
994 */
995 public function convertPosNeg($valueArray, $fTable, $nfTable) {
996 if (is_array($valueArray) && $fTable) {
997 foreach ($valueArray as $key => $val) {
998 $val = strrev($val);
999 $parts = explode('_', $val, 2);
1000 $theID = strrev($parts[0]);
1001 $theTable = strrev($parts[1]);
1002 if (MathUtility::canBeInterpretedAsInteger($theID)
1003 && (!$theTable || $theTable === (string)$fTable || $theTable === (string)$nfTable)
1004 ) {
1005 $valueArray[$key] = $theTable && $theTable !== (string)$fTable ? $theID * -1 : $theID;
1006 }
1007 }
1008 }
1009 return $valueArray;
1010 }
1011
1012 /**
1013 * Reads all records from internal tableArray into the internal ->results array
1014 * where keys are table names and for each table, records are stored with uids as their keys.
1015 * If $this->fetchAllFields is false you can save a little memory
1016 * since only uid,pid and a few other fields are selected.
1017 *
1018 * @return array
1019 * @todo Define visibility
1020 */
1021 public function getFromDB() {
1022 // Traverses the tables listed:
1023 foreach ($this->tableArray as $key => $val) {
1024 if (is_array($val)) {
1025 $itemList = implode(',', $val);
1026 if ($itemList) {
1027 if ($this->fetchAllFields) {
1028 $from = '*';
1029 } else {
1030 $from = 'uid,pid';
1031 if ($GLOBALS['TCA'][$key]['ctrl']['label']) {
1032 // Titel
1033 $from .= ',' . $GLOBALS['TCA'][$key]['ctrl']['label'];
1034 }
1035 if ($GLOBALS['TCA'][$key]['ctrl']['label_alt']) {
1036 // Alternative Title-Fields
1037 $from .= ',' . $GLOBALS['TCA'][$key]['ctrl']['label_alt'];
1038 }
1039 if ($GLOBALS['TCA'][$key]['ctrl']['thumbnail']) {
1040 // Thumbnail
1041 $from .= ',' . $GLOBALS['TCA'][$key]['ctrl']['thumbnail'];
1042 }
1043 }
1044 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($from, $key, 'uid IN (' . $itemList . ')' . $this->additionalWhere[$key]);
1045 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1046 $this->results[$key][$row['uid']] = $row;
1047 }
1048 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1049 }
1050 }
1051 }
1052 return $this->results;
1053 }
1054
1055 /**
1056 * Prepare items from itemArray to be transferred to the TCEforms interface (as a comma list)
1057 *
1058 * @return string
1059 * @todo Define visibility
1060 */
1061 public function readyForInterface() {
1062 if (!is_array($this->itemArray)) {
1063 return FALSE;
1064 }
1065 $output = array();
1066 $titleLen = (int)$GLOBALS['BE_USER']->uc['titleLen'];
1067 foreach ($this->itemArray as $val) {
1068 $theRow = $this->results[$val['table']][$val['id']];
1069 if ($theRow && is_array($GLOBALS['TCA'][$val['table']])) {
1070 $label = GeneralUtility::fixed_lgd_cs(strip_tags(
1071 BackendUtility::getRecordTitle($val['table'], $theRow)), $titleLen);
1072 $label = $label ? $label : '[...]';
1073 $output[] = str_replace(',', '', $val['table'] . '_' . $val['id'] . '|' . rawurlencode($label));
1074 }
1075 }
1076 return implode(',', $output);
1077 }
1078
1079 /**
1080 * Counts the items in $this->itemArray and puts this value in an array by default.
1081 *
1082 * @param boolean $returnAsArray Whether to put the count value in an array
1083 * @return mixed The plain count as integer or the same inside an array
1084 * @todo Define visibility
1085 */
1086 public function countItems($returnAsArray = TRUE) {
1087 $count = count($this->itemArray);
1088 if ($returnAsArray) {
1089 $count = array($count);
1090 }
1091 return $count;
1092 }
1093
1094 /**
1095 * Update Reference Index (sys_refindex) for a record
1096 * Should be called any almost any update to a record which could affect references inside the record.
1097 * (copied from TCEmain)
1098 *
1099 * @param string $table Table name
1100 * @param integer $id Record UID
1101 * @return array Information concerning modifications delivered by \TYPO3\CMS\Core\Database\ReferenceIndex::updateRefIndexTable()
1102 * @todo Define visibility
1103 */
1104 public function updateRefIndex($table, $id) {
1105 $statisticsArray = array();
1106 if ($this->updateReferenceIndex) {
1107 /** @var $refIndexObj \TYPO3\CMS\Core\Database\ReferenceIndex */
1108 $refIndexObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\ReferenceIndex');
1109 if (BackendUtility::isTableWorkspaceEnabled($table)) {
1110 $refIndexObj->setWorkspaceId($this->getWorkspaceId());
1111 }
1112 $statisticsArray = $refIndexObj->updateRefIndexTable($table, $id);
1113 }
1114 return $statisticsArray;
1115 }
1116
1117 /**
1118 * @param NULL|int $workspaceId
1119 * @return bool Whether items have been purged
1120 */
1121 public function purgeItemArray($workspaceId = NULL) {
1122 if ($workspaceId === NULL) {
1123 $workspaceId = $this->getWorkspaceId();
1124 } else {
1125 $workspaceId = (int)$workspaceId;
1126 }
1127
1128 // Ensure, only live relations are in the items Array
1129 if ($workspaceId === 0) {
1130 $purgeCallback = 'purgeVersionedIds';
1131 // Otherwise, ensure that live relations are purged if version exists
1132 } else {
1133 $purgeCallback = 'purgeLiveVersionedIds';
1134 }
1135
1136 $itemArrayHasBeenPurged = $this->purgeItemArrayHandler($purgeCallback);
1137 $this->purged = ($this->purged || $itemArrayHasBeenPurged);
1138 return $itemArrayHasBeenPurged;
1139 }
1140
1141 /**
1142 * Removes items having a delete placeholder from $this->itemArray
1143 *
1144 * @return bool Whether items have been purged
1145 */
1146 public function processDeletePlaceholder() {
1147 if (!$this->useLiveReferenceIds || $this->getWorkspaceId() === 0) {
1148 return FALSE;
1149 }
1150
1151 return $this->purgeItemArrayHandler('purgeDeletePlaceholder');
1152 }
1153
1154 /**
1155 * Handles a purge callback on $this->itemArray
1156 *
1157 * @param callable $purgeCallback
1158 * @return bool Whether items have been purged
1159 */
1160 protected function purgeItemArrayHandler($purgeCallback) {
1161 $itemArrayHasBeenPurged = FALSE;
1162
1163 foreach ($this->tableArray as $itemTableName => $itemIds) {
1164 if (!count($itemIds) || !BackendUtility::isTableWorkspaceEnabled($itemTableName)) {
1165 continue;
1166 }
1167
1168 $purgedItemIds = call_user_func(array($this, $purgeCallback), $itemTableName, $itemIds);
1169 $removedItemIds = array_diff($itemIds, $purgedItemIds);
1170 foreach ($removedItemIds as $removedItemId) {
1171 $this->removeFromItemArray($itemTableName, $removedItemId);
1172 }
1173 $this->tableArray[$itemTableName] = $purgedItemIds;
1174 if (count($removedItemIds)) {
1175 $itemArrayHasBeenPurged = TRUE;
1176 }
1177 }
1178
1179 return $itemArrayHasBeenPurged;
1180 }
1181
1182 /**
1183 * Purges ids that are versioned.
1184 *
1185 * @param string $tableName
1186 * @param array $ids
1187 * @return array
1188 */
1189 protected function purgeVersionedIds($tableName, array $ids) {
1190 $ids = $this->getDatabaseConnection()->cleanIntArray($ids);
1191 $ids = array_combine($ids, $ids);
1192
1193 $versions = $this->getDatabaseConnection()->exec_SELECTgetRows(
1194 'uid,t3ver_oid,t3ver_state',
1195 $tableName,
1196 'pid=-1 AND t3ver_oid IN (' . implode(',', $ids) . ') AND t3ver_wsid<>0',
1197 '',
1198 't3ver_state DESC'
1199 );
1200
1201 if (!empty($versions)) {
1202 foreach ($versions as $version) {
1203 $versionId = $version['uid'];
1204 if (isset($ids[$versionId])) {
1205 unset($ids[$versionId]);
1206 }
1207 }
1208 }
1209
1210 return array_values($ids);
1211 }
1212
1213 /**
1214 * Purges ids that are live but have an accordant version.
1215 *
1216 * @param string $tableName
1217 * @param array $ids
1218 * @return array
1219 */
1220 protected function purgeLiveVersionedIds($tableName, array $ids) {
1221 $ids = $this->getDatabaseConnection()->cleanIntArray($ids);
1222 $ids = array_combine($ids, $ids);
1223
1224 $versions = $this->getDatabaseConnection()->exec_SELECTgetRows(
1225 'uid,t3ver_oid,t3ver_state',
1226 $tableName,
1227 'pid=-1 AND t3ver_oid IN (' . implode(',', $ids) . ') AND t3ver_wsid<>0',
1228 '',
1229 't3ver_state DESC'
1230 );
1231
1232 if (!empty($versions)) {
1233 foreach ($versions as $version) {
1234 $versionId = $version['uid'];
1235 $liveId = $version['t3ver_oid'];
1236 if (isset($ids[$liveId]) && isset($ids[$versionId])) {
1237 unset($ids[$liveId]);
1238 }
1239 }
1240 }
1241
1242 return array_values($ids);
1243 }
1244
1245 /**
1246 * Purges ids that have a delete placeholder
1247 *
1248 * @param string $tableName
1249 * @param array $ids
1250 * @return array
1251 */
1252 protected function purgeDeletePlaceholder($tableName, array $ids) {
1253 $ids = $this->getDatabaseConnection()->cleanIntArray($ids);
1254 $ids = array_combine($ids, $ids);
1255
1256 $versions = $this->getDatabaseConnection()->exec_SELECTgetRows(
1257 'uid,t3ver_oid,t3ver_state',
1258 $tableName,
1259 'pid=-1 AND t3ver_oid IN (' . implode(',', $ids) . ') AND t3ver_wsid=' . $this->getWorkspaceId() .
1260 ' AND t3ver_state=' . VersionState::cast(VersionState::DELETE_PLACEHOLDER)
1261 );
1262
1263 if (!empty($versions)) {
1264 foreach ($versions as $version) {
1265 $liveId = $version['t3ver_oid'];
1266 if (isset($ids[$liveId])) {
1267 unset($ids[$liveId]);
1268 }
1269 }
1270 }
1271
1272 return array_values($ids);
1273 }
1274
1275 protected function removeFromItemArray($tableName, $id) {
1276 foreach ($this->itemArray as $index => $item) {
1277 if ($item['table'] === $tableName && (string)$item['id'] === (string)$id) {
1278 unset($this->itemArray[$index]);
1279 return TRUE;
1280 }
1281 }
1282 return FALSE;
1283 }
1284
1285 /**
1286 * Checks, if we're looking from the "other" side, the symmetric side, to a symmetric relation.
1287 *
1288 * @param string $parentUid The uid of the parent record
1289 * @param array $parentConf The TCA configuration of the parent field embedding the child records
1290 * @param array $childRec The record row of the child record
1291 * @return boolean Returns TRUE if looking from the symmetric ("other") side to the relation.
1292 * @todo Define visibility
1293 */
1294 static public function isOnSymmetricSide($parentUid, $parentConf, $childRec) {
1295 return MathUtility::canBeInterpretedAsInteger($childRec['uid'])
1296 && $parentConf['symmetric_field']
1297 && $parentUid == $childRec[$parentConf['symmetric_field']];
1298 }
1299
1300 /**
1301 * Completes MM values to be written by values from the opposite relation.
1302 * This method used MM insert field or MM match fields if defined.
1303 *
1304 * @param string $tableName Name of the opposite table
1305 * @param array $referenceValues Values to be written
1306 * @return array Values to be written, possibly modified
1307 */
1308 protected function completeOppositeUsageValues($tableName, array $referenceValues) {
1309 if (empty($this->MM_oppositeUsage[$tableName]) || count($this->MM_oppositeUsage[$tableName]) > 1) {
1310 return $referenceValues;
1311 }
1312
1313 $fieldName = $this->MM_oppositeUsage[$tableName][0];
1314 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1315 return $referenceValues;
1316 }
1317
1318 $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1319 if (!empty($configuration['MM_insert_fields'])) {
1320 $referenceValues = array_merge($configuration['MM_insert_fields'], $referenceValues);
1321 } elseif (!empty($configuration['MM_match_fields'])) {
1322 $referenceValues = array_merge($configuration['MM_match_fields'], $referenceValues);
1323 }
1324
1325 return $referenceValues;
1326 }
1327
1328 /**
1329 * @param string $tableName
1330 * @param array $records
1331 * @return array
1332 */
1333 protected function getRecordVersionsIds($tableName, array $records) {
1334 $workspaceId = (int)$GLOBALS['BE_USER']->workspace;
1335 $liveIds = array_map('intval', $this->extractValues($records, 'uid'));
1336 $liveIdList = implode(',', $liveIds);
1337
1338 if (BackendUtility::isTableMovePlaceholderAware($tableName)) {
1339 $versions = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
1340 'uid,t3ver_move_id',
1341 $tableName,
1342 't3ver_state=3 AND t3ver_wsid=' . $workspaceId . ' AND t3ver_move_id IN (' . $liveIdList . ')'
1343 );
1344
1345 if (!empty($versions)) {
1346 foreach ($versions as $version) {
1347 $liveReferenceId = $version['t3ver_move_id'];
1348 $movePlaceholderId = $version['uid'];
1349 if (isset($records[$liveReferenceId]) && $records[$movePlaceholderId]) {
1350 $records[$movePlaceholderId] = $records[$liveReferenceId];
1351 unset($records[$liveReferenceId]);
1352 }
1353 }
1354 $liveIds = array_map('intval', $this->extractValues($records, 'uid'));
1355 $records = array_combine($liveIds, array_values($records));
1356 $liveIdList = implode(',', $liveIds);
1357 }
1358 }
1359
1360 $versions = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
1361 'uid,t3ver_oid,t3ver_state',
1362 $tableName,
1363 'pid=-1 AND t3ver_oid IN (' . $liveIdList . ') AND t3ver_wsid=' . $workspaceId,
1364 '',
1365 't3ver_state DESC'
1366 );
1367
1368 if (!empty($versions)) {
1369 foreach ($versions as $version) {
1370 $liveId = $version['t3ver_oid'];
1371 if (isset($records[$liveId])) {
1372 $records[$liveId] = $version;
1373 }
1374 }
1375 }
1376
1377 return $records;
1378 }
1379
1380 /**
1381 * @param array $array
1382 * @param string $fieldName
1383 * @return array
1384 */
1385 protected function extractValues(array $array, $fieldName) {
1386 $values = array();
1387 foreach ($array as $item) {
1388 $values[] = $item[$fieldName];
1389 }
1390 return $values;
1391 }
1392
1393 /**
1394 * Gets the record uid of the live default record. If already
1395 * pointing to the live record, the submitted record uid is returned.
1396 *
1397 * @param string $tableName
1398 * @param int $id
1399 * @return int
1400 */
1401 protected function getLiveDefaultId($tableName, $id) {
1402 $liveDefaultId = BackendUtility::getLiveVersionIdOfRecord($tableName, $id);
1403 if ($liveDefaultId === NULL) {
1404 $liveDefaultId = $id;
1405 }
1406 return (int)$liveDefaultId;
1407 }
1408
1409 /**
1410 * @return DatabaseConnection
1411 */
1412 protected function getDatabaseConnection() {
1413 return $GLOBALS['TYPO3_DB'];
1414 }
1415
1416 }