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