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