[TASK] Doctrine: Migrate RelationHandler
[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 = array();
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 = array();
60
61 /**
62 * Array for NON-table elements
63 *
64 * @var array
65 */
66 public $nonTableArray = array();
67
68 /**
69 * @var array
70 */
71 public $additionalWhere = array();
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 = array();
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 = array();
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 = array();
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 = array();
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 = array())
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'] : array();
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] = array();
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 = array();
452 $foreignTable = $configuration['foreign_table'];
453 $ids = $this->getResolver($foreignTable, $this->tableArray[$foreignTable])->get();
454 foreach ($ids as $id) {
455 $this->itemArray[] = array(
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 = array();
488 $this->tableArray = array();
489 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
490 $queryBuilder->getRestrictions()->removeAll();
491 $queryBuilder->select('uid')
492 ->from($table)
493 ->where(
494 $queryBuilder->expr()->in('uid', GeneralUtility::intExplode(',', $uidList))
495 );
496 foreach (QueryHelper::parseOrderBy((string)$sortby) as $orderPair) {
497 list($fieldName, $order) = $orderPair;
498 $queryBuilder->addOrderBy($fieldName, $order);
499 }
500 $statement = $queryBuilder->execute();
501 while ($row = $statement->fetch()) {
502 $this->itemArray[] = array('id' => $row['uid'], 'table' => $table);
503 $this->tableArray[$table][] = $row['uid'];
504 }
505 }
506 }
507 }
508
509 /**
510 * Reads the record tablename/id into the internal arrays itemArray and tableArray from MM records.
511 * You can call this function after start if you supply no list to start()
512 *
513 * @param string $tableName MM Tablename
514 * @param int $uid Local UID
515 * @return void
516 */
517 public function readMM($tableName, $uid)
518 {
519 $key = 0;
520 $theTable = null;
521 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
522 $queryBuilder->getRestrictions()->removeAll();
523 $queryBuilder->select('*')->from($tableName);
524 // In case of a reverse relation
525 if ($this->MM_is_foreign) {
526 $uidLocal_field = 'uid_foreign';
527 $uidForeign_field = 'uid_local';
528 $sorting_field = 'sorting_foreign';
529 if ($this->MM_isMultiTableRelationship) {
530 // Be backwards compatible! When allowing more than one table after
531 // having previously allowed only one table, this case applies.
532 if ($this->currentTable == $this->MM_isMultiTableRelationship) {
533 $expression = $queryBuilder->expr()->orX(
534 $queryBuilder->expr()->eq('tablenames', $queryBuilder->createNamedParameter($this->currentTable)),
535 $queryBuilder->expr()->eq('tablenames', $queryBuilder->createNamedParameter(''))
536 );
537 } else {
538 $expression = $queryBuilder->expr()->eq('tablenames', $queryBuilder->createNamedParameter($this->currentTable));
539 }
540 $queryBuilder->andWhere($expression);
541 }
542 $theTable = $this->MM_oppositeTable;
543 } else {
544 // Default
545 $uidLocal_field = 'uid_local';
546 $uidForeign_field = 'uid_foreign';
547 $sorting_field = 'sorting';
548 }
549 if ($this->MM_table_where) {
550 $queryBuilder->andWhere(
551 QueryHelper::stripLogicalOperatorPrefix(str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where))
552 );
553 }
554 foreach ($this->MM_match_fields as $field => $value) {
555 $queryBuilder->andWhere(
556 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($value))
557 );
558 }
559 $queryBuilder->andWhere(
560 $queryBuilder->expr()->eq($uidLocal_field, (int)$uid)
561 );
562 $queryBuilder->orderBy($sorting_field);
563 $statement = $queryBuilder->execute();
564 while ($row = $statement->fetch()) {
565 // Default
566 if (!$this->MM_is_foreign) {
567 // If tablesnames columns exists and contain a name, then this value is the table, else it's the firstTable...
568 $theTable = $row['tablenames'] ?: $this->firstTable;
569 }
570 if (($row[$uidForeign_field] || $theTable == 'pages') && $theTable && isset($this->tableArray[$theTable])) {
571 $this->itemArray[$key]['id'] = $row[$uidForeign_field];
572 $this->itemArray[$key]['table'] = $theTable;
573 $this->tableArray[$theTable][] = $row[$uidForeign_field];
574 } elseif ($this->registerNonTableValues) {
575 $this->itemArray[$key]['id'] = $row[$uidForeign_field];
576 $this->itemArray[$key]['table'] = '_NO_TABLE';
577 $this->nonTableArray[] = $row[$uidForeign_field];
578 }
579 $key++;
580 }
581 }
582
583 /**
584 * Writes the internal itemArray to MM table:
585 *
586 * @param string $MM_tableName MM table name
587 * @param int $uid Local UID
588 * @param bool $prependTableName If set, then table names will always be written.
589 * @return void
590 */
591 public function writeMM($MM_tableName, $uid, $prependTableName = false)
592 {
593 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($MM_tableName);
594 $expressionBuilder = $connection->createQueryBuilder()->expr();
595
596 // In case of a reverse relation
597 if ($this->MM_is_foreign) {
598 $uidLocal_field = 'uid_foreign';
599 $uidForeign_field = 'uid_local';
600 $sorting_field = 'sorting_foreign';
601 } else {
602 // default
603 $uidLocal_field = 'uid_local';
604 $uidForeign_field = 'uid_foreign';
605 $sorting_field = 'sorting';
606 }
607 // If there are tables...
608 $tableC = count($this->tableArray);
609 if ($tableC) {
610 // Boolean: does the field "tablename" need to be filled?
611 $prep = $tableC > 1 || $prependTableName || $this->MM_isMultiTableRelationship ? 1 : 0;
612 $c = 0;
613 $additionalWhere_tablenames = '';
614 if ($this->MM_is_foreign && $prep) {
615 $additionalWhere_tablenames = $expressionBuilder->eq(
616 'tablenames',
617 $expressionBuilder->literal($this->currentTable)
618 );
619 }
620 $additionalWhere = $expressionBuilder->andX();
621 // Add WHERE clause if configured
622 if ($this->MM_table_where) {
623 $additionalWhere->add(
624 QueryHelper::stripLogicalOperatorPrefix(
625 str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where)
626 )
627 );
628 }
629 // Select, update or delete only those relations that match the configured fields
630 foreach ($this->MM_match_fields as $field => $value) {
631 $additionalWhere->add($expressionBuilder->eq($field, $expressionBuilder->literal($value)));
632 }
633
634 $queryBuilder = $connection->createQueryBuilder();
635 $queryBuilder->getRestrictions()->removeAll();
636 $queryBuilder->select($uidForeign_field)
637 ->from($MM_tableName)
638 ->where($queryBuilder->expr()->eq($uidLocal_field, (int)$uid))
639 ->orderBy($sorting_field);
640
641 if ($prep) {
642 $queryBuilder->addSelect('tablenames');
643 }
644 if ($this->MM_hasUidField) {
645 $queryBuilder->addSelect('uid');
646 }
647 if ($additionalWhere_tablenames) {
648 $queryBuilder->andWhere($additionalWhere_tablenames);
649 }
650 if ($additionalWhere->count()) {
651 $queryBuilder->andWhere($additionalWhere);
652 }
653
654 $result = $queryBuilder->execute();
655 $oldMMs = array();
656 // This array is similar to $oldMMs but also holds the uid of the MM-records, if any (configured by MM_hasUidField).
657 // If the UID is present it will be used to update sorting and delete MM-records.
658 // This is necessary if the "multiple" feature is used for the MM relations.
659 // $oldMMs is still needed for the in_array() search used to look if an item from $this->itemArray is in $oldMMs
660 $oldMMs_inclUid = array();
661 while ($row = $result->fetch()) {
662 if (!$this->MM_is_foreign && $prep) {
663 $oldMMs[] = array($row['tablenames'], $row[$uidForeign_field]);
664 } else {
665 $oldMMs[] = $row[$uidForeign_field];
666 }
667 $oldMMs_inclUid[] = array($row['tablenames'], $row[$uidForeign_field], $row['uid']);
668 }
669 // For each item, insert it:
670 foreach ($this->itemArray as $val) {
671 $c++;
672 if ($prep || $val['table'] == '_NO_TABLE') {
673 // Insert current table if needed
674 if ($this->MM_is_foreign) {
675 $tablename = $this->currentTable;
676 } else {
677 $tablename = $val['table'];
678 }
679 } else {
680 $tablename = '';
681 }
682 if (!$this->MM_is_foreign && $prep) {
683 $item = array($val['table'], $val['id']);
684 } else {
685 $item = $val['id'];
686 }
687 if (in_array($item, $oldMMs)) {
688 $oldMMs_index = array_search($item, $oldMMs);
689 // In principle, selecting on the UID is all we need to do
690 // if a uid field is available since that is unique!
691 // But as long as it "doesn't hurt" we just add it to the where clause. It should all match up.
692 $queryBuilder = $connection->createQueryBuilder();
693 $queryBuilder->update($MM_tableName)
694 ->set($sorting_field, $c)
695 ->where(
696 $expressionBuilder->eq($uidLocal_field, $uid),
697 $expressionBuilder->eq($uidForeign_field, $val['id'])
698 );
699
700 if ($additionalWhere->count()) {
701 $queryBuilder->andWhere($additionalWhere);
702 }
703 if ($this->MM_hasUidField) {
704 $queryBuilder->andWhere($expressionBuilder->eq('uid', (int)$oldMMs_inclUid[$oldMMs_index][2]));
705 }
706 if ($tablename) {
707 $queryBuilder->andWhere(
708 $expressionBuilder->eq('tablenames', $queryBuilder->createNamedParameter($tablename))
709 );
710 }
711
712 $queryBuilder->execute();
713 // Remove the item from the $oldMMs array so after this
714 // foreach loop only the ones that need to be deleted are in there.
715 unset($oldMMs[$oldMMs_index]);
716 // Remove the item from the $oldMMs_inclUid array so after this
717 // foreach loop only the ones that need to be deleted are in there.
718 unset($oldMMs_inclUid[$oldMMs_index]);
719 } else {
720 $insertFields = $this->MM_insert_fields;
721 $insertFields[$uidLocal_field] = $uid;
722 $insertFields[$uidForeign_field] = $val['id'];
723 $insertFields[$sorting_field] = $c;
724 if ($tablename) {
725 $insertFields['tablenames'] = $tablename;
726 $insertFields = $this->completeOppositeUsageValues($tablename, $insertFields);
727 }
728 $connection->insert($MM_tableName, $insertFields);
729 if ($this->MM_is_foreign) {
730 $this->updateRefIndex($val['table'], $val['id']);
731 }
732 }
733 }
734 // Delete all not-used relations:
735 if (is_array($oldMMs) && !empty($oldMMs)) {
736 $queryBuilder = $connection->createQueryBuilder();
737 $removeClauses = $queryBuilder->expr()->orX();
738 $updateRefIndex_records = array();
739 foreach ($oldMMs as $oldMM_key => $mmItem) {
740 // If UID field is present, of course we need only use that for deleting.
741 if ($this->MM_hasUidField) {
742 $removeClauses->add($queryBuilder->expr()->eq('uid', (int)$oldMMs_inclUid[$oldMM_key][2]));
743 } else {
744 if (is_array($mmItem)) {
745 $removeClauses->add(
746 $queryBuilder->expr()->andX(
747 $queryBuilder->expr()->eq(
748 'tablenames',
749 $queryBuilder->createNamedParameter($mmItem[0])
750 ),
751 $queryBuilder->expr()->eq(
752 $uidForeign_field,
753 $queryBuilder->createNamedParameter($mmItem[1])
754 )
755 )
756 );
757 } else {
758 $removeClauses->add(
759 $queryBuilder->expr()->eq(
760 $uidForeign_field,
761 $queryBuilder->createNamedParameter($mmItem)
762 )
763 );
764 }
765 }
766 if ($this->MM_is_foreign) {
767 if (is_array($mmItem)) {
768 $updateRefIndex_records[] = array($mmItem[0], $mmItem[1]);
769 } else {
770 $updateRefIndex_records[] = array($this->firstTable, $mmItem);
771 }
772 }
773 }
774
775 $queryBuilder->delete($MM_tableName)
776 ->where(
777 $queryBuilder->expr()->eq($uidLocal_field, (int)$uid),
778 $removeClauses
779 );
780
781 if ($additionalWhere_tablenames) {
782 $queryBuilder->andWhere($additionalWhere_tablenames);
783 }
784 if ($additionalWhere->count()) {
785 $queryBuilder->andWhere($additionalWhere);
786 }
787
788 $queryBuilder->execute();
789
790 // Update ref index:
791 foreach ($updateRefIndex_records as $pair) {
792 $this->updateRefIndex($pair[0], $pair[1]);
793 }
794 }
795 // Update ref index; In tcemain it is not certain that this will happen because
796 // if only the MM field is changed the record itself is not updated and so the ref-index is not either.
797 // This could also have been fixed in updateDB in tcemain, however I decided to do it here ...
798 $this->updateRefIndex($this->currentTable, $uid);
799 }
800 }
801
802 /**
803 * Remaps MM table elements from one local uid to another
804 * Does NOT update the reference index for you, must be called subsequently to do that!
805 *
806 * @param string $MM_tableName MM table name
807 * @param int $uid Local, current UID
808 * @param int $newUid Local, new UID
809 * @param bool $prependTableName If set, then table names will always be written.
810 * @return void
811 */
812 public function remapMM($MM_tableName, $uid, $newUid, $prependTableName = false)
813 {
814 // In case of a reverse relation
815 if ($this->MM_is_foreign) {
816 $uidLocal_field = 'uid_foreign';
817 } else {
818 // default
819 $uidLocal_field = 'uid_local';
820 }
821 // If there are tables...
822 $tableC = count($this->tableArray);
823 if ($tableC) {
824 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($MM_tableName);
825 $queryBuilder->update($MM_tableName)
826 ->set($uidLocal_field, (int)$newUid)
827 ->where($queryBuilder->expr()->eq($uidLocal_field, (int)$uid));
828 // Boolean: does the field "tablename" need to be filled?
829 $prep = $tableC > 1 || $prependTableName || $this->MM_isMultiTableRelationship;
830 $additionalWhere_tablenames = '';
831 if ($this->MM_is_foreign && $prep) {
832 $queryBuilder->andWhere(
833 $queryBuilder->expr()->eq('tablenames', $queryBuilder->createNamedParameter($this->currentTable))
834 );
835 }
836 // Add WHERE clause if configured
837 if ($this->MM_table_where) {
838 $queryBuilder->andWhere(
839 QueryHelper::stripLogicalOperatorPrefix(str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where))
840 );
841 }
842 // Select, update or delete only those relations that match the configured fields
843 foreach ($this->MM_match_fields as $field => $value) {
844 $queryBuilder->andWhere(
845 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($value))
846 );
847 }
848 $queryBuilder->execute();
849 }
850 }
851
852 /**
853 * Reads items from a foreign_table, that has a foreign_field (uid of the parent record) and
854 * stores the parts in the internal array itemArray and tableArray.
855 *
856 * @param int $uid The uid of the parent record (this value is also on the foreign_table in the foreign_field)
857 * @param array $conf TCA configuration for current field
858 * @return void
859 */
860 public function readForeignField($uid, $conf)
861 {
862 if ($this->useLiveParentIds) {
863 $uid = $this->getLiveDefaultId($this->currentTable, $uid);
864 }
865
866 $key = 0;
867 $uid = (int)$uid;
868 $foreign_table = $conf['foreign_table'];
869 $foreign_table_field = $conf['foreign_table_field'];
870 $useDeleteClause = !$this->undeleteRecord;
871 $foreign_match_fields = is_array($conf['foreign_match_fields']) ? $conf['foreign_match_fields'] : array();
872 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
873 ->getQueryBuilderForTable($foreign_table);
874 $queryBuilder->getRestrictions()
875 ->removeAll();
876 // Use the deleteClause (e.g. "deleted=0") on this table
877 if ($useDeleteClause) {
878 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
879 }
880
881 $queryBuilder->select('uid')
882 ->from($foreign_table);
883
884 // Search for $uid in foreign_field, and if we have symmetric relations, do this also on symmetric_field
885 if ($conf['symmetric_field']) {
886 $queryBuilder->where(
887 $queryBuilder->expr()->orX(
888 $queryBuilder->expr()->eq($conf['foreign_field'], $uid),
889 $queryBuilder->expr()->eq($conf['symmetric_field'], $uid)
890 )
891 );
892 } else {
893 $queryBuilder->where($queryBuilder->expr()->eq($conf['foreign_field'], $uid));
894 }
895 // If it's requested to look for the parent uid AND the parent table,
896 // add an additional SQL-WHERE clause
897 if ($foreign_table_field && $this->currentTable) {
898 $queryBuilder->andWhere(
899 $queryBuilder->expr()->eq(
900 $foreign_table_field,
901 $queryBuilder->createNamedParameter($this->currentTable)
902 )
903 );
904 }
905 // Add additional where clause if foreign_match_fields are defined
906 foreach ($foreign_match_fields as $field => $value) {
907 $queryBuilder->andWhere(
908 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($value))
909 );
910 }
911 // Select children from the live(!) workspace only
912 if (BackendUtility::isTableWorkspaceEnabled($foreign_table)) {
913 $queryBuilder->andWhere(
914 $queryBuilder->expr()->in($foreign_table . '.t3ver_wsid', [0, (int)$this->getWorkspaceId()]),
915 $queryBuilder->expr()->neq($foreign_table . '.pid', -1)
916 );
917 }
918 // Get the correct sorting field
919 // Specific manual sortby for data handled by this field
920 $sortby = '';
921 if ($conf['foreign_sortby']) {
922 if ($conf['symmetric_sortby'] && $conf['symmetric_field']) {
923 // Sorting depends on, from which side of the relation we're looking at it
924 // This requires bypassing automatic quoting and setting of the default sort direction
925 $queryBuilder->add(
926 'orderBy',
927 'CASE
928 WHEN ' . $queryBuilder->expr()->eq($conf['foreign_field'], $uid) . '
929 THEN ' . $queryBuilder->quoteIdentifier($conf['foreign_sortby']) . '
930 ELSE ' . $queryBuilder->quoteIdentifier($conf['symmetric_sortby']) . '
931 END'
932 );
933 } else {
934 // Regular single-side behaviour
935 $sortby = $conf['foreign_sortby'];
936 }
937 } elseif ($conf['foreign_default_sortby']) {
938 // Specific default sortby for data handled by this field
939 $sortby = $conf['foreign_default_sortby'];
940 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) {
941 // Manual sortby for all table records
942 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
943 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby']) {
944 // Default sortby for all table records
945 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby'];
946 }
947
948 if (!empty($sortby)) {
949 foreach (QueryHelper::parseOrderBy($sortby) as $orderPair) {
950 list($fieldName, $sorting) = $orderPair;
951 $queryBuilder->addOrderBy($fieldName, $sorting);
952 }
953 }
954
955 // Get the rows from storage
956 $rows = [];
957 $result = $queryBuilder->execute();
958 while ($row = $result->fetch()) {
959 $rows[$row['uid']] = $row;
960 }
961 if (!empty($rows)) {
962 // Retrieve the parsed and prepared ORDER BY configuration for the resolver
963 $sortby = $queryBuilder->getQueryPart('orderBy');
964 $ids = $this->getResolver($foreign_table, array_keys($rows), $sortby)->get();
965 foreach ($ids as $id) {
966 $this->itemArray[$key]['id'] = $id;
967 $this->itemArray[$key]['table'] = $foreign_table;
968 $this->tableArray[$foreign_table][] = $id;
969 $key++;
970 }
971 }
972 }
973
974 /**
975 * Write the sorting values to a foreign_table, that has a foreign_field (uid of the parent record)
976 *
977 * @param array $conf TCA configuration for current field
978 * @param int $parentUid The uid of the parent record
979 * @param int $updateToUid If this is larger than zero it will be used as foreign UID instead of the given $parentUid (on Copy)
980 * @param bool $skipSorting Do not update the sorting columns, this could happen for imported values
981 * @return void
982 */
983 public function writeForeignField($conf, $parentUid, $updateToUid = 0, $skipSorting = false)
984 {
985 if ($this->useLiveParentIds) {
986 $parentUid = $this->getLiveDefaultId($this->currentTable, $parentUid);
987 if (!empty($updateToUid)) {
988 $updateToUid = $this->getLiveDefaultId($this->currentTable, $updateToUid);
989 }
990 }
991
992 $c = 0;
993 $foreign_table = $conf['foreign_table'];
994 $foreign_field = $conf['foreign_field'];
995 $symmetric_field = $conf['symmetric_field'];
996 $foreign_table_field = $conf['foreign_table_field'];
997 $foreign_match_fields = is_array($conf['foreign_match_fields']) ? $conf['foreign_match_fields'] : array();
998 // If there are table items and we have a proper $parentUid
999 if (MathUtility::canBeInterpretedAsInteger($parentUid) && !empty($this->tableArray)) {
1000 // If updateToUid is not a positive integer, set it to '0', so it will be ignored
1001 if (!(MathUtility::canBeInterpretedAsInteger($updateToUid) && $updateToUid > 0)) {
1002 $updateToUid = 0;
1003 }
1004 $considerWorkspaces = ($GLOBALS['BE_USER']->workspace !== 0 && BackendUtility::isTableWorkspaceEnabled($foreign_table));
1005 $fields = 'uid,pid,' . $foreign_field;
1006 // Consider the symmetric field if defined:
1007 if ($symmetric_field) {
1008 $fields .= ',' . $symmetric_field;
1009 }
1010 // Consider workspaces if defined and currently used:
1011 if ($considerWorkspaces) {
1012 $fields .= ',t3ver_wsid,t3ver_state,t3ver_oid';
1013 }
1014 // Update all items
1015 foreach ($this->itemArray as $val) {
1016 $uid = $val['id'];
1017 $table = $val['table'];
1018 $row = array();
1019 // Fetch the current (not overwritten) relation record if we should handle symmetric relations
1020 if ($symmetric_field || $considerWorkspaces) {
1021 $row = BackendUtility::getRecord($table, $uid, $fields, '', true);
1022 if (empty($row)) {
1023 continue;
1024 }
1025 }
1026 $isOnSymmetricSide = false;
1027 if ($symmetric_field) {
1028 $isOnSymmetricSide = self::isOnSymmetricSide($parentUid, $conf, $row);
1029 }
1030 $updateValues = $foreign_match_fields;
1031 // No update to the uid is requested, so this is the normal behaviour
1032 // just update the fields and care about sorting
1033 if (!$updateToUid) {
1034 // Always add the pointer to the parent uid
1035 if ($isOnSymmetricSide) {
1036 $updateValues[$symmetric_field] = $parentUid;
1037 } else {
1038 $updateValues[$foreign_field] = $parentUid;
1039 }
1040 // If it is configured in TCA also to store the parent table in the child record, just do it
1041 if ($foreign_table_field && $this->currentTable) {
1042 $updateValues[$foreign_table_field] = $this->currentTable;
1043 }
1044 // Update sorting columns if not to be skipped
1045 if (!$skipSorting) {
1046 // Get the correct sorting field
1047 // Specific manual sortby for data handled by this field
1048 $sortby = '';
1049 if ($conf['foreign_sortby']) {
1050 $sortby = $conf['foreign_sortby'];
1051 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) {
1052 // manual sortby for all table records
1053 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
1054 }
1055 // Apply sorting on the symmetric side
1056 // (it depends on who created the relation, so what uid is in the symmetric_field):
1057 if ($isOnSymmetricSide && isset($conf['symmetric_sortby']) && $conf['symmetric_sortby']) {
1058 $sortby = $conf['symmetric_sortby'];
1059 } else {
1060 $tempSortBy = [];
1061 foreach (QueryHelper::parseOrderBy($sortby) as $orderPair) {
1062 list($fieldName, $order) = $orderPair;
1063 if ($order !== null) {
1064 $tempSortBy[] = implode(' ', $orderPair);
1065 } else {
1066 $tempSortBy[] = $fieldName;
1067 }
1068 }
1069 $sortby = implode(',', $tempSortBy);
1070 }
1071 if ($sortby) {
1072 $updateValues[$sortby] = ++$c;
1073 }
1074 }
1075 } else {
1076 if ($isOnSymmetricSide) {
1077 $updateValues[$symmetric_field] = $updateToUid;
1078 } else {
1079 $updateValues[$foreign_field] = $updateToUid;
1080 }
1081 }
1082 // Update accordant fields in the database:
1083 if (!empty($updateValues)) {
1084 // Update tstamp if any foreign field value has changed
1085 if (!empty($GLOBALS['TCA'][$table]['ctrl']['tstamp'])) {
1086 $currentRow = BackendUtility::getRecord($table, $uid, implode(',', array_keys($updateValues)), '', true);
1087 $needTstampUpdate = false;
1088 if (empty($currentRow)) {
1089 $needTstampUpdate = true;
1090 } else {
1091 foreach ($currentRow as $field => $curValue) {
1092 if ((string)$curValue !== (string)$updateValues[$field]) {
1093 $needTstampUpdate = true;
1094 break;
1095 }
1096 }
1097 }
1098 if ($needTstampUpdate) {
1099 $updateValues[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1100 }
1101 }
1102 GeneralUtility::makeInstance(ConnectionPool::class)
1103 ->getConnectionForTable($table)
1104 ->update(
1105 $table,
1106 $updateValues,
1107 ['uid' => (int)$uid]
1108 );
1109 $this->updateRefIndex($table, $uid);
1110 }
1111 // Update accordant fields in the database for workspaces overlays/placeholders:
1112 if ($considerWorkspaces) {
1113 // It's the specific versioned record -> update placeholder (if any)
1114 if (!empty($row['t3ver_oid']) && VersionState::cast($row['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER_VERSION)) {
1115 GeneralUtility::makeInstance(ConnectionPool::class)
1116 ->getConnectionForTable($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 = array();
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 = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1185 $queryBuilder->getRestrictions()->removeAll();
1186 $queryBuilder->select(...(GeneralUtility::trimExplode(',', $fields, true)))
1187 ->from($table)
1188 ->where($queryBuilder->expr()->in('uid', GeneralUtility::intExplode(',', $itemList)));
1189 if ($this->additionalWhere[$table]) {
1190 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->additionalWhere[$table]));
1191 }
1192 $statement = $queryBuilder->execute();
1193 while ($row = $statement->fetch()) {
1194 $this->results[$table][$row['uid']] = $row;
1195 }
1196 }
1197 }
1198 }
1199 return $this->results;
1200 }
1201
1202 /**
1203 * Prepare items from itemArray to be transferred to the TCEforms interface (as a comma list)
1204 *
1205 * @return string
1206 */
1207 public function readyForInterface()
1208 {
1209 if (!is_array($this->itemArray)) {
1210 return false;
1211 }
1212 $output = array();
1213 $titleLen = (int)$GLOBALS['BE_USER']->uc['titleLen'];
1214 foreach ($this->itemArray as $val) {
1215 $theRow = $this->results[$val['table']][$val['id']];
1216 if ($theRow && is_array($GLOBALS['TCA'][$val['table']])) {
1217 $label = GeneralUtility::fixed_lgd_cs(strip_tags(
1218 BackendUtility::getRecordTitle($val['table'], $theRow)), $titleLen);
1219 $label = $label ? $label : '[...]';
1220 $output[] = str_replace(',', '', $val['table'] . '_' . $val['id'] . '|' . rawurlencode($label));
1221 }
1222 }
1223 return implode(',', $output);
1224 }
1225
1226 /**
1227 * Counts the items in $this->itemArray and puts this value in an array by default.
1228 *
1229 * @param bool $returnAsArray Whether to put the count value in an array
1230 * @return mixed The plain count as integer or the same inside an array
1231 */
1232 public function countItems($returnAsArray = true)
1233 {
1234 $count = count($this->itemArray);
1235 if ($returnAsArray) {
1236 $count = array($count);
1237 }
1238 return $count;
1239 }
1240
1241 /**
1242 * Update Reference Index (sys_refindex) for a record
1243 * Should be called any almost any update to a record which could affect references inside the record.
1244 * (copied from TCEmain)
1245 *
1246 * @param string $table Table name
1247 * @param int $id Record UID
1248 * @return array Information concerning modifications delivered by \TYPO3\CMS\Core\Database\ReferenceIndex::updateRefIndexTable()
1249 */
1250 public function updateRefIndex($table, $id)
1251 {
1252 $statisticsArray = array();
1253 if ($this->updateReferenceIndex) {
1254 /** @var $refIndexObj \TYPO3\CMS\Core\Database\ReferenceIndex */
1255 $refIndexObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ReferenceIndex::class);
1256 if (BackendUtility::isTableWorkspaceEnabled($table)) {
1257 $refIndexObj->setWorkspaceId($this->getWorkspaceId());
1258 }
1259 $statisticsArray = $refIndexObj->updateRefIndexTable($table, $id);
1260 }
1261 return $statisticsArray;
1262 }
1263
1264 /**
1265 * @param NULL|int $workspaceId
1266 * @return bool Whether items have been purged
1267 */
1268 public function purgeItemArray($workspaceId = null)
1269 {
1270 if ($workspaceId === null) {
1271 $workspaceId = $this->getWorkspaceId();
1272 } else {
1273 $workspaceId = (int)$workspaceId;
1274 }
1275
1276 // Ensure, only live relations are in the items Array
1277 if ($workspaceId === 0) {
1278 $purgeCallback = 'purgeVersionedIds';
1279 // Otherwise, ensure that live relations are purged if version exists
1280 } else {
1281 $purgeCallback = 'purgeLiveVersionedIds';
1282 }
1283
1284 $itemArrayHasBeenPurged = $this->purgeItemArrayHandler($purgeCallback);
1285 $this->purged = ($this->purged || $itemArrayHasBeenPurged);
1286 return $itemArrayHasBeenPurged;
1287 }
1288
1289 /**
1290 * Removes items having a delete placeholder from $this->itemArray
1291 *
1292 * @return bool Whether items have been purged
1293 */
1294 public function processDeletePlaceholder()
1295 {
1296 if (!$this->useLiveReferenceIds || $this->getWorkspaceId() === 0) {
1297 return false;
1298 }
1299
1300 return $this->purgeItemArrayHandler('purgeDeletePlaceholder');
1301 }
1302
1303 /**
1304 * Handles a purge callback on $this->itemArray
1305 *
1306 * @param callable $purgeCallback
1307 * @return bool Whether items have been purged
1308 */
1309 protected function purgeItemArrayHandler($purgeCallback)
1310 {
1311 $itemArrayHasBeenPurged = false;
1312
1313 foreach ($this->tableArray as $itemTableName => $itemIds) {
1314 if (empty($itemIds) || !BackendUtility::isTableWorkspaceEnabled($itemTableName)) {
1315 continue;
1316 }
1317
1318 $purgedItemIds = call_user_func(array($this, $purgeCallback), $itemTableName, $itemIds);
1319 $removedItemIds = array_diff($itemIds, $purgedItemIds);
1320 foreach ($removedItemIds as $removedItemId) {
1321 $this->removeFromItemArray($itemTableName, $removedItemId);
1322 }
1323 $this->tableArray[$itemTableName] = $purgedItemIds;
1324 if (!empty($removedItemIds)) {
1325 $itemArrayHasBeenPurged = true;
1326 }
1327 }
1328
1329 return $itemArrayHasBeenPurged;
1330 }
1331
1332 /**
1333 * Purges ids that are versioned.
1334 *
1335 * @param string $tableName
1336 * @param array $ids
1337 * @return array
1338 */
1339 protected function purgeVersionedIds($tableName, array $ids)
1340 {
1341 $ids = array_map('intval', $ids);
1342 $ids = array_combine($ids, $ids);
1343
1344 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
1345 $queryBuilder->getRestrictions()->removeAll();
1346 $versions = $queryBuilder->select('uid', 't3ver_oid', 't3ver_state')
1347 ->from($tableName)
1348 ->where(
1349 $queryBuilder->expr()->eq('pid', -1),
1350 $queryBuilder->expr()->in('t3ver_oid', $ids),
1351 $queryBuilder->expr()->neq('t3ver_wsid', 0)
1352 )
1353 ->orderBy('t3ver_state', 'DESC')
1354 ->execute()
1355 ->fetchAll();
1356
1357 if (!empty($versions)) {
1358 foreach ($versions as $version) {
1359 $versionId = $version['uid'];
1360 if (isset($ids[$versionId])) {
1361 unset($ids[$versionId]);
1362 }
1363 }
1364 }
1365
1366 return array_values($ids);
1367 }
1368
1369 /**
1370 * Purges ids that are live but have an accordant version.
1371 *
1372 * @param string $tableName
1373 * @param array $ids
1374 * @return array
1375 */
1376 protected function purgeLiveVersionedIds($tableName, array $ids)
1377 {
1378 $ids = array_map('intval', $ids);
1379 $ids = array_combine($ids, $ids);
1380
1381 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
1382 $queryBuilder->getRestrictions()->removeAll();
1383 $versions = $queryBuilder->select('uid', 't3ver_oid', 't3ver_state')
1384 ->from($tableName)
1385 ->where(
1386 $queryBuilder->expr()->eq('pid', -1),
1387 $queryBuilder->expr()->in('t3ver_oid', $ids),
1388 $queryBuilder->expr()->neq('t3ver_wsid', 0)
1389 )
1390 ->orderBy('t3ver_state', 'DESC')
1391 ->execute()
1392 ->fetchAll();
1393
1394 if (!empty($versions)) {
1395 foreach ($versions as $version) {
1396 $versionId = $version['uid'];
1397 $liveId = $version['t3ver_oid'];
1398 if (isset($ids[$liveId]) && isset($ids[$versionId])) {
1399 unset($ids[$liveId]);
1400 }
1401 }
1402 }
1403
1404 return array_values($ids);
1405 }
1406
1407 /**
1408 * Purges ids that have a delete placeholder
1409 *
1410 * @param string $tableName
1411 * @param array $ids
1412 * @return array
1413 */
1414 protected function purgeDeletePlaceholder($tableName, array $ids)
1415 {
1416 $ids = array_map('intval', $ids);
1417 $ids = array_combine($ids, $ids);
1418
1419 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
1420 $queryBuilder->getRestrictions()->removeAll();
1421 $versions = $queryBuilder->select('uid', 't3ver_oid', 't3ver_state')
1422 ->from($tableName)
1423 ->where(
1424 $queryBuilder->expr()->eq('pid', -1),
1425 $queryBuilder->expr()->in('t3ver_oid', $ids),
1426 $queryBuilder->expr()->neq('t3ver_wsid', (int)$this->getWorkspaceId()),
1427 $queryBuilder->expr()->eq('t3ver_state', (int)VersionState::cast(VersionState::DELETE_PLACEHOLDER))
1428 )
1429 ->execute()
1430 ->fetchAll();
1431
1432 if (!empty($versions)) {
1433 foreach ($versions as $version) {
1434 $liveId = $version['t3ver_oid'];
1435 if (isset($ids[$liveId])) {
1436 unset($ids[$liveId]);
1437 }
1438 }
1439 }
1440
1441 return array_values($ids);
1442 }
1443
1444 protected function removeFromItemArray($tableName, $id)
1445 {
1446 foreach ($this->itemArray as $index => $item) {
1447 if ($item['table'] === $tableName && (string)$item['id'] === (string)$id) {
1448 unset($this->itemArray[$index]);
1449 return true;
1450 }
1451 }
1452 return false;
1453 }
1454
1455 /**
1456 * Checks, if we're looking from the "other" side, the symmetric side, to a symmetric relation.
1457 *
1458 * @param string $parentUid The uid of the parent record
1459 * @param array $parentConf The TCA configuration of the parent field embedding the child records
1460 * @param array $childRec The record row of the child record
1461 * @return bool Returns TRUE if looking from the symmetric ("other") side to the relation.
1462 */
1463 public static function isOnSymmetricSide($parentUid, $parentConf, $childRec)
1464 {
1465 return MathUtility::canBeInterpretedAsInteger($childRec['uid'])
1466 && $parentConf['symmetric_field']
1467 && $parentUid == $childRec[$parentConf['symmetric_field']];
1468 }
1469
1470 /**
1471 * Completes MM values to be written by values from the opposite relation.
1472 * This method used MM insert field or MM match fields if defined.
1473 *
1474 * @param string $tableName Name of the opposite table
1475 * @param array $referenceValues Values to be written
1476 * @return array Values to be written, possibly modified
1477 */
1478 protected function completeOppositeUsageValues($tableName, array $referenceValues)
1479 {
1480 if (empty($this->MM_oppositeUsage[$tableName]) || count($this->MM_oppositeUsage[$tableName]) > 1) {
1481 return $referenceValues;
1482 }
1483
1484 $fieldName = $this->MM_oppositeUsage[$tableName][0];
1485 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1486 return $referenceValues;
1487 }
1488
1489 $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1490 if (!empty($configuration['MM_insert_fields'])) {
1491 $referenceValues = array_merge($configuration['MM_insert_fields'], $referenceValues);
1492 } elseif (!empty($configuration['MM_match_fields'])) {
1493 $referenceValues = array_merge($configuration['MM_match_fields'], $referenceValues);
1494 }
1495
1496 return $referenceValues;
1497 }
1498
1499 /**
1500 * Gets the record uid of the live default record. If already
1501 * pointing to the live record, the submitted record uid is returned.
1502 *
1503 * @param string $tableName
1504 * @param int $id
1505 * @return int
1506 */
1507 protected function getLiveDefaultId($tableName, $id)
1508 {
1509 $liveDefaultId = BackendUtility::getLiveVersionIdOfRecord($tableName, $id);
1510 if ($liveDefaultId === null) {
1511 $liveDefaultId = $id;
1512 }
1513 return (int)$liveDefaultId;
1514 }
1515
1516 /**
1517 * @param string $tableName
1518 * @param int[] $ids
1519 * @param array $sortingStatement
1520 * @return PlainDataResolver
1521 */
1522 protected function getResolver($tableName, array $ids, array $sortingStatement = null)
1523 {
1524 /** @var PlainDataResolver $resolver */
1525 $resolver = GeneralUtility::makeInstance(
1526 PlainDataResolver::class,
1527 $tableName,
1528 $ids,
1529 $sortingStatement
1530 );
1531 $resolver->setWorkspaceId($this->getWorkspaceId());
1532 $resolver->setKeepDeletePlaceholder(true);
1533 $resolver->setKeepLiveIds($this->useLiveReferenceIds);
1534 return $resolver;
1535 }
1536 }