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