[TASK] Superfluous comparison in RelationHandler
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Database / RelationHandler.php
1 <?php
2 namespace TYPO3\CMS\Core\Database;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 use TYPO3\CMS\Backend\Utility\BackendUtility;
31 use TYPO3\CMS\Core\Utility\GeneralUtility;
32 use TYPO3\CMS\Core\Utility\MathUtility;
33 use TYPO3\CMS\Core\Versioning\VersionState;
34
35 /**
36 * Load database groups (relations)
37 * Used to process the relations created by the TCA element types "group" and "select" for database records.
38 * Manages MM-relations as well.
39 *
40 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
41 */
42 class RelationHandler {
43
44 /**
45 * $fetchAllFields if false getFromDB() fetches only uid, pid, thumbnail and label fields (as defined in TCA)
46 *
47 * @var boolean
48 */
49 protected $fetchAllFields = FALSE;
50
51 /**
52 * If set, values that are not ids in tables are normally discarded. By this options they will be preserved.
53 * @todo Define visibility
54 */
55 public $registerNonTableValues = 0;
56
57 /**
58 * Contains the table names as keys. The values are the id-values for each table.
59 * Should ONLY contain proper table names.
60 *
61 * @var array
62 * @todo Define visibility
63 */
64 public $tableArray = array();
65
66 /**
67 * Contains items in an numeric array (table/id for each). Tablenames here might be "_NO_TABLE"
68 *
69 * @var array
70 * @todo Define visibility
71 */
72 public $itemArray = array();
73
74 /**
75 * Array for NON-table elements
76 *
77 * @var array
78 * @todo Define visibility
79 */
80 public $nonTableArray = array();
81
82 /**
83 * @var array
84 * @todo Define visibility
85 */
86 public $additionalWhere = array();
87
88 /**
89 * Deleted-column is added to additionalWhere... if this is set...
90 *
91 * @var boolean
92 * @todo Define visibility
93 */
94 public $checkIfDeleted = TRUE;
95
96 /**
97 * @var array
98 * @todo Define visibility
99 */
100 public $dbPaths = array();
101
102 /**
103 * Will contain the first table name in the $tablelist (for positive ids)
104 *
105 * @var string
106 * @todo Define visibility
107 */
108 public $firstTable = '';
109
110 /**
111 * Will contain the second table name in the $tablelist (for negative ids)
112 *
113 * @var string
114 * @todo Define visibility
115 */
116 public $secondTable = '';
117
118 /**
119 * If TRUE, uid_local and uid_foreign are switched, and the current table
120 * is inserted as tablename - this means you display a foreign relation "from the opposite side"
121 *
122 * @var boolean
123 * @todo Define visibility
124 */
125 public $MM_is_foreign = FALSE;
126
127 /**
128 * Field name at the "local" side of the MM relation
129 *
130 * @var string
131 * @todo Define visibility
132 */
133 public $MM_oppositeField = '';
134
135 /**
136 * Only set if MM_is_foreign is set
137 *
138 * @var string
139 * @todo Define visibility
140 */
141 public $MM_oppositeTable = '';
142
143 /**
144 * Only set if MM_is_foreign is set
145 *
146 * @var string
147 * @todo Define visibility
148 */
149 public $MM_oppositeFieldConf = '';
150
151 /**
152 * Is empty by default; if MM_is_foreign is set and there is more than one table
153 * allowed (on the "local" side), then it contains the first table (as a fallback)
154 * @todo Define visibility
155 * @var string
156 */
157 public $MM_isMultiTableRelationship = '';
158
159 /**
160 * Current table => Only needed for reverse relations
161 *
162 * @var string
163 * @todo Define visibility
164 */
165 public $currentTable;
166
167 /**
168 * If a record should be undeleted
169 * (so do not use the $useDeleteClause on \TYPO3\CMS\Backend\Utility\BackendUtility)
170 *
171 * @var boolean
172 * @todo Define visibility
173 */
174 public $undeleteRecord;
175
176 /**
177 * Array of fields value pairs that should match while SELECT
178 * and will be written into MM table if $MM_insert_fields is not set
179 *
180 * @var array
181 * @todo Define visibility
182 */
183 public $MM_match_fields = array();
184
185 /**
186 * This is set to TRUE if the MM table has a UID field.
187 *
188 * @var boolean
189 * @todo Define visibility
190 */
191 public $MM_hasUidField;
192
193 /**
194 * Array of fields and value pairs used for insert in MM table
195 *
196 * @var array
197 * @todo Define visibility
198 */
199 public $MM_insert_fields = array();
200
201 /**
202 * Extra MM table where
203 *
204 * @var string
205 * @todo Define visibility
206 */
207 public $MM_table_where = '';
208
209 /**
210 * @var boolean
211 */
212 protected $updateReferenceIndex = TRUE;
213
214 /**
215 * This array will be filled by getFromDB().
216 *
217 * @var array
218 */
219 public $results = array();
220
221 /**
222 * Initialization of the class.
223 *
224 * @param string $itemlist List of group/select items
225 * @param string $tablelist Comma list of tables, first table takes priority if no table is set for an entry in the list.
226 * @param string $MMtable Name of a MM table.
227 * @param integer $MMuid Local UID for MM lookup
228 * @param string $currentTable Current table name
229 * @param array $conf TCA configuration for current field
230 * @return void
231 * @todo Define visibility
232 */
233 public function start($itemlist, $tablelist, $MMtable = '', $MMuid = 0, $currentTable = '', $conf = array()) {
234 // SECTION: MM reverse relations
235 $this->MM_is_foreign = (boolean)$conf['MM_opposite_field'];
236 $this->MM_oppositeField = $conf['MM_opposite_field'];
237 $this->MM_table_where = $conf['MM_table_where'];
238 $this->MM_hasUidField = $conf['MM_hasUidField'];
239 $this->MM_match_fields = is_array($conf['MM_match_fields']) ? $conf['MM_match_fields'] : array();
240 $this->MM_insert_fields = is_array($conf['MM_insert_fields']) ? $conf['MM_insert_fields'] : $this->MM_match_fields;
241 $this->currentTable = $currentTable;
242 if ($this->MM_is_foreign) {
243 $tmp = $conf['type'] === 'group' ? $conf['allowed'] : $conf['foreign_table'];
244 // Normally, $conf['allowed'] can contain a list of tables,
245 // but as we are looking at a MM relation from the foreign side,
246 // it only makes sense to allow one one table in $conf['allowed']
247 $tmp = GeneralUtility::trimExplode(',', $tmp);
248 $this->MM_oppositeTable = $tmp[0];
249 unset($tmp);
250 // Only add the current table name if there is more than one allowed field
251 // We must be sure this has been done at least once before accessing the "columns" part of TCA for a table.
252 $this->MM_oppositeFieldConf = $GLOBALS['TCA'][$this->MM_oppositeTable]['columns'][$this->MM_oppositeField]['config'];
253 if ($this->MM_oppositeFieldConf['allowed']) {
254 $oppositeFieldConf_allowed = explode(',', $this->MM_oppositeFieldConf['allowed']);
255 if (count($oppositeFieldConf_allowed) > 1 || $this->MM_oppositeFieldConf['allowed'] === '*') {
256 $this->MM_isMultiTableRelationship = $oppositeFieldConf_allowed[0];
257 }
258 }
259 }
260 // SECTION: normal MM relations
261 // If the table list is "*" then all tables are used in the list:
262 if (!strcmp(trim($tablelist), '*')) {
263 $tablelist = implode(',', array_keys($GLOBALS['TCA']));
264 }
265 // The tables are traversed and internal arrays are initialized:
266 $tempTableArray = GeneralUtility::trimExplode(',', $tablelist, TRUE);
267 foreach ($tempTableArray as $val) {
268 $tName = trim($val);
269 $this->tableArray[$tName] = array();
270 if ($this->checkIfDeleted && $GLOBALS['TCA'][$tName]['ctrl']['delete']) {
271 $fieldN = $tName . '.' . $GLOBALS['TCA'][$tName]['ctrl']['delete'];
272 $this->additionalWhere[$tName] .= ' AND ' . $fieldN . '=0';
273 }
274 }
275 if (is_array($this->tableArray)) {
276 reset($this->tableArray);
277 } else {
278 // No tables
279 return;
280 }
281 // Set first and second tables:
282 // Is the first table
283 $this->firstTable = key($this->tableArray);
284 next($this->tableArray);
285 // If the second table is set and the ID number is less than zero (later)
286 // then the record is regarded to come from the second table...
287 $this->secondTable = key($this->tableArray);
288 // Now, populate the internal itemArray and tableArray arrays:
289 // If MM, then call this function to do that:
290 if ($MMtable) {
291 if ($MMuid) {
292 $this->readMM($MMtable, $MMuid);
293 } else {
294 // Revert to readList() for new records in order to load possible default values from $itemlist
295 $this->readList($itemlist);
296 }
297 } elseif ($MMuid && $conf['foreign_field']) {
298 // If not MM but foreign_field, the read the records by the foreign_field
299 $this->readForeignField($MMuid, $conf);
300 } else {
301 // If not MM, then explode the itemlist by "," and traverse the list:
302 $this->readList($itemlist);
303 // Do automatic default_sortby, if any
304 if ($conf['foreign_default_sortby']) {
305 $this->sortList($conf['foreign_default_sortby']);
306 }
307 }
308 }
309
310 /**
311 * Magic setter method.
312 * Used for compatibility with changed attribute visibility
313 *
314 * @param string $name name of the attribute
315 * @param mixed $value value to set the attribute to
316 * @deprecated since 6.1, only required as compatibility layer for renamed attribute $fromTC
317 */
318 public function __set($name, $value) {
319 if($name === 'fromTC') {
320 GeneralUtility::deprecationLog(
321 '$fromTC is protected since TYPO3 6.1. Use setFetchAllFields() instead!'
322 );
323 $this->setFetchAllFields(!$value);
324 }
325 }
326
327 /**
328 * Sets $fetchAllFields
329 *
330 * @param boolean $allFields enables fetching of all fields in getFromDB()
331 */
332 public function setFetchAllFields($allFields) {
333 $this->fetchAllFields = (boolean)$allFields;
334 }
335
336 /**
337 * Sets whether the reference index shall be updated.
338 *
339 * @param boolean $updateReferenceIndex Whether the reference index shall be updated
340 * @return void
341 */
342 public function setUpdateReferenceIndex($updateReferenceIndex) {
343 $this->updateReferenceIndex = (boolean)$updateReferenceIndex;
344 }
345
346 /**
347 * Explodes the item list and stores the parts in the internal arrays itemArray and tableArray from MM records.
348 *
349 * @param string $itemlist Item list
350 * @return void
351 * @todo Define visibility
352 */
353 public function readList($itemlist) {
354 if ((string) trim($itemlist) != '') {
355 $tempItemArray = GeneralUtility::trimExplode(',', $itemlist);
356 // Changed to trimExplode 31/3 04; HMENU special type "list" didn't work
357 // if there were spaces in the list... I suppose this is better overall...
358 foreach ($tempItemArray as $key => $val) {
359 // Will be set to "1" if the entry was a real table/id:
360 $isSet = 0;
361 // Extract table name and id. This is un the formular [tablename]_[id]
362 // where table name MIGHT contain "_", hence the reversion of the string!
363 $val = strrev($val);
364 $parts = explode('_', $val, 2);
365 $theID = strrev($parts[0]);
366 // Check that the id IS an integer:
367 if (MathUtility::canBeInterpretedAsInteger($theID)) {
368 // Get the table name: If a part of the exploded string, use that.
369 // Otherwise if the id number is LESS than zero, use the second table, otherwise the first table
370 $theTable = trim($parts[1])
371 ? strrev(trim($parts[1]))
372 : ($this->secondTable && $theID < 0 ? $this->secondTable : $this->firstTable);
373 // If the ID is not blank and the table name is among the names in the inputted tableList
374 if (((string) $theID != '' && $theID) && $theTable && isset($this->tableArray[$theTable])) {
375 // Get ID as the right value:
376 $theID = $this->secondTable ? abs(intval($theID)) : intval($theID);
377 // Register ID/table name in internal arrays:
378 $this->itemArray[$key]['id'] = $theID;
379 $this->itemArray[$key]['table'] = $theTable;
380 $this->tableArray[$theTable][] = $theID;
381 // Set update-flag:
382 $isSet = 1;
383 }
384 }
385 // If it turns out that the value from the list was NOT a valid reference to a table-record,
386 // then we might still set it as a NO_TABLE value:
387 if (!$isSet && $this->registerNonTableValues) {
388 $this->itemArray[$key]['id'] = $tempItemArray[$key];
389 $this->itemArray[$key]['table'] = '_NO_TABLE';
390 $this->nonTableArray[] = $tempItemArray[$key];
391 }
392 }
393 }
394 }
395
396 /**
397 * Does a sorting on $this->itemArray depending on a default sortby field.
398 * This is only used for automatic sorting of comma separated lists.
399 * This function is only relevant for data that is stored in comma separated lists!
400 *
401 * @param string $sortby The default_sortby field/command (e.g. 'price DESC')
402 * @return void
403 * @todo Define visibility
404 */
405 public function sortList($sortby) {
406 // Sort directly without fetching addional data
407 if ($sortby == 'uid') {
408 usort(
409 $this->itemArray,
410 function ($a, $b) {
411 return $a['id'] < $b['id'] ? -1 : 1;
412 }
413 );
414 } elseif (count($this->tableArray) == 1) {
415 reset($this->tableArray);
416 $table = key($this->tableArray);
417 $uidList = implode(',', current($this->tableArray));
418 if ($uidList) {
419 $this->itemArray = array();
420 $this->tableArray = array();
421 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'uid IN (' . $uidList . ')', '', $sortby);
422 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
423 $this->itemArray[] = array('id' => $row['uid'], 'table' => $table);
424 $this->tableArray[$table][] = $row['uid'];
425 }
426 $GLOBALS['TYPO3_DB']->sql_free_result($res);
427 }
428 }
429 }
430
431 /**
432 * Reads the record tablename/id into the internal arrays itemArray and tableArray from MM records.
433 * You can call this function after start if you supply no list to start()
434 *
435 * @param string $tableName MM Tablename
436 * @param integer $uid Local UID
437 * @return void
438 * @todo Define visibility
439 */
440 public function readMM($tableName, $uid) {
441 $key = 0;
442 $additionalWhere = '';
443 $theTable = NULL;
444 // In case of a reverse relation
445 if ($this->MM_is_foreign) {
446 $uidLocal_field = 'uid_foreign';
447 $uidForeign_field = 'uid_local';
448 $sorting_field = 'sorting_foreign';
449 if ($this->MM_isMultiTableRelationship) {
450 $additionalWhere .= ' AND ( tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable, $tableName);
451 // Be backwards compatible! When allowing more than one table after
452 // having previously allowed only one table, this case applies.
453 if ($this->currentTable == $this->MM_isMultiTableRelationship) {
454 $additionalWhere .= ' OR tablenames=\'\'';
455 }
456 $additionalWhere .= ' ) ';
457 }
458 $theTable = $this->MM_oppositeTable;
459 } else {
460 // Default
461 $uidLocal_field = 'uid_local';
462 $uidForeign_field = 'uid_foreign';
463 $sorting_field = 'sorting';
464 }
465 if ($this->MM_table_where) {
466 $additionalWhere .= LF . str_replace('###THIS_UID###', intval($uid), $this->MM_table_where);
467 }
468 foreach ($this->MM_match_fields as $field => $value) {
469 $additionalWhere .= ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $tableName);
470 }
471 // Select all MM relations:
472 $where = $uidLocal_field . '=' . intval($uid) . $additionalWhere;
473 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $tableName, $where, '', $sorting_field);
474 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
475 // Default
476 if (!$this->MM_is_foreign) {
477 // If tablesnames columns exists and contain a name, then this value is the table, else it's the firstTable...
478 $theTable = $row['tablenames'] ? $row['tablenames'] : $this->firstTable;
479 }
480 if (($row[$uidForeign_field] || $theTable == 'pages') && $theTable && isset($this->tableArray[$theTable])) {
481 $this->itemArray[$key]['id'] = $row[$uidForeign_field];
482 $this->itemArray[$key]['table'] = $theTable;
483 $this->tableArray[$theTable][] = $row[$uidForeign_field];
484 } elseif ($this->registerNonTableValues) {
485 $this->itemArray[$key]['id'] = $row[$uidForeign_field];
486 $this->itemArray[$key]['table'] = '_NO_TABLE';
487 $this->nonTableArray[] = $row[$uidForeign_field];
488 }
489 $key++;
490 }
491 $GLOBALS['TYPO3_DB']->sql_free_result($res);
492 }
493
494 /**
495 * Writes the internal itemArray to MM table:
496 *
497 * @param string $MM_tableName MM table name
498 * @param integer $uid Local UID
499 * @param boolean $prependTableName If set, then table names will always be written.
500 * @return void
501 * @todo Define visibility
502 */
503 public function writeMM($MM_tableName, $uid, $prependTableName = FALSE) {
504 // In case of a reverse relation
505 if ($this->MM_is_foreign) {
506 $uidLocal_field = 'uid_foreign';
507 $uidForeign_field = 'uid_local';
508 $sorting_field = 'sorting_foreign';
509 } else {
510 // default
511 $uidLocal_field = 'uid_local';
512 $uidForeign_field = 'uid_foreign';
513 $sorting_field = 'sorting';
514 }
515 // If there are tables...
516 $tableC = count($this->tableArray);
517 if ($tableC) {
518 // Boolean: does the field "tablename" need to be filled?
519 $prep = $tableC > 1 || $prependTableName || $this->MM_isMultiTableRelationship ? 1 : 0;
520 $c = 0;
521 $additionalWhere_tablenames = '';
522 if ($this->MM_is_foreign && $prep) {
523 $additionalWhere_tablenames = ' AND tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable, $MM_tableName);
524 }
525 $additionalWhere = '';
526 // Add WHERE clause if configured
527 if ($this->MM_table_where) {
528 $additionalWhere .= LF . str_replace('###THIS_UID###', intval($uid), $this->MM_table_where);
529 }
530 // Select, update or delete only those relations that match the configured fields
531 foreach ($this->MM_match_fields as $field => $value) {
532 $additionalWhere .= ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $MM_tableName);
533 }
534 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
535 $uidForeign_field . ($prep ? ', tablenames' : '') . ($this->MM_hasUidField ? ', uid' : ''),
536 $MM_tableName,
537 $uidLocal_field . '=' . $uid . $additionalWhere_tablenames . $additionalWhere,
538 '',
539 $sorting_field
540 );
541 $oldMMs = array();
542 // This array is similar to $oldMMs but also holds the uid of the MM-records, if any (configured by MM_hasUidField).
543 // If the UID is present it will be used to update sorting and delete MM-records.
544 // This is necessary if the "multiple" feature is used for the MM relations.
545 // $oldMMs is still needed for the in_array() search used to look if an item from $this->itemArray is in $oldMMs
546 $oldMMs_inclUid = array();
547 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
548 if (!$this->MM_is_foreign && $prep) {
549 $oldMMs[] = array($row['tablenames'], $row[$uidForeign_field]);
550 } else {
551 $oldMMs[] = $row[$uidForeign_field];
552 }
553 $oldMMs_inclUid[] = array($row['tablenames'], $row[$uidForeign_field], $row['uid']);
554 }
555 $GLOBALS['TYPO3_DB']->sql_free_result($res);
556 // For each item, insert it:
557 foreach ($this->itemArray as $val) {
558 $c++;
559 if ($prep || $val['table'] == '_NO_TABLE') {
560 // Insert current table if needed
561 if ($this->MM_is_foreign) {
562 $tablename = $this->currentTable;
563 } else {
564 $tablename = $val['table'];
565 }
566 } else {
567 $tablename = '';
568 }
569 if (!$this->MM_is_foreign && $prep) {
570 $item = array($val['table'], $val['id']);
571 } else {
572 $item = $val['id'];
573 }
574 if (in_array($item, $oldMMs)) {
575 $oldMMs_index = array_search($item, $oldMMs);
576 // In principle, selecting on the UID is all we need to do
577 // if a uid field is available since that is unique!
578 // But as long as it "doesn't hurt" we just add it to the where clause. It should all match up.
579 $whereClause = $uidLocal_field . '=' . $uid . ' AND ' . $uidForeign_field . '=' . $val['id']
580 . ($this->MM_hasUidField ? ' AND uid=' . intval($oldMMs_inclUid[$oldMMs_index][2]) : '');
581 if ($tablename) {
582 $whereClause .= ' AND tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tablename, $MM_tableName);
583 }
584 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($MM_tableName, $whereClause . $additionalWhere, array($sorting_field => $c));
585 // Remove the item from the $oldMMs array so after this
586 // foreach loop only the ones that need to be deleted are in there.
587 unset($oldMMs[$oldMMs_index]);
588 // Remove the item from the $oldMMs_inclUid array so after this
589 // foreach loop only the ones that need to be deleted are in there.
590 unset($oldMMs_inclUid[$oldMMs_index]);
591 } else {
592 $insertFields = $this->MM_insert_fields;
593 $insertFields[$uidLocal_field] = $uid;
594 $insertFields[$uidForeign_field] = $val['id'];
595 $insertFields[$sorting_field] = $c;
596 if ($tablename) {
597 $insertFields['tablenames'] = $tablename;
598 }
599 $GLOBALS['TYPO3_DB']->exec_INSERTquery($MM_tableName, $insertFields);
600 if ($this->MM_is_foreign) {
601 $this->updateRefIndex($val['table'], $val['id']);
602 }
603 }
604 }
605 // Delete all not-used relations:
606 if (is_array($oldMMs) && count($oldMMs) > 0) {
607 $removeClauses = array();
608 $updateRefIndex_records = array();
609 foreach ($oldMMs as $oldMM_key => $mmItem) {
610 // If UID field is present, of course we need only use that for deleting.
611 if ($this->MM_hasUidField) {
612 $removeClauses[] = 'uid=' . intval($oldMMs_inclUid[$oldMM_key][2]);
613 } else {
614 if (is_array($mmItem)) {
615 $removeClauses[] = 'tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($mmItem[0], $MM_tableName)
616 . ' AND ' . $uidForeign_field . '=' . $mmItem[1];
617 } else {
618 $removeClauses[] = $uidForeign_field . '=' . $mmItem;
619 }
620 }
621 if ($this->MM_is_foreign) {
622 if (is_array($mmItem)) {
623 $updateRefIndex_records[] = array($mmItem[0], $mmItem[1]);
624 } else {
625 $updateRefIndex_records[] = array($this->firstTable, $mmItem);
626 }
627 }
628 }
629 $deleteAddWhere = ' AND (' . implode(' OR ', $removeClauses) . ')';
630 $where = $uidLocal_field . '=' . intval($uid) . $deleteAddWhere . $additionalWhere_tablenames . $additionalWhere;
631 $GLOBALS['TYPO3_DB']->exec_DELETEquery($MM_tableName, $where);
632 // Update ref index:
633 foreach ($updateRefIndex_records as $pair) {
634 $this->updateRefIndex($pair[0], $pair[1]);
635 }
636 }
637 // Update ref index; In tcemain it is not certain that this will happen because
638 // if only the MM field is changed the record itself is not updated and so the ref-index is not either.
639 // This could also have been fixed in updateDB in tcemain, however I decided to do it here ...
640 $this->updateRefIndex($this->currentTable, $uid);
641 }
642 }
643
644 /**
645 * Remaps MM table elements from one local uid to another
646 * Does NOT update the reference index for you, must be called subsequently to do that!
647 *
648 * @param string $MM_tableName MM table name
649 * @param integer $uid Local, current UID
650 * @param integer $newUid Local, new UID
651 * @param boolean $prependTableName If set, then table names will always be written.
652 * @return void
653 * @todo Define visibility
654 */
655 public function remapMM($MM_tableName, $uid, $newUid, $prependTableName = FALSE) {
656 // In case of a reverse relation
657 if ($this->MM_is_foreign) {
658 $uidLocal_field = 'uid_foreign';
659 } else {
660 // default
661 $uidLocal_field = 'uid_local';
662 }
663 // If there are tables...
664 $tableC = count($this->tableArray);
665 if ($tableC) {
666 // Boolean: does the field "tablename" need to be filled?
667 $prep = $tableC > 1 || $prependTableName || $this->MM_isMultiTableRelationship;
668 $additionalWhere_tablenames = '';
669 if ($this->MM_is_foreign && $prep) {
670 $additionalWhere_tablenames = ' AND tablenames=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable, $MM_tableName);
671 }
672 $additionalWhere = '';
673 // Add WHERE clause if configured
674 if ($this->MM_table_where) {
675 $additionalWhere .= LF . str_replace('###THIS_UID###', intval($uid), $this->MM_table_where);
676 }
677 // Select, update or delete only those relations that match the configured fields
678 foreach ($this->MM_match_fields as $field => $value) {
679 $additionalWhere .= ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $MM_tableName);
680 }
681 $where = $uidLocal_field . '=' . intval($uid) . $additionalWhere_tablenames . $additionalWhere;
682 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($MM_tableName, $where, array($uidLocal_field => $newUid));
683 }
684 }
685
686 /**
687 * Reads items from a foreign_table, that has a foreign_field (uid of the parent record) and
688 * stores the parts in the internal array itemArray and tableArray.
689 *
690 * @param integer $uid The uid of the parent record (this value is also on the foreign_table in the foreign_field)
691 * @param array $conf TCA configuration for current field
692 * @return void
693 * @todo Define visibility
694 */
695 public function readForeignField($uid, $conf) {
696 $key = 0;
697 $uid = intval($uid);
698 $foreign_table = $conf['foreign_table'];
699 $foreign_table_field = $conf['foreign_table_field'];
700 $useDeleteClause = !$this->undeleteRecord;
701 $foreign_match_fields = is_array($conf['foreign_match_fields']) ? $conf['foreign_match_fields'] : array();
702 // Search for $uid in foreign_field, and if we have symmetric relations, do this also on symmetric_field
703 if ($conf['symmetric_field']) {
704 $whereClause = '(' . $conf['foreign_field'] . '=' . $uid . ' OR ' . $conf['symmetric_field'] . '=' . $uid . ')';
705 } else {
706 $whereClause = $conf['foreign_field'] . '=' . $uid;
707 }
708 // Use the deleteClause (e.g. "deleted=0") on this table
709 if ($useDeleteClause) {
710 $whereClause .= BackendUtility::deleteClause($foreign_table);
711 }
712 // If it's requested to look for the parent uid AND the parent table,
713 // add an additional SQL-WHERE clause
714 if ($foreign_table_field && $this->currentTable) {
715 $whereClause .= ' AND ' . $foreign_table_field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable, $foreign_table);
716 }
717 // Add additional where clause if foreign_match_fields are defined
718 foreach ($foreign_match_fields as $field => $value) {
719 $whereClause .= ' AND ' . $field . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($value, $foreign_table);
720 }
721 // Select children in the same workspace:
722 if (BackendUtility::isTableWorkspaceEnabled($this->currentTable) && BackendUtility::isTableWorkspaceEnabled($foreign_table)) {
723 $currentRecord = BackendUtility::getRecord($this->currentTable, $uid, 't3ver_wsid', '', $useDeleteClause);
724 $whereClause .= BackendUtility::getWorkspaceWhereClause($foreign_table, $currentRecord['t3ver_wsid']);
725 }
726 // Get the correct sorting field
727 // Specific manual sortby for data handled by this field
728 $sortby = '';
729 if ($conf['foreign_sortby']) {
730 if ($conf['symmetric_sortby'] && $conf['symmetric_field']) {
731 // Sorting depends on, from which side of the relation we're looking at it
732 $sortby = '
733 CASE
734 WHEN ' . $conf['foreign_field'] . '=' . $uid . '
735 THEN ' . $conf['foreign_sortby'] . '
736 ELSE ' . $conf['symmetric_sortby'] . '
737 END';
738 } else {
739 // Regular single-side behaviour
740 $sortby = $conf['foreign_sortby'];
741 }
742 } elseif ($conf['foreign_default_sortby']) {
743 // Specific default sortby for data handled by this field
744 $sortby = $conf['foreign_default_sortby'];
745 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) {
746 // Manual sortby for all table records
747 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
748 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby']) {
749 // Default sortby for all table records
750 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby'];
751 }
752 // Strip a possible "ORDER BY" in front of the $sortby value
753 $sortby = $GLOBALS['TYPO3_DB']->stripOrderBy($sortby);
754 // Get the rows from storage
755 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', $foreign_table, $whereClause, '', $sortby);
756 if (count($rows)) {
757 foreach ($rows as $row) {
758 $this->itemArray[$key]['id'] = $row['uid'];
759 $this->itemArray[$key]['table'] = $foreign_table;
760 $this->tableArray[$foreign_table][] = $row['uid'];
761 $key++;
762 }
763 }
764 }
765
766 /**
767 * Write the sorting values to a foreign_table, that has a foreign_field (uid of the parent record)
768 *
769 * @param array $conf TCA configuration for current field
770 * @param integer $parentUid The uid of the parent record
771 * @param integer $updateToUid If this is larger than zero it will be used as foreign UID instead of the given $parentUid (on Copy)
772 * @param boolean $skipSorting Do not update the sorting columns, this could happen for imported values
773 * @return void
774 * @todo Define visibility
775 */
776 public function writeForeignField($conf, $parentUid, $updateToUid = 0, $skipSorting = FALSE) {
777 $c = 0;
778 $foreign_table = $conf['foreign_table'];
779 $foreign_field = $conf['foreign_field'];
780 $symmetric_field = $conf['symmetric_field'];
781 $foreign_table_field = $conf['foreign_table_field'];
782 $foreign_match_fields = is_array($conf['foreign_match_fields']) ? $conf['foreign_match_fields'] : array();
783 // If there are table items and we have a proper $parentUid
784 if (MathUtility::canBeInterpretedAsInteger($parentUid) && count($this->tableArray)) {
785 // If updateToUid is not a positive integer, set it to '0', so it will be ignored
786 if (!(MathUtility::canBeInterpretedAsInteger($updateToUid) && $updateToUid > 0)) {
787 $updateToUid = 0;
788 }
789 $considerWorkspaces = $GLOBALS['BE_USER']->workspace !== 0 && BackendUtility::isTableWorkspaceEnabled($foreign_table);
790 $fields = 'uid,' . $foreign_field;
791 // Consider the symmetric field if defined:
792 if ($symmetric_field) {
793 $fields .= ',' . $symmetric_field;
794 }
795 // Consider workspaces if defined and currently used:
796 if ($considerWorkspaces) {
797 $fields .= ',' . 't3ver_state,t3ver_oid';
798 }
799 // Update all items
800 foreach ($this->itemArray as $val) {
801 $uid = $val['id'];
802 $table = $val['table'];
803 $row = array();
804 // Fetch the current (not overwritten) relation record if we should handle symmetric relations
805 if ($symmetric_field || $considerWorkspaces) {
806 $row = BackendUtility::getRecord($table, $uid, $fields, '', FALSE);
807 }
808 $isOnSymmetricSide = FALSE;
809 if ($symmetric_field) {
810 $isOnSymmetricSide = self::isOnSymmetricSide($parentUid, $conf, $row);
811 }
812 $updateValues = $foreign_match_fields;
813 $workspaceValues = array();
814 // No update to the uid is requested, so this is the normal behaviour
815 // just update the fields and care about sorting
816 if (!$updateToUid) {
817 // Always add the pointer to the parent uid
818 if ($isOnSymmetricSide) {
819 $updateValues[$symmetric_field] = $parentUid;
820 } else {
821 $updateValues[$foreign_field] = $parentUid;
822 }
823 // If it is configured in TCA also to store the parent table in the child record, just do it
824 if ($foreign_table_field && $this->currentTable) {
825 $updateValues[$foreign_table_field] = $this->currentTable;
826 }
827 // Update sorting columns if not to be skipped
828 if (!$skipSorting) {
829 // Get the correct sorting field
830 // Specific manual sortby for data handled by this field
831 $sortby = '';
832 if ($conf['foreign_sortby']) {
833 $sortby = $conf['foreign_sortby'];
834 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) {
835 // manual sortby for all table records
836 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
837 }
838 // Apply sorting on the symmetric side
839 // (it depends on who created the relation, so what uid is in the symmetric_field):
840 if ($isOnSymmetricSide && isset($conf['symmetric_sortby']) && $conf['symmetric_sortby']) {
841 $sortby = $conf['symmetric_sortby'];
842 } else {
843 $sortby = $GLOBALS['TYPO3_DB']->stripOrderBy($sortby);
844 }
845 if ($sortby) {
846 $updateValues[$sortby] = ($workspaceValues[$sortby] = ++$c);
847 }
848 }
849 } else {
850 if ($isOnSymmetricSide) {
851 $updateValues[$symmetric_field] = $updateToUid;
852 } else {
853 $updateValues[$foreign_field] = $updateToUid;
854 }
855 }
856 // Update accordant fields in the database:
857 if (count($updateValues)) {
858 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($uid), $updateValues);
859 $this->updateRefIndex($table, $uid);
860 }
861 // Update accordant fields in the database for workspaces overlays/placeholders:
862 if (count($workspaceValues) && $considerWorkspaces) {
863 if (
864 isset($row['t3ver_oid'])
865 && $row['t3ver_oid']
866 && VersionState::cast($row['t3ver_state'])->equals(VersionState::NEW_PLACEHOLDER_VERSION)
867 ) {
868 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($row['t3ver_oid']), $workspaceValues);
869 }
870 }
871 }
872 }
873 }
874
875 /**
876 * After initialization you can extract an array of the elements from the object. Use this function for that.
877 *
878 * @param boolean $prependTableName If set, then table names will ALWAYS be prepended (unless its a _NO_TABLE value)
879 * @return array A numeric array.
880 * @todo Define visibility
881 */
882 public function getValueArray($prependTableName = FALSE) {
883 // INIT:
884 $valueArray = array();
885 $tableC = count($this->tableArray);
886 // If there are tables in the table array:
887 if ($tableC) {
888 // If there are more than ONE table in the table array, then always prepend table names:
889 $prep = $tableC > 1 || $prependTableName;
890 // Traverse the array of items:
891 foreach ($this->itemArray as $val) {
892 $valueArray[] = ($prep && $val['table'] != '_NO_TABLE' ? $val['table'] . '_' : '') . $val['id'];
893 }
894 }
895 // Return the array
896 return $valueArray;
897 }
898
899 /**
900 * Converts id numbers from negative to positive.
901 *
902 * @param array $valueArray Array of [table]_[id] pairs.
903 * @param string $fTable Foreign table (the one used for positive numbers)
904 * @param string $nfTable Negative foreign table
905 * @return array The array with ID integer values, converted to positive for those where the table name was set but did NOT match the positive foreign table.
906 * @todo Define visibility
907 */
908 public function convertPosNeg($valueArray, $fTable, $nfTable) {
909 if (is_array($valueArray) && $fTable) {
910 foreach ($valueArray as $key => $val) {
911 $val = strrev($val);
912 $parts = explode('_', $val, 2);
913 $theID = strrev($parts[0]);
914 $theTable = strrev($parts[1]);
915 if (MathUtility::canBeInterpretedAsInteger($theID)
916 && (!$theTable || !strcmp($theTable, $fTable) || !strcmp($theTable, $nfTable))
917 ) {
918 $valueArray[$key] = $theTable && strcmp($theTable, $fTable) ? $theID * -1 : $theID;
919 }
920 }
921 }
922 return $valueArray;
923 }
924
925 /**
926 * Reads all records from internal tableArray into the internal ->results array
927 * where keys are table names and for each table, records are stored with uids as their keys.
928 * If $this->fetchAllFields is false you can save a little memory
929 * since only uid,pid and a few other fields are selected.
930 *
931 * @return array
932 * @todo Define visibility
933 */
934 public function getFromDB() {
935 // Traverses the tables listed:
936 foreach ($this->tableArray as $key => $val) {
937 if (is_array($val)) {
938 $itemList = implode(',', $val);
939 if ($itemList) {
940 if ($this->fetchAllFields) {
941 $from = '*';
942 } else {
943 $from = 'uid,pid';
944 if ($GLOBALS['TCA'][$key]['ctrl']['label']) {
945 // Titel
946 $from .= ',' . $GLOBALS['TCA'][$key]['ctrl']['label'];
947 }
948 if ($GLOBALS['TCA'][$key]['ctrl']['label_alt']) {
949 // Alternative Title-Fields
950 $from .= ',' . $GLOBALS['TCA'][$key]['ctrl']['label_alt'];
951 }
952 if ($GLOBALS['TCA'][$key]['ctrl']['thumbnail']) {
953 // Thumbnail
954 $from .= ',' . $GLOBALS['TCA'][$key]['ctrl']['thumbnail'];
955 }
956 }
957 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($from, $key, 'uid IN (' . $itemList . ')' . $this->additionalWhere[$key]);
958 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
959 $this->results[$key][$row['uid']] = $row;
960 }
961 $GLOBALS['TYPO3_DB']->sql_free_result($res);
962 }
963 }
964 }
965 return $this->results;
966 }
967
968 /**
969 * Prepare items from itemArray to be transferred to the TCEforms interface (as a comma list)
970 *
971 * @return string
972 * @todo Define visibility
973 */
974 public function readyForInterface() {
975 if (!is_array($this->itemArray)) {
976 return FALSE;
977 }
978 $output = array();
979 $titleLen = intval($GLOBALS['BE_USER']->uc['titleLen']);
980 foreach ($this->itemArray as $val) {
981 $theRow = $this->results[$val['table']][$val['id']];
982 if ($theRow && is_array($GLOBALS['TCA'][$val['table']])) {
983 $label = GeneralUtility::fixed_lgd_cs(strip_tags(
984 BackendUtility::getRecordTitle($val['table'], $theRow)), $titleLen);
985 $label = $label ? $label : '[...]';
986 $output[] = str_replace(',', '', $val['table'] . '_' . $val['id'] . '|' . rawurlencode($label));
987 }
988 }
989 return implode(',', $output);
990 }
991
992 /**
993 * Counts the items in $this->itemArray and puts this value in an array by default.
994 *
995 * @param boolean $returnAsArray Whether to put the count value in an array
996 * @return mixed The plain count as integer or the same inside an array
997 * @todo Define visibility
998 */
999 public function countItems($returnAsArray = TRUE) {
1000 $count = count($this->itemArray);
1001 if ($returnAsArray) {
1002 $count = array($count);
1003 }
1004 return $count;
1005 }
1006
1007 /**
1008 * Update Reference Index (sys_refindex) for a record
1009 * Should be called any almost any update to a record which could affect references inside the record.
1010 * (copied from TCEmain)
1011 *
1012 * @param string $table Table name
1013 * @param integer $id Record UID
1014 * @return array Information concerning modifications delivered by \TYPO3\CMS\Core\Database\ReferenceIndex::updateRefIndexTable()
1015 * @todo Define visibility
1016 */
1017 public function updateRefIndex($table, $id) {
1018 $statisticsArray = array();
1019 if ($this->updateReferenceIndex) {
1020 /** @var $refIndexObj \TYPO3\CMS\Core\Database\ReferenceIndex */
1021 $refIndexObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\ReferenceIndex');
1022 $statisticsArray = $refIndexObj->updateRefIndexTable($table, $id);
1023 }
1024 return $statisticsArray;
1025 }
1026
1027 /**
1028 * Checks, if we're looking from the "other" side, the symmetric side, to a symmetric relation.
1029 *
1030 * @param string $parentUid The uid of the parent record
1031 * @param array $parentConf The TCA configuration of the parent field embedding the child records
1032 * @param array $childRec The record row of the child record
1033 * @return boolean Returns TRUE if looking from the symmetric ("other") side to the relation.
1034 * @todo Define visibility
1035 */
1036 public function isOnSymmetricSide($parentUid, $parentConf, $childRec) {
1037 return MathUtility::canBeInterpretedAsInteger($childRec['uid'])
1038 && $parentConf['symmetric_field']
1039 && $parentUid == $childRec[$parentConf['symmetric_field']];
1040 }
1041 }