91fcbc8553a867a6510e065fec0708786579b830
[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 || $this->getWorkspaceId() === 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(
496 'uid',
497 $queryBuilder->createNamedParameter(
498 GeneralUtility::intExplode(',', $uidList),
499 Connection::PARAM_INT_ARRAY
500 )
501 )
502 );
503 foreach (QueryHelper::parseOrderBy((string)$sortby) as $orderPair) {
504 list($fieldName, $order) = $orderPair;
505 $queryBuilder->addOrderBy($fieldName, $order);
506 }
507 $statement = $queryBuilder->execute();
508 while ($row = $statement->fetch()) {
509 $this->itemArray[] = ['id' => $row['uid'], 'table' => $table];
510 $this->tableArray[$table][] = $row['uid'];
511 }
512 }
513 }
514 }
515
516 /**
517 * Reads the record tablename/id into the internal arrays itemArray and tableArray from MM records.
518 * You can call this function after start if you supply no list to start()
519 *
520 * @param string $tableName MM Tablename
521 * @param int $uid Local UID
522 * @return void
523 */
524 public function readMM($tableName, $uid)
525 {
526 $key = 0;
527 $theTable = null;
528 $queryBuilder = $this->getConnectionForTableName($tableName)
529 ->createQueryBuilder();
530 $queryBuilder->getRestrictions()->removeAll();
531 $queryBuilder->select('*')->from($tableName);
532 // In case of a reverse relation
533 if ($this->MM_is_foreign) {
534 $uidLocal_field = 'uid_foreign';
535 $uidForeign_field = 'uid_local';
536 $sorting_field = 'sorting_foreign';
537 if ($this->MM_isMultiTableRelationship) {
538 // Be backwards compatible! When allowing more than one table after
539 // having previously allowed only one table, this case applies.
540 if ($this->currentTable == $this->MM_isMultiTableRelationship) {
541 $expression = $queryBuilder->expr()->orX(
542 $queryBuilder->expr()->eq(
543 'tablenames',
544 $queryBuilder->createNamedParameter($this->currentTable, \PDO::PARAM_STR)
545 ),
546 $queryBuilder->expr()->eq(
547 'tablenames',
548 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
549 )
550 );
551 } else {
552 $expression = $queryBuilder->expr()->eq(
553 'tablenames',
554 $queryBuilder->createNamedParameter($this->currentTable, \PDO::PARAM_STR)
555 );
556 }
557 $queryBuilder->andWhere($expression);
558 }
559 $theTable = $this->MM_oppositeTable;
560 } else {
561 // Default
562 $uidLocal_field = 'uid_local';
563 $uidForeign_field = 'uid_foreign';
564 $sorting_field = 'sorting';
565 }
566 if ($this->MM_table_where) {
567 $queryBuilder->andWhere(
568 QueryHelper::stripLogicalOperatorPrefix(str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where))
569 );
570 }
571 foreach ($this->MM_match_fields as $field => $value) {
572 $queryBuilder->andWhere(
573 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($value, \PDO::PARAM_STR))
574 );
575 }
576 if (MathUtility::canBeInterpretedAsInteger($uid)) {
577 $queryBuilder->andWhere(
578 $queryBuilder->expr()->eq(
579 $uidLocal_field,
580 $queryBuilder->createNamedParameter((int)$uid, \PDO::PARAM_INT)
581 )
582 );
583 }
584 $queryBuilder->orderBy($sorting_field);
585 $statement = $queryBuilder->execute();
586 while ($row = $statement->fetch()) {
587 // Default
588 if (!$this->MM_is_foreign) {
589 // If tablesnames columns exists and contain a name, then this value is the table, else it's the firstTable...
590 $theTable = $row['tablenames'] ?: $this->firstTable;
591 }
592 if (($row[$uidForeign_field] || $theTable == 'pages') && $theTable && isset($this->tableArray[$theTable])) {
593 $this->itemArray[$key]['id'] = $row[$uidForeign_field];
594 $this->itemArray[$key]['table'] = $theTable;
595 $this->tableArray[$theTable][] = $row[$uidForeign_field];
596 } elseif ($this->registerNonTableValues) {
597 $this->itemArray[$key]['id'] = $row[$uidForeign_field];
598 $this->itemArray[$key]['table'] = '_NO_TABLE';
599 $this->nonTableArray[] = $row[$uidForeign_field];
600 }
601 $key++;
602 }
603 }
604
605 /**
606 * Writes the internal itemArray to MM table:
607 *
608 * @param string $MM_tableName MM table name
609 * @param int $uid Local UID
610 * @param bool $prependTableName If set, then table names will always be written.
611 * @return void
612 */
613 public function writeMM($MM_tableName, $uid, $prependTableName = false)
614 {
615 $connection = $this->getConnectionForTableName($MM_tableName);
616 $expressionBuilder = $connection->createQueryBuilder()->expr();
617
618 // In case of a reverse relation
619 if ($this->MM_is_foreign) {
620 $uidLocal_field = 'uid_foreign';
621 $uidForeign_field = 'uid_local';
622 $sorting_field = 'sorting_foreign';
623 } else {
624 // default
625 $uidLocal_field = 'uid_local';
626 $uidForeign_field = 'uid_foreign';
627 $sorting_field = 'sorting';
628 }
629 // If there are tables...
630 $tableC = count($this->tableArray);
631 if ($tableC) {
632 // Boolean: does the field "tablename" need to be filled?
633 $prep = $tableC > 1 || $prependTableName || $this->MM_isMultiTableRelationship ? 1 : 0;
634 $c = 0;
635 $additionalWhere_tablenames = '';
636 if ($this->MM_is_foreign && $prep) {
637 $additionalWhere_tablenames = $expressionBuilder->eq(
638 'tablenames',
639 $expressionBuilder->literal($this->currentTable)
640 );
641 }
642 $additionalWhere = $expressionBuilder->andX();
643 // Add WHERE clause if configured
644 if ($this->MM_table_where) {
645 $additionalWhere->add(
646 QueryHelper::stripLogicalOperatorPrefix(
647 str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where)
648 )
649 );
650 }
651 // Select, update or delete only those relations that match the configured fields
652 foreach ($this->MM_match_fields as $field => $value) {
653 $additionalWhere->add($expressionBuilder->eq($field, $expressionBuilder->literal($value)));
654 }
655
656 $queryBuilder = $connection->createQueryBuilder();
657 $queryBuilder->getRestrictions()->removeAll();
658 $queryBuilder->select($uidForeign_field)
659 ->from($MM_tableName)
660 ->where($queryBuilder->expr()->eq(
661 $uidLocal_field,
662 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
663 ))
664 ->orderBy($sorting_field);
665
666 if ($prep) {
667 $queryBuilder->addSelect('tablenames');
668 }
669 if ($this->MM_hasUidField) {
670 $queryBuilder->addSelect('uid');
671 }
672 if ($additionalWhere_tablenames) {
673 $queryBuilder->andWhere($additionalWhere_tablenames);
674 }
675 if ($additionalWhere->count()) {
676 $queryBuilder->andWhere($additionalWhere);
677 }
678
679 $result = $queryBuilder->execute();
680 $oldMMs = [];
681 // This array is similar to $oldMMs but also holds the uid of the MM-records, if any (configured by MM_hasUidField).
682 // If the UID is present it will be used to update sorting and delete MM-records.
683 // This is necessary if the "multiple" feature is used for the MM relations.
684 // $oldMMs is still needed for the in_array() search used to look if an item from $this->itemArray is in $oldMMs
685 $oldMMs_inclUid = [];
686 while ($row = $result->fetch()) {
687 if (!$this->MM_is_foreign && $prep) {
688 $oldMMs[] = [$row['tablenames'], $row[$uidForeign_field]];
689 } else {
690 $oldMMs[] = $row[$uidForeign_field];
691 }
692 $oldMMs_inclUid[] = [$row['tablenames'], $row[$uidForeign_field], $row['uid']];
693 }
694 // For each item, insert it:
695 foreach ($this->itemArray as $val) {
696 $c++;
697 if ($prep || $val['table'] == '_NO_TABLE') {
698 // Insert current table if needed
699 if ($this->MM_is_foreign) {
700 $tablename = $this->currentTable;
701 } else {
702 $tablename = $val['table'];
703 }
704 } else {
705 $tablename = '';
706 }
707 if (!$this->MM_is_foreign && $prep) {
708 $item = [$val['table'], $val['id']];
709 } else {
710 $item = $val['id'];
711 }
712 if (in_array($item, $oldMMs)) {
713 $oldMMs_index = array_search($item, $oldMMs);
714 // In principle, selecting on the UID is all we need to do
715 // if a uid field is available since that is unique!
716 // But as long as it "doesn't hurt" we just add it to the where clause. It should all match up.
717 $queryBuilder = $connection->createQueryBuilder();
718 $queryBuilder->update($MM_tableName)
719 ->set($sorting_field, $c)
720 ->where(
721 $expressionBuilder->eq(
722 $uidLocal_field,
723 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
724 ),
725 $expressionBuilder->eq(
726 $uidForeign_field,
727 $queryBuilder->createNamedParameter($val['id'], \PDO::PARAM_INT)
728 )
729 );
730
731 if ($additionalWhere->count()) {
732 $queryBuilder->andWhere($additionalWhere);
733 }
734 if ($this->MM_hasUidField) {
735 $queryBuilder->andWhere(
736 $expressionBuilder->eq(
737 'uid',
738 $queryBuilder->createNamedParameter($oldMMs_inclUid[$oldMMs_index][2], \PDO::PARAM_INT)
739 )
740 );
741 }
742 if ($tablename) {
743 $queryBuilder->andWhere(
744 $expressionBuilder->eq(
745 'tablenames',
746 $queryBuilder->createNamedParameter($tablename, \PDO::PARAM_STR)
747 )
748 );
749 }
750
751 $queryBuilder->execute();
752 // Remove the item from the $oldMMs array so after this
753 // foreach loop only the ones that need to be deleted are in there.
754 unset($oldMMs[$oldMMs_index]);
755 // Remove the item from the $oldMMs_inclUid array so after this
756 // foreach loop only the ones that need to be deleted are in there.
757 unset($oldMMs_inclUid[$oldMMs_index]);
758 } else {
759 $insertFields = $this->MM_insert_fields;
760 $insertFields[$uidLocal_field] = $uid;
761 $insertFields[$uidForeign_field] = $val['id'];
762 $insertFields[$sorting_field] = $c;
763 if ($tablename) {
764 $insertFields['tablenames'] = $tablename;
765 $insertFields = $this->completeOppositeUsageValues($tablename, $insertFields);
766 }
767 $connection->insert($MM_tableName, $insertFields);
768 if ($this->MM_is_foreign) {
769 $this->updateRefIndex($val['table'], $val['id']);
770 }
771 }
772 }
773 // Delete all not-used relations:
774 if (is_array($oldMMs) && !empty($oldMMs)) {
775 $queryBuilder = $connection->createQueryBuilder();
776 $removeClauses = $queryBuilder->expr()->orX();
777 $updateRefIndex_records = [];
778 foreach ($oldMMs as $oldMM_key => $mmItem) {
779 // If UID field is present, of course we need only use that for deleting.
780 if ($this->MM_hasUidField) {
781 $removeClauses->add($queryBuilder->expr()->eq(
782 'uid',
783 $queryBuilder->createNamedParameter($oldMMs_inclUid[$oldMM_key][2], \PDO::PARAM_INT)
784 ));
785 } else {
786 if (is_array($mmItem)) {
787 $removeClauses->add(
788 $queryBuilder->expr()->andX(
789 $queryBuilder->expr()->eq(
790 'tablenames',
791 $queryBuilder->createNamedParameter($mmItem[0], \PDO::PARAM_STR)
792 ),
793 $queryBuilder->expr()->eq(
794 $uidForeign_field,
795 $queryBuilder->createNamedParameter($mmItem[1], \PDO::PARAM_INT)
796 )
797 )
798 );
799 } else {
800 $removeClauses->add(
801 $queryBuilder->expr()->eq(
802 $uidForeign_field,
803 $queryBuilder->createNamedParameter($mmItem, \PDO::PARAM_INT)
804 )
805 );
806 }
807 }
808 if ($this->MM_is_foreign) {
809 if (is_array($mmItem)) {
810 $updateRefIndex_records[] = [$mmItem[0], $mmItem[1]];
811 } else {
812 $updateRefIndex_records[] = [$this->firstTable, $mmItem];
813 }
814 }
815 }
816
817 $queryBuilder->delete($MM_tableName)
818 ->where(
819 $queryBuilder->expr()->eq(
820 $uidLocal_field,
821 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
822 ),
823 $removeClauses
824 );
825
826 if ($additionalWhere_tablenames) {
827 $queryBuilder->andWhere($additionalWhere_tablenames);
828 }
829 if ($additionalWhere->count()) {
830 $queryBuilder->andWhere($additionalWhere);
831 }
832
833 $queryBuilder->execute();
834
835 // Update ref index:
836 foreach ($updateRefIndex_records as $pair) {
837 $this->updateRefIndex($pair[0], $pair[1]);
838 }
839 }
840 // Update ref index; In DataHandler it is not certain that this will happen because
841 // if only the MM field is changed the record itself is not updated and so the ref-index is not either.
842 // This could also have been fixed in updateDB in DataHandler, however I decided to do it here ...
843 $this->updateRefIndex($this->currentTable, $uid);
844 }
845 }
846
847 /**
848 * Remaps MM table elements from one local uid to another
849 * Does NOT update the reference index for you, must be called subsequently to do that!
850 *
851 * @param string $MM_tableName MM table name
852 * @param int $uid Local, current UID
853 * @param int $newUid Local, new UID
854 * @param bool $prependTableName If set, then table names will always be written.
855 * @return void
856 */
857 public function remapMM($MM_tableName, $uid, $newUid, $prependTableName = false)
858 {
859 // In case of a reverse relation
860 if ($this->MM_is_foreign) {
861 $uidLocal_field = 'uid_foreign';
862 } else {
863 // default
864 $uidLocal_field = 'uid_local';
865 }
866 // If there are tables...
867 $tableC = count($this->tableArray);
868 if ($tableC) {
869 $queryBuilder = $this->getConnectionForTableName($MM_tableName)
870 ->createQueryBuilder();
871 $queryBuilder->update($MM_tableName)
872 ->set($uidLocal_field, (int)$newUid)
873 ->where($queryBuilder->expr()->eq(
874 $uidLocal_field,
875 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
876 ));
877 // Boolean: does the field "tablename" need to be filled?
878 $prep = $tableC > 1 || $prependTableName || $this->MM_isMultiTableRelationship;
879 if ($this->MM_is_foreign && $prep) {
880 $queryBuilder->andWhere(
881 $queryBuilder->expr()->eq(
882 'tablenames',
883 $queryBuilder->createNamedParameter($this->currentTable, \PDO::PARAM_STR)
884 )
885 );
886 }
887 // Add WHERE clause if configured
888 if ($this->MM_table_where) {
889 $queryBuilder->andWhere(
890 QueryHelper::stripLogicalOperatorPrefix(str_replace('###THIS_UID###', (int)$uid, $this->MM_table_where))
891 );
892 }
893 // Select, update or delete only those relations that match the configured fields
894 foreach ($this->MM_match_fields as $field => $value) {
895 $queryBuilder->andWhere(
896 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($value, \PDO::PARAM_STR))
897 );
898 }
899 $queryBuilder->execute();
900 }
901 }
902
903 /**
904 * Reads items from a foreign_table, that has a foreign_field (uid of the parent record) and
905 * stores the parts in the internal array itemArray and tableArray.
906 *
907 * @param int $uid The uid of the parent record (this value is also on the foreign_table in the foreign_field)
908 * @param array $conf TCA configuration for current field
909 * @return void
910 */
911 public function readForeignField($uid, $conf)
912 {
913 if ($this->useLiveParentIds) {
914 $uid = $this->getLiveDefaultId($this->currentTable, $uid);
915 }
916
917 $key = 0;
918 $uid = (int)$uid;
919 $foreign_table = $conf['foreign_table'];
920 $foreign_table_field = $conf['foreign_table_field'];
921 $useDeleteClause = !$this->undeleteRecord;
922 $foreign_match_fields = is_array($conf['foreign_match_fields']) ? $conf['foreign_match_fields'] : [];
923 $queryBuilder = $this->getConnectionForTableName($foreign_table)
924 ->createQueryBuilder();
925 $queryBuilder->getRestrictions()
926 ->removeAll();
927 // Use the deleteClause (e.g. "deleted=0") on this table
928 if ($useDeleteClause) {
929 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
930 }
931
932 $queryBuilder->select('uid')
933 ->from($foreign_table);
934
935 // Search for $uid in foreign_field, and if we have symmetric relations, do this also on symmetric_field
936 if ($conf['symmetric_field']) {
937 $queryBuilder->where(
938 $queryBuilder->expr()->orX(
939 $queryBuilder->expr()->eq(
940 $conf['foreign_field'],
941 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
942 ),
943 $queryBuilder->expr()->eq(
944 $conf['symmetric_field'],
945 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
946 )
947 )
948 );
949 } else {
950 $queryBuilder->where($queryBuilder->expr()->eq(
951 $conf['foreign_field'],
952 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
953 ));
954 }
955 // If it's requested to look for the parent uid AND the parent table,
956 // add an additional SQL-WHERE clause
957 if ($foreign_table_field && $this->currentTable) {
958 $queryBuilder->andWhere(
959 $queryBuilder->expr()->eq(
960 $foreign_table_field,
961 $queryBuilder->createNamedParameter($this->currentTable, \PDO::PARAM_STR)
962 )
963 );
964 }
965 // Add additional where clause if foreign_match_fields are defined
966 foreach ($foreign_match_fields as $field => $value) {
967 $queryBuilder->andWhere(
968 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($value, \PDO::PARAM_STR))
969 );
970 }
971 // Select children from the live(!) workspace only
972 if (BackendUtility::isTableWorkspaceEnabled($foreign_table)) {
973 $queryBuilder->andWhere(
974 $queryBuilder->expr()->in(
975 $foreign_table . '.t3ver_wsid',
976 $queryBuilder->createNamedParameter([0, (int)$this->getWorkspaceId()], Connection::PARAM_INT_ARRAY)
977 ),
978 $queryBuilder->expr()->neq(
979 $foreign_table . '.pid',
980 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
981 )
982 );
983 }
984 // Get the correct sorting field
985 // Specific manual sortby for data handled by this field
986 $sortby = '';
987 if ($conf['foreign_sortby']) {
988 if ($conf['symmetric_sortby'] && $conf['symmetric_field']) {
989 // Sorting depends on, from which side of the relation we're looking at it
990 // This requires bypassing automatic quoting and setting of the default sort direction
991 // @TODO: Doctrine: generalize to standard SQL to guarantee database independency
992 $queryBuilder->add(
993 'orderBy',
994 'CASE
995 WHEN ' . $queryBuilder->expr()->eq($conf['foreign_field'], $uid) . '
996 THEN ' . $queryBuilder->quoteIdentifier($conf['foreign_sortby']) . '
997 ELSE ' . $queryBuilder->quoteIdentifier($conf['symmetric_sortby']) . '
998 END'
999 );
1000 } else {
1001 // Regular single-side behaviour
1002 $sortby = $conf['foreign_sortby'];
1003 }
1004 } elseif ($conf['foreign_default_sortby']) {
1005 // Specific default sortby for data handled by this field
1006 $sortby = $conf['foreign_default_sortby'];
1007 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) {
1008 // Manual sortby for all table records
1009 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
1010 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby']) {
1011 // Default sortby for all table records
1012 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby'];
1013 }
1014
1015 if (!empty($sortby)) {
1016 foreach (QueryHelper::parseOrderBy($sortby) as $orderPair) {
1017 list($fieldName, $sorting) = $orderPair;
1018 $queryBuilder->addOrderBy($fieldName, $sorting);
1019 }
1020 }
1021
1022 // Get the rows from storage
1023 $rows = [];
1024 $result = $queryBuilder->execute();
1025 while ($row = $result->fetch()) {
1026 $rows[$row['uid']] = $row;
1027 }
1028 if (!empty($rows)) {
1029 // Retrieve the parsed and prepared ORDER BY configuration for the resolver
1030 $sortby = $queryBuilder->getQueryPart('orderBy');
1031 $ids = $this->getResolver($foreign_table, array_keys($rows), $sortby)->get();
1032 foreach ($ids as $id) {
1033 $this->itemArray[$key]['id'] = $id;
1034 $this->itemArray[$key]['table'] = $foreign_table;
1035 $this->tableArray[$foreign_table][] = $id;
1036 $key++;
1037 }
1038 }
1039 }
1040
1041 /**
1042 * Write the sorting values to a foreign_table, that has a foreign_field (uid of the parent record)
1043 *
1044 * @param array $conf TCA configuration for current field
1045 * @param int $parentUid The uid of the parent record
1046 * @param int $updateToUid If this is larger than zero it will be used as foreign UID instead of the given $parentUid (on Copy)
1047 * @param bool $skipSorting Do not update the sorting columns, this could happen for imported values
1048 * @return void
1049 */
1050 public function writeForeignField($conf, $parentUid, $updateToUid = 0, $skipSorting = false)
1051 {
1052 if ($this->useLiveParentIds) {
1053 $parentUid = $this->getLiveDefaultId($this->currentTable, $parentUid);
1054 if (!empty($updateToUid)) {
1055 $updateToUid = $this->getLiveDefaultId($this->currentTable, $updateToUid);
1056 }
1057 }
1058
1059 $c = 0;
1060 $foreign_table = $conf['foreign_table'];
1061 $foreign_field = $conf['foreign_field'];
1062 $symmetric_field = $conf['symmetric_field'];
1063 $foreign_table_field = $conf['foreign_table_field'];
1064 $foreign_match_fields = is_array($conf['foreign_match_fields']) ? $conf['foreign_match_fields'] : [];
1065 // If there are table items and we have a proper $parentUid
1066 if (MathUtility::canBeInterpretedAsInteger($parentUid) && !empty($this->tableArray)) {
1067 // If updateToUid is not a positive integer, set it to '0', so it will be ignored
1068 if (!(MathUtility::canBeInterpretedAsInteger($updateToUid) && $updateToUid > 0)) {
1069 $updateToUid = 0;
1070 }
1071 $considerWorkspaces = BackendUtility::isTableWorkspaceEnabled($foreign_table);
1072 $fields = 'uid,pid,' . $foreign_field;
1073 // Consider the symmetric field if defined:
1074 if ($symmetric_field) {
1075 $fields .= ',' . $symmetric_field;
1076 }
1077 // Consider workspaces if defined and currently used:
1078 if ($considerWorkspaces) {
1079 $fields .= ',t3ver_wsid,t3ver_state,t3ver_oid';
1080 }
1081 // Update all items
1082 foreach ($this->itemArray as $val) {
1083 $uid = $val['id'];
1084 $table = $val['table'];
1085 $row = [];
1086 // Fetch the current (not overwritten) relation record if we should handle symmetric relations
1087 if ($symmetric_field || $considerWorkspaces) {
1088 $row = BackendUtility::getRecord($table, $uid, $fields, '', true);
1089 if (empty($row)) {
1090 continue;
1091 }
1092 }
1093 $isOnSymmetricSide = false;
1094 if ($symmetric_field) {
1095 $isOnSymmetricSide = self::isOnSymmetricSide($parentUid, $conf, $row);
1096 }
1097 $updateValues = $foreign_match_fields;
1098 // No update to the uid is requested, so this is the normal behaviour
1099 // just update the fields and care about sorting
1100 if (!$updateToUid) {
1101 // Always add the pointer to the parent uid
1102 if ($isOnSymmetricSide) {
1103 $updateValues[$symmetric_field] = $parentUid;
1104 } else {
1105 $updateValues[$foreign_field] = $parentUid;
1106 }
1107 // If it is configured in TCA also to store the parent table in the child record, just do it
1108 if ($foreign_table_field && $this->currentTable) {
1109 $updateValues[$foreign_table_field] = $this->currentTable;
1110 }
1111 // Update sorting columns if not to be skipped
1112 if (!$skipSorting) {
1113 // Get the correct sorting field
1114 // Specific manual sortby for data handled by this field
1115 $sortby = '';
1116 if ($conf['foreign_sortby']) {
1117 $sortby = $conf['foreign_sortby'];
1118 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) {
1119 // manual sortby for all table records
1120 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
1121 }
1122 // Apply sorting on the symmetric side
1123 // (it depends on who created the relation, so what uid is in the symmetric_field):
1124 if ($isOnSymmetricSide && isset($conf['symmetric_sortby']) && $conf['symmetric_sortby']) {
1125 $sortby = $conf['symmetric_sortby'];
1126 } else {
1127 $tempSortBy = [];
1128 foreach (QueryHelper::parseOrderBy($sortby) as $orderPair) {
1129 list($fieldName, $order) = $orderPair;
1130 if ($order !== null) {
1131 $tempSortBy[] = implode(' ', $orderPair);
1132 } else {
1133 $tempSortBy[] = $fieldName;
1134 }
1135 }
1136 $sortby = implode(',', $tempSortBy);
1137 }
1138 if ($sortby) {
1139 $updateValues[$sortby] = ++$c;
1140 }
1141 }
1142 } else {
1143 if ($isOnSymmetricSide) {
1144 $updateValues[$symmetric_field] = $updateToUid;
1145 } else {
1146 $updateValues[$foreign_field] = $updateToUid;
1147 }
1148 }
1149 // Update accordant fields in the database:
1150 if (!empty($updateValues)) {
1151 // Update tstamp if any foreign field value has changed
1152 if (!empty($GLOBALS['TCA'][$table]['ctrl']['tstamp'])) {
1153 $updateValues[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1154 }
1155 $this->getConnectionForTableName($table)
1156 ->update(
1157 $table,
1158 $updateValues,
1159 ['uid' => (int)$uid]
1160 );
1161 $this->updateRefIndex($table, $uid);
1162 }
1163 // Update accordant fields in the database for workspaces overlays/placeholders:
1164 if ($considerWorkspaces) {
1165 // It's the specific versioned record -> update placeholder (if any)
1166 if (!empty($row['t3ver_oid']) && VersionState::cast($row['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER_VERSION)) {
1167 $this->getConnectionForTableName($table)
1168 ->update(
1169 $table,
1170 $updateValues,
1171 ['uid' => (int)$row['t3ver_oid']]
1172 );
1173 }
1174 }
1175 }
1176 }
1177 }
1178
1179 /**
1180 * After initialization you can extract an array of the elements from the object. Use this function for that.
1181 *
1182 * @param bool $prependTableName If set, then table names will ALWAYS be prepended (unless its a _NO_TABLE value)
1183 * @return array A numeric array.
1184 */
1185 public function getValueArray($prependTableName = false)
1186 {
1187 // INIT:
1188 $valueArray = [];
1189 $tableC = count($this->tableArray);
1190 // If there are tables in the table array:
1191 if ($tableC) {
1192 // If there are more than ONE table in the table array, then always prepend table names:
1193 $prep = $tableC > 1 || $prependTableName;
1194 // Traverse the array of items:
1195 foreach ($this->itemArray as $val) {
1196 $valueArray[] = ($prep && $val['table'] != '_NO_TABLE' ? $val['table'] . '_' : '') . $val['id'];
1197 }
1198 }
1199 // Return the array
1200 return $valueArray;
1201 }
1202
1203 /**
1204 * Reads all records from internal tableArray into the internal ->results array
1205 * where keys are table names and for each table, records are stored with uids as their keys.
1206 * If $this->fetchAllFields is false you can save a little memory
1207 * since only uid,pid and a few other fields are selected.
1208 *
1209 * @return array
1210 */
1211 public function getFromDB()
1212 {
1213 // Traverses the tables listed:
1214 foreach ($this->tableArray as $table => $val) {
1215 if (is_array($val)) {
1216 $itemList = implode(',', $val);
1217 if ($itemList) {
1218 if ($this->fetchAllFields) {
1219 $fields = '*';
1220 } else {
1221 $fields = 'uid,pid';
1222 if ($GLOBALS['TCA'][$table]['ctrl']['label']) {
1223 // Titel
1224 $fields .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
1225 }
1226 if ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
1227 // Alternative Title-Fields
1228 $fields .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label_alt'];
1229 }
1230 if ($GLOBALS['TCA'][$table]['ctrl']['thumbnail']) {
1231 // Thumbnail
1232 $fields .= ',' . $GLOBALS['TCA'][$table]['ctrl']['thumbnail'];
1233 }
1234 }
1235 $queryBuilder = $this->getConnectionForTableName($table)
1236 ->createQueryBuilder();
1237 $queryBuilder->getRestrictions()->removeAll();
1238 $queryBuilder->select(...(GeneralUtility::trimExplode(',', $fields, true)))
1239 ->from($table)
1240 ->where($queryBuilder->expr()->in(
1241 'uid',
1242 $queryBuilder->createNamedParameter(
1243 GeneralUtility::intExplode(',', $itemList),
1244 Connection::PARAM_INT_ARRAY
1245 )
1246 ));
1247 if ($this->additionalWhere[$table]) {
1248 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->additionalWhere[$table]));
1249 }
1250 $statement = $queryBuilder->execute();
1251 while ($row = $statement->fetch()) {
1252 $this->results[$table][$row['uid']] = $row;
1253 }
1254 }
1255 }
1256 }
1257 return $this->results;
1258 }
1259
1260 /**
1261 * Prepare items from itemArray to be transferred to the TCEforms interface (as a comma list)
1262 *
1263 * @return string
1264 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
1265 */
1266 public function readyForInterface()
1267 {
1268 GeneralUtility::logDeprecatedFunction();
1269 if (!is_array($this->itemArray)) {
1270 return false;
1271 }
1272 $output = [];
1273 $titleLen = (int)$GLOBALS['BE_USER']->uc['titleLen'];
1274 foreach ($this->itemArray as $val) {
1275 $theRow = $this->results[$val['table']][$val['id']];
1276 if ($theRow && is_array($GLOBALS['TCA'][$val['table']])) {
1277 $label = GeneralUtility::fixed_lgd_cs(strip_tags(
1278 BackendUtility::getRecordTitle($val['table'], $theRow)), $titleLen);
1279 $label = $label ? $label : '[...]';
1280 $output[] = str_replace(',', '', $val['table'] . '_' . $val['id'] . '|' . rawurlencode($label));
1281 }
1282 }
1283 return implode(',', $output);
1284 }
1285
1286 /**
1287 * This method is typically called after getFromDB().
1288 * $this->results holds a list of resolved and valid relations,
1289 * $this->itemArray hold a list of "selected" relations from the incoming selection array.
1290 * The difference is that "itemArray" may hold a single table/uid combination multiple times,
1291 * for instance in a type=group relation having multiple=true, while "results" hold each
1292 * resolved relation only once.
1293 * The methods creates a sanitized "itemArray" from resolved "results" list, normalized
1294 * the return array to always contain both table name and uid, and keep incoming
1295 * "itemArray" sort order and keeps "multiple" selections.
1296 *
1297 * @return array
1298 */
1299 public function getResolvedItemArray(): array
1300 {
1301 $itemArray = [];
1302 foreach ($this->itemArray as $item) {
1303 if (isset($this->results[$item['table']][$item['id']])) {
1304 $itemArray[] = [
1305 'table' => $item['table'],
1306 'uid' => $item['id'],
1307 ];
1308 }
1309 }
1310 return $itemArray;
1311 }
1312
1313 /**
1314 * Counts the items in $this->itemArray and puts this value in an array by default.
1315 *
1316 * @param bool $returnAsArray Whether to put the count value in an array
1317 * @return mixed The plain count as integer or the same inside an array
1318 */
1319 public function countItems($returnAsArray = true)
1320 {
1321 $count = count($this->itemArray);
1322 if ($returnAsArray) {
1323 $count = [$count];
1324 }
1325 return $count;
1326 }
1327
1328 /**
1329 * Update Reference Index (sys_refindex) for a record
1330 * Should be called any almost any update to a record which could affect references inside the record.
1331 * (copied from DataHandler)
1332 *
1333 * @param string $table Table name
1334 * @param int $id Record UID
1335 * @return array Information concerning modifications delivered by \TYPO3\CMS\Core\Database\ReferenceIndex::updateRefIndexTable()
1336 */
1337 public function updateRefIndex($table, $id)
1338 {
1339 $statisticsArray = [];
1340 if ($this->updateReferenceIndex) {
1341 /** @var $refIndexObj \TYPO3\CMS\Core\Database\ReferenceIndex */
1342 $refIndexObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ReferenceIndex::class);
1343 if (BackendUtility::isTableWorkspaceEnabled($table)) {
1344 $refIndexObj->setWorkspaceId($this->getWorkspaceId());
1345 }
1346 $statisticsArray = $refIndexObj->updateRefIndexTable($table, $id);
1347 }
1348 return $statisticsArray;
1349 }
1350
1351 /**
1352 * Converts elements in the local item array to use version ids instead of
1353 * live ids, if possible. The most common use case is, to call that prior
1354 * to processing with MM relations in a workspace context. For tha special
1355 * case, ids on both side of the MM relation must use version ids if
1356 * available.
1357 *
1358 * @return bool Whether items have been converted
1359 */
1360 public function convertItemArray()
1361 {
1362 $hasBeenConverted = false;
1363
1364 // conversion is only required in a workspace context
1365 // (the case that version ids are submitted in a live context are rare)
1366 if ($this->getWorkspaceId() === 0) {
1367 return $hasBeenConverted;
1368 }
1369
1370 foreach ($this->tableArray as $tableName => $ids) {
1371 if (empty($ids) || !BackendUtility::isTableWorkspaceEnabled($tableName)) {
1372 continue;
1373 }
1374
1375 // convert live ids to version ids if available
1376 $convertedIds = $this->getResolver($tableName, $ids)
1377 ->setKeepDeletePlaceholder(false)
1378 ->setKeepMovePlaceholder(false)
1379 ->processVersionOverlays($ids);
1380 foreach ($this->itemArray as $index => $item) {
1381 if ($item['table'] !== $tableName) {
1382 continue;
1383 }
1384 $currentItemId = $item['id'];
1385 if (
1386 !isset($convertedIds[$currentItemId])
1387 || $currentItemId === $convertedIds[$currentItemId]
1388 ) {
1389 continue;
1390 }
1391 // adjust local item to use resolved version id
1392 $this->itemArray[$index]['id'] = $convertedIds[$currentItemId];
1393 $hasBeenConverted = true;
1394 }
1395 // update per-table reference for ids
1396 if ($hasBeenConverted) {
1397 $this->tableArray[$tableName] = array_values($convertedIds);
1398 }
1399 }
1400
1401 return $hasBeenConverted;
1402 }
1403
1404 /**
1405 * @param NULL|int $workspaceId
1406 * @return bool Whether items have been purged
1407 */
1408 public function purgeItemArray($workspaceId = null)
1409 {
1410 if ($workspaceId === null) {
1411 $workspaceId = $this->getWorkspaceId();
1412 } else {
1413 $workspaceId = (int)$workspaceId;
1414 }
1415
1416 // Ensure, only live relations are in the items Array
1417 if ($workspaceId === 0) {
1418 $purgeCallback = 'purgeVersionedIds';
1419 // Otherwise, ensure that live relations are purged if version exists
1420 } else {
1421 $purgeCallback = 'purgeLiveVersionedIds';
1422 }
1423
1424 $itemArrayHasBeenPurged = $this->purgeItemArrayHandler($purgeCallback);
1425 $this->purged = ($this->purged || $itemArrayHasBeenPurged);
1426 return $itemArrayHasBeenPurged;
1427 }
1428
1429 /**
1430 * Removes items having a delete placeholder from $this->itemArray
1431 *
1432 * @return bool Whether items have been purged
1433 */
1434 public function processDeletePlaceholder()
1435 {
1436 if (!$this->useLiveReferenceIds || $this->getWorkspaceId() === 0) {
1437 return false;
1438 }
1439
1440 return $this->purgeItemArrayHandler('purgeDeletePlaceholder');
1441 }
1442
1443 /**
1444 * Handles a purge callback on $this->itemArray
1445 *
1446 * @param callable $purgeCallback
1447 * @return bool Whether items have been purged
1448 */
1449 protected function purgeItemArrayHandler($purgeCallback)
1450 {
1451 $itemArrayHasBeenPurged = false;
1452
1453 foreach ($this->tableArray as $itemTableName => $itemIds) {
1454 if (empty($itemIds) || !BackendUtility::isTableWorkspaceEnabled($itemTableName)) {
1455 continue;
1456 }
1457
1458 $purgedItemIds = call_user_func([$this, $purgeCallback], $itemTableName, $itemIds);
1459 $removedItemIds = array_diff($itemIds, $purgedItemIds);
1460 foreach ($removedItemIds as $removedItemId) {
1461 $this->removeFromItemArray($itemTableName, $removedItemId);
1462 }
1463 $this->tableArray[$itemTableName] = $purgedItemIds;
1464 if (!empty($removedItemIds)) {
1465 $itemArrayHasBeenPurged = true;
1466 }
1467 }
1468
1469 return $itemArrayHasBeenPurged;
1470 }
1471
1472 /**
1473 * Purges ids that are versioned.
1474 *
1475 * @param string $tableName
1476 * @param array $ids
1477 * @return array
1478 */
1479 protected function purgeVersionedIds($tableName, array $ids)
1480 {
1481 $ids = array_combine($ids, $ids);
1482
1483 $queryBuilder = $this->getConnectionForTableName($tableName)
1484 ->createQueryBuilder();
1485 $queryBuilder->getRestrictions()->removeAll();
1486 $versions = $queryBuilder->select('uid', 't3ver_oid', 't3ver_state')
1487 ->from($tableName)
1488 ->where(
1489 $queryBuilder->expr()->eq(
1490 'pid',
1491 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1492 ),
1493 $queryBuilder->expr()->in(
1494 't3ver_oid',
1495 $queryBuilder->createNamedParameter($ids, Connection::PARAM_INT_ARRAY)
1496 ),
1497 $queryBuilder->expr()->neq(
1498 't3ver_wsid',
1499 $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
1500 )
1501 )
1502 ->orderBy('t3ver_state', 'DESC')
1503 ->execute()
1504 ->fetchAll();
1505
1506 if (!empty($versions)) {
1507 foreach ($versions as $version) {
1508 $versionId = $version['uid'];
1509 if (isset($ids[$versionId])) {
1510 unset($ids[$versionId]);
1511 }
1512 }
1513 }
1514
1515 return array_values($ids);
1516 }
1517
1518 /**
1519 * Purges ids that are live but have an accordant version.
1520 *
1521 * @param string $tableName
1522 * @param array $ids
1523 * @return array
1524 */
1525 protected function purgeLiveVersionedIds($tableName, array $ids)
1526 {
1527 $ids = array_combine($ids, $ids);
1528
1529 $queryBuilder = $this->getConnectionForTableName($tableName)
1530 ->createQueryBuilder();
1531 $queryBuilder->getRestrictions()->removeAll();
1532 $versions = $queryBuilder->select('uid', 't3ver_oid', 't3ver_state')
1533 ->from($tableName)
1534 ->where(
1535 $queryBuilder->expr()->eq(
1536 'pid',
1537 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1538 ),
1539 $queryBuilder->expr()->in(
1540 't3ver_oid',
1541 $queryBuilder->createNamedParameter($ids, Connection::PARAM_INT_ARRAY)
1542 ),
1543 $queryBuilder->expr()->neq(
1544 't3ver_wsid',
1545 $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
1546 )
1547 )
1548 ->orderBy('t3ver_state', 'DESC')
1549 ->execute()
1550 ->fetchAll();
1551
1552 if (!empty($versions)) {
1553 foreach ($versions as $version) {
1554 $versionId = $version['uid'];
1555 $liveId = $version['t3ver_oid'];
1556 if (isset($ids[$liveId]) && isset($ids[$versionId])) {
1557 unset($ids[$liveId]);
1558 }
1559 }
1560 }
1561
1562 return array_values($ids);
1563 }
1564
1565 /**
1566 * Purges ids that have a delete placeholder
1567 *
1568 * @param string $tableName
1569 * @param array $ids
1570 * @return array
1571 */
1572 protected function purgeDeletePlaceholder($tableName, array $ids)
1573 {
1574 $ids = array_combine($ids, $ids);
1575
1576 $queryBuilder = $this->getConnectionForTableName($tableName)
1577 ->createQueryBuilder();
1578 $queryBuilder->getRestrictions()->removeAll();
1579 $versions = $queryBuilder->select('uid', 't3ver_oid', 't3ver_state')
1580 ->from($tableName)
1581 ->where(
1582 $queryBuilder->expr()->eq(
1583 'pid',
1584 $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
1585 ),
1586 $queryBuilder->expr()->in(
1587 't3ver_oid',
1588 $queryBuilder->createNamedParameter($ids, Connection::PARAM_INT_ARRAY)
1589 ),
1590 $queryBuilder->expr()->neq(
1591 't3ver_wsid',
1592 $queryBuilder->createNamedParameter(
1593 $this->getWorkspaceId(),
1594 \PDO::PARAM_INT
1595 )
1596 ),
1597 $queryBuilder->expr()->eq(
1598 't3ver_state',
1599 $queryBuilder->createNamedParameter(
1600 (string)VersionState::cast(VersionState::DELETE_PLACEHOLDER),
1601 \PDO::PARAM_INT
1602 )
1603 )
1604 )
1605 ->execute()
1606 ->fetchAll();
1607
1608 if (!empty($versions)) {
1609 foreach ($versions as $version) {
1610 $liveId = $version['t3ver_oid'];
1611 if (isset($ids[$liveId])) {
1612 unset($ids[$liveId]);
1613 }
1614 }
1615 }
1616
1617 return array_values($ids);
1618 }
1619
1620 protected function removeFromItemArray($tableName, $id)
1621 {
1622 foreach ($this->itemArray as $index => $item) {
1623 if ($item['table'] === $tableName && (string)$item['id'] === (string)$id) {
1624 unset($this->itemArray[$index]);
1625 return true;
1626 }
1627 }
1628 return false;
1629 }
1630
1631 /**
1632 * Checks, if we're looking from the "other" side, the symmetric side, to a symmetric relation.
1633 *
1634 * @param string $parentUid The uid of the parent record
1635 * @param array $parentConf The TCA configuration of the parent field embedding the child records
1636 * @param array $childRec The record row of the child record
1637 * @return bool Returns TRUE if looking from the symmetric ("other") side to the relation.
1638 */
1639 public static function isOnSymmetricSide($parentUid, $parentConf, $childRec)
1640 {
1641 return MathUtility::canBeInterpretedAsInteger($childRec['uid'])
1642 && $parentConf['symmetric_field']
1643 && $parentUid == $childRec[$parentConf['symmetric_field']];
1644 }
1645
1646 /**
1647 * Completes MM values to be written by values from the opposite relation.
1648 * This method used MM insert field or MM match fields if defined.
1649 *
1650 * @param string $tableName Name of the opposite table
1651 * @param array $referenceValues Values to be written
1652 * @return array Values to be written, possibly modified
1653 */
1654 protected function completeOppositeUsageValues($tableName, array $referenceValues)
1655 {
1656 if (empty($this->MM_oppositeUsage[$tableName]) || count($this->MM_oppositeUsage[$tableName]) > 1) {
1657 return $referenceValues;
1658 }
1659
1660 $fieldName = $this->MM_oppositeUsage[$tableName][0];
1661 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'])) {
1662 return $referenceValues;
1663 }
1664
1665 $configuration = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
1666 if (!empty($configuration['MM_insert_fields'])) {
1667 $referenceValues = array_merge($configuration['MM_insert_fields'], $referenceValues);
1668 } elseif (!empty($configuration['MM_match_fields'])) {
1669 $referenceValues = array_merge($configuration['MM_match_fields'], $referenceValues);
1670 }
1671
1672 return $referenceValues;
1673 }
1674
1675 /**
1676 * Gets the record uid of the live default record. If already
1677 * pointing to the live record, the submitted record uid is returned.
1678 *
1679 * @param string $tableName
1680 * @param int $id
1681 * @return int
1682 */
1683 protected function getLiveDefaultId($tableName, $id)
1684 {
1685 $liveDefaultId = BackendUtility::getLiveVersionIdOfRecord($tableName, $id);
1686 if ($liveDefaultId === null) {
1687 $liveDefaultId = $id;
1688 }
1689 return (int)$liveDefaultId;
1690 }
1691
1692 /**
1693 * @param string $tableName
1694 * @param int[] $ids
1695 * @param array $sortingStatement
1696 * @return PlainDataResolver
1697 */
1698 protected function getResolver($tableName, array $ids, array $sortingStatement = null)
1699 {
1700 /** @var PlainDataResolver $resolver */
1701 $resolver = GeneralUtility::makeInstance(
1702 PlainDataResolver::class,
1703 $tableName,
1704 $ids,
1705 $sortingStatement
1706 );
1707 $resolver->setWorkspaceId($this->getWorkspaceId());
1708 $resolver->setKeepDeletePlaceholder(true);
1709 $resolver->setKeepLiveIds($this->useLiveReferenceIds);
1710 return $resolver;
1711 }
1712
1713 /**
1714 * @param string $tableName
1715 * @return Connection
1716 */
1717 protected function getConnectionForTableName(string $tableName)
1718 {
1719 return GeneralUtility::makeInstance(ConnectionPool::class)
1720 ->getConnectionForTable($tableName);
1721 }
1722 }