2 /***************************************************************
5 * (c) 1999-2009 Kasper Skaarhoj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Contains class for loading database groups
31 * Revised for TYPO3 3.6 September/2003 by Kasper Skaarhoj
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
36 * [CLASS/FUNCTION INDEX of SCRIPT]
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)
55 * (This index is automatically created/updated by the extension "extdeveval")
65 require_once (PATH_t3lib
.'class.t3lib_refindex.php');
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.
73 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
77 class t3lib_loadDBGroup
{
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.
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...
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)
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)
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
107 * Initialization of the class.
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
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
;
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];
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'];
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];
146 // SECTION: normal MM relations
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']));
153 // The tables are traversed and internal arrays are initialized:
154 $tempTableArray = t3lib_div
::trimExplode(',',$tablelist,1);
155 foreach($tempTableArray as $key => $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';
164 if (is_array($this->tableArray
)) {
165 reset($this->tableArray
);
166 } else {return 'No tables!';}
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...
173 // Now, populate the internal itemArray and tableArray arrays:
174 if ($MMtable) { // If MM, then call this function to do that:
176 $this->readMM($MMtable, $MMuid);
177 } else { // Revert to readList() for new records in order to load possible default values from $itemlist
178 $this->readList($itemlist);
180 } elseif ($MMuid && $conf['foreign_field']) {
181 // If not MM but foreign_field, the read the records by the foreign_field
182 $this->readForeignField($MMuid, $conf);
184 // If not MM, then explode the itemlist by "," and traverse the list:
185 $this->readList($itemlist);
186 // do automatic default_sortby, if any
187 if ($conf['foreign_default_sortby']) {
188 $this->sortList($conf['foreign_default_sortby']);
194 * Explodes the item list and stores the parts in the internal arrays itemArray and tableArray from MM records.
196 * @param string Item list
199 function readList($itemlist) {
200 if ((string)trim($itemlist)!='') {
201 $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...
202 foreach($tempItemArray as $key => $val) {
203 $isSet = 0; // Will be set to "1" if the entry was a real table/id:
205 // Extract table name and id. This is un the formular [tablename]_[id] where table name MIGHT contain "_", hence the reversion of the string!
207 $parts = explode('_',$val,2);
208 $theID = strrev($parts[0]);
210 // Check that the id IS an integer:
211 if (t3lib_div
::testInt($theID)) {
212 // 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
213 $theTable = trim($parts[1]) ?
strrev(trim($parts[1])) : ($this->secondTable
&& $theID<0 ?
$this->secondTable
: $this->firstTable
);
214 // If the ID is not blank and the table name is among the names in the inputted tableList, then proceed:
215 if ((string)$theID!='' && $theID && $theTable && isset($this->tableArray
[$theTable])) {
216 // Get ID as the right value:
217 $theID = $this->secondTable ?
abs(intval($theID)) : intval($theID);
218 // Register ID/table name in internal arrays:
219 $this->itemArray
[$key]['id'] = $theID;
220 $this->itemArray
[$key]['table'] = $theTable;
221 $this->tableArray
[$theTable][] = $theID;
227 // 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:
228 if (!$isSet && $this->registerNonTableValues
) {
229 $this->itemArray
[$key]['id'] = $tempItemArray[$key];
230 $this->itemArray
[$key]['table'] = '_NO_TABLE';
231 $this->nonTableArray
[] = $tempItemArray[$key];
238 * Does a sorting on $this->itemArray depending on a default sortby field.
239 * This is only used for automatic sorting of comma separated lists.
240 * This function is only relevant for data that is stored in comma separated lists!
242 * @param string $sortby: The default_sortby field/command (e.g. 'price DESC')
245 function sortList($sortby) {
246 // sort directly without fetching addional data
247 if ($sortby == 'uid') {
248 usort($this->itemArray
, create_function('$a,$b', 'return $a["id"] < $b["id"] ? -1 : 1;'));
249 // only useful if working on the same table
250 } elseif (count($this->tableArray
) == 1) {
251 reset($this->tableArray
);
252 $table = key($this->tableArray
);
253 $uidList = implode(',', current($this->tableArray
));
256 $this->itemArray
= array();
257 $this->tableArray
= array();
259 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'uid IN ('.$uidList.')', '', $sortby);
260 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
261 $this->itemArray
[] = array('id' => $row['uid'], 'table' => $table);
262 $this->tableArray
[$table][] = $row['uid'];
264 $GLOBALS['TYPO3_DB']->sql_free_result($res);
270 * Reads the record tablename/id into the internal arrays itemArray and tableArray from MM records.
271 * You can call this function after start if you supply no list to start()
273 * @param string MM Tablename
274 * @param integer Local UID
277 function readMM($tableName,$uid) {
279 $additionalWhere = '';
281 if ($this->MM_is_foreign
) { // in case of a reverse relation
282 $uidLocal_field = 'uid_foreign';
283 $uidForeign_field = 'uid_local';
284 $sorting_field = 'sorting_foreign';
286 if ($this->MM_isMultiTableRelationship
) {
287 $additionalWhere .= ' AND ( tablenames="'.$this->currentTable
.'"';
288 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.
289 $additionalWhere .= ' OR tablenames=""';
291 $additionalWhere .= ' ) ';
293 $theTable = $this->MM_oppositeTable
;
295 $uidLocal_field = 'uid_local';
296 $uidForeign_field = 'uid_foreign';
297 $sorting_field = 'sorting';
301 if ($this->MM_table_where
) {
302 $additionalWhere.= "\n".str_replace('###THIS_UID###', intval($uid), $this->MM_table_where
);
304 foreach ($this->MM_match_fields
as $field => $value) {
305 $additionalWhere.= ' AND '.$field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $tableName);
308 // Select all MM relations:
309 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $tableName, $uidLocal_field.'='.intval($uid).$additionalWhere, '', $sorting_field);
310 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
311 if (!$this->MM_is_foreign
) { // default
312 $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...
314 if (($row[$uidForeign_field] ||
$theTable=='pages') && $theTable && isset($this->tableArray
[$theTable])) {
316 $this->itemArray
[$key]['id'] = $row[$uidForeign_field];
317 $this->itemArray
[$key]['table'] = $theTable;
318 $this->tableArray
[$theTable][]= $row[$uidForeign_field];
319 } elseif ($this->registerNonTableValues
) {
320 $this->itemArray
[$key]['id'] = $row[$uidForeign_field];
321 $this->itemArray
[$key]['table'] = '_NO_TABLE';
322 $this->nonTableArray
[] = $row[$uidForeign_field];
326 $GLOBALS['TYPO3_DB']->sql_free_result($res);
330 * Writes the internal itemArray to MM table:
332 * @param string MM table name
333 * @param integer Local UID
334 * @param boolean If set, then table names will always be written.
337 function writeMM($MM_tableName,$uid,$prependTableName=0) {
339 if ($this->MM_is_foreign
) { // in case of a reverse relation
340 $uidLocal_field = 'uid_foreign';
341 $uidForeign_field = 'uid_local';
342 $sorting_field = 'sorting_foreign';
344 $uidLocal_field = 'uid_local';
345 $uidForeign_field = 'uid_foreign';
346 $sorting_field = 'sorting';
349 // If there are tables...
350 $tableC = count($this->tableArray
);
352 $prep = ($tableC>1||
$prependTableName||
$this->MM_isMultiTableRelationship
) ?
1 : 0; // boolean: does the field "tablename" need to be filled?
355 $additionalWhere_tablenames = '';
356 if ($this->MM_is_foreign
&& $prep) {
357 $additionalWhere_tablenames = ' AND tablenames="'.$this->currentTable
.'"';
360 $additionalWhere = '';
361 // add WHERE clause if configured
362 if ($this->MM_table_where
) {
363 $additionalWhere.= "\n".str_replace('###THIS_UID###', intval($uid), $this->MM_table_where
);
365 // Select, update or delete only those relations that match the configured fields
366 foreach ($this->MM_match_fields
as $field => $value) {
367 $additionalWhere.= ' AND '.$field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $MM_tableName);
370 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
371 $uidForeign_field.($prep?
', tablenames':'').($this->MM_hasUidField?
', uid':''),
373 $uidLocal_field.'='.$uid.$additionalWhere_tablenames.$additionalWhere,
379 $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
380 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
381 if (!$this->MM_is_foreign
&& $prep) {
382 $oldMMs[] = array($row['tablenames'], $row[$uidForeign_field]);
384 $oldMMs[] = $row[$uidForeign_field];
386 $oldMMs_inclUid[] = array($row['tablenames'], $row[$uidForeign_field], $row['uid']);
389 // For each item, insert it:
390 foreach($this->itemArray
as $val) {
393 if ($prep ||
$val['table']=='_NO_TABLE') {
394 if ($this->MM_is_foreign
) { // insert current table if needed
395 $tablename = $this->currentTable
;
397 $tablename = $val['table'];
403 if(!$this->MM_is_foreign
&& $prep) {
404 $item = array($val['table'], $val['id']);
409 if (in_array($item, $oldMMs)) {
410 $oldMMs_index = array_search($item, $oldMMs);
412 $whereClause = $uidLocal_field.'='.$uid.' AND '.$uidForeign_field.'='.$val['id'].
413 ($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.
415 $whereClause .= ' AND tablenames="'.$tablename.'"';
417 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($MM_tableName, $whereClause.$additionalWhere, array($sorting_field => $c));
419 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.
420 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.
423 $insertFields = $this->MM_insert_fields
;
424 $insertFields[$uidLocal_field] = $uid;
425 $insertFields[$uidForeign_field] = $val['id'];
426 $insertFields[$sorting_field] = $c;
428 $insertFields['tablenames'] = $tablename;
431 $GLOBALS['TYPO3_DB']->exec_INSERTquery($MM_tableName, $insertFields);
433 if ($this->MM_is_foreign
) {
434 $this->updateRefIndex($val['table'], $val['id']);
439 // Delete all not-used relations:
440 if(is_array($oldMMs) && count($oldMMs) > 0) {
441 $removeClauses = array();
442 $updateRefIndex_records = array();
443 foreach($oldMMs as $oldMM_key => $mmItem) {
444 if ($this->MM_hasUidField
) { // If UID field is present, of course we need only use that for deleting...:
445 $removeClauses[] = 'uid='.intval($oldMMs_inclUid[$oldMM_key][2]);
446 $elDelete = $oldMMs_inclUid[$oldMM_key];
448 if(is_array($mmItem)) {
449 $removeClauses[] = 'tablenames="'.$mmItem[0].'" AND '.$uidForeign_field.'='.$mmItem[1];
451 $removeClauses[] = $uidForeign_field.'='.$mmItem;
454 if ($this->MM_is_foreign
) {
455 if(is_array($mmItem)) {
456 $updateRefIndex_records[] = array($mmItem[0],$mmItem[1]);
458 $updateRefIndex_records[] = array($this->firstTable
,$mmItem);
462 $deleteAddWhere = ' AND ('.implode(' OR ', $removeClauses).')';
463 $GLOBALS['TYPO3_DB']->exec_DELETEquery($MM_tableName, $uidLocal_field.'='.intval($uid).$deleteAddWhere.$additionalWhere_tablenames.$additionalWhere);
466 foreach($updateRefIndex_records as $pair) {
467 $this->updateRefIndex($pair[0],$pair[1]);
471 // 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 ...
472 $this->updateRefIndex($this->currentTable
,$uid);
477 * Remaps MM table elements from one local uid to another
478 * Does NOT update the reference index for you, must be called subsequently to do that!
480 * @param string MM table name
481 * @param integer Local, current UID
482 * @param integer Local, new UID
483 * @param boolean If set, then table names will always be written.
486 function remapMM($MM_tableName,$uid,$newUid,$prependTableName=0) {
488 if ($this->MM_is_foreign
) { // in case of a reverse relation
489 $uidLocal_field = 'uid_foreign';
491 $uidLocal_field = 'uid_local';
494 // If there are tables...
495 $tableC = count($this->tableArray
);
497 $prep = ($tableC>1||
$prependTableName||
$this->MM_isMultiTableRelationship
) ?
1 : 0; // boolean: does the field "tablename" need to be filled?
500 $additionalWhere_tablenames = '';
501 if ($this->MM_is_foreign
&& $prep) {
502 $additionalWhere_tablenames = ' AND tablenames="'.$this->currentTable
.'"';
505 $additionalWhere = '';
506 // add WHERE clause if configured
507 if ($this->MM_table_where
) {
508 $additionalWhere.= "\n".str_replace('###THIS_UID###', intval($uid), $this->MM_table_where
);
510 // Select, update or delete only those relations that match the configured fields
511 foreach ($this->MM_match_fields
as $field => $value) {
512 $additionalWhere.= ' AND '.$field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $MM_tableName);
515 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($MM_tableName, $uidLocal_field.'='.intval($uid).$additionalWhere_tablenames.$additionalWhere, array($uidLocal_field => $newUid));
520 * Reads items from a foreign_table, that has a foreign_field (uid of the parent record) and
521 * stores the parts in the internal array itemArray and tableArray.
523 * @param integer $uid: The uid of the parent record (this value is also on the foreign_table in the foreign_field)
524 * @param array $conf: TCA configuration for current field
527 function readForeignField($uid, $conf) {
531 $foreign_table = $conf['foreign_table'];
532 $foreign_table_field = $conf['foreign_table_field'];
533 $useDeleteClause = $this->undeleteRecord ? false
: true
;
535 // search for $uid in foreign_field, and if we have symmetric relations, do this also on symmetric_field
536 if ($conf['symmetric_field']) {
537 $whereClause = '('.$conf['foreign_field'].'='.$uid.' OR '.$conf['symmetric_field'].'='.$uid.')';
539 $whereClause = $conf['foreign_field'].'='.$uid;
541 // use the deleteClause (e.g. "deleted=0") on this table
542 if ($useDeleteClause) {
543 $whereClause .= t3lib_BEfunc
::deleteClause($foreign_table);
545 // if it's requested to look for the parent uid AND the parent table,
546 // add an additional SQL-WHERE clause
547 if ($foreign_table_field && $this->currentTable
) {
548 $whereClause .= ' AND '.$foreign_table_field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->currentTable
, $foreign_table);
551 // get the correct sorting field
552 if ($conf['foreign_sortby']) { // specific manual sortby for data handled by this field
553 if ($conf['symmetric_sortby'] && $conf['symmetric_field']) {
554 // sorting depends on, from which side of the relation we're looking at it
557 WHEN '.$conf['foreign_field'].'='.$uid.'
558 THEN '.$conf['foreign_sortby'].'
559 ELSE '.$conf['symmetric_sortby'].'
562 // regular single-side behaviour
563 $sortby = $conf['foreign_sortby'];
565 } elseif ($conf['foreign_default_sortby']) { // specific default sortby for data handled by this field
566 $sortby = $conf['foreign_default_sortby'];
567 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) { // manual sortby for all table records
568 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
569 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby']) { // default sortby for all table records
570 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['default_sortby'];
573 // strip a possible "ORDER BY" in front of the $sortby value
574 $sortby = $GLOBALS['TYPO3_DB']->stripOrderBy($sortby);
575 // get the rows from storage
576 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', $foreign_table, $whereClause, '', $sortby);
579 foreach ($rows as $row) {
580 $this->itemArray
[$key]['id'] = $row['uid'];
581 $this->itemArray
[$key]['table'] = $foreign_table;
582 $this->tableArray
[$foreign_table][]= $row['uid'];
589 * Write the sorting values to a foreign_table, that has a foreign_field (uid of the parent record)
591 * @param array $conf: TCA configuration for current field
592 * @param integer $parentUid: The uid of the parent record
593 * @param boolean $updateToUid: Whether to update the foreign field with the $parentUid (on Copy)
594 * @param boolean $skipSorting: Do not update the sorting columns, this could happen for imported values
597 function writeForeignField($conf, $parentUid, $updateToUid=0, $skipSorting=false
) {
599 $foreign_table = $conf['foreign_table'];
600 $foreign_field = $conf['foreign_field'];
601 $symmetric_field = $conf['symmetric_field'];
602 $foreign_table_field = $conf['foreign_table_field'];
604 // if there are table items and we have a proper $parentUid
605 if (t3lib_div
::testInt($parentUid) && count($this->tableArray
)) {
606 // if updateToUid is not a positive integer, set it to '0', so it will be ignored
607 if (!(t3lib_div
::testInt($updateToUid) && $updateToUid > 0)) {
610 $fields = 'uid,'.$foreign_field.($symmetric_field ?
','.$symmetric_field : '');
613 foreach ($this->itemArray
as $val) {
615 $table = $val['table'];
617 // fetch the current (not overwritten) relation record if we should handle symmetric relations
618 if ($conf['symmetric_field']) {
619 $row = t3lib_BEfunc
::getRecord($table,$uid,$fields,'',false
);
620 $isOnSymmetricSide = t3lib_loadDBGroup
::isOnSymmetricSide($parentUid, $conf, $row);
623 $updateValues = array();
625 // no update to the uid is requested, so this is the normal behaviour
626 // just update the fields and care about sorting
628 // Always add the pointer to the parent uid
629 if ($isOnSymmetricSide) {
630 $updateValues[$symmetric_field] = $parentUid;
632 $updateValues[$foreign_field] = $parentUid;
635 // if it is configured in TCA also to store the parent table in the child record, just do it
636 if ($foreign_table_field && $this->currentTable
) {
637 $updateValues[$foreign_table_field] = $this->currentTable
;
640 // update sorting columns if not to be skipped
642 // get the correct sorting field
643 if ($conf['foreign_sortby']) { // specific manual sortby for data handled by this field
644 $sortby = $conf['foreign_sortby'];
645 } elseif ($GLOBALS['TCA'][$foreign_table]['ctrl']['sortby']) { // manual sortby for all table records
646 $sortby = $GLOBALS['TCA'][$foreign_table]['ctrl']['sortby'];
648 // strip a possible "ORDER BY" in front of the $sortby value
649 $sortby = $GLOBALS['TYPO3_DB']->stripOrderBy($sortby);
650 $symSortby = $conf['symmetric_sortby'];
652 // set the sorting on the right side, it depends on who created the relation, so what uid is in the symmetric_field
653 if ($isOnSymmetricSide && $symSortby) {
654 $updateValues[$symSortby] = ++
$c;
656 $updateValues[$sortby] = ++
$c;
660 // update to a foreign_field/symmetric_field pointer is requested, normally used on record copies
661 // only update the fields, if the old uid is found somewhere - for select fields, TCEmain is doing this already!
663 if ($isOnSymmetricSide) {
664 $updateValues[$symmetric_field] = $updateToUid;
666 $updateValues[$foreign_field] = $updateToUid;
670 if (count($updateValues)) {
671 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($uid), $updateValues);
672 $this->updateRefIndex($table, $uid);
679 * After initialization you can extract an array of the elements from the object. Use this function for that.
681 * @param boolean If set, then table names will ALWAYS be prepended (unless its a _NO_TABLE value)
682 * @return array A numeric array.
684 function getValueArray($prependTableName='') {
687 $tableC = count($this->tableArray
);
689 // If there are tables in the table array:
691 // If there are more than ONE table in the table array, then always prepend table names:
692 $prep = ($tableC>1||
$prependTableName) ?
1 : 0;
694 // Traverse the array of items:
695 foreach($this->itemArray
as $val) {
696 $valueArray[]=(($prep && $val['table']!='_NO_TABLE') ?
$val['table'].'_' : '').
705 * Converts id numbers from negative to positive.
707 * @param array Array of [table]_[id] pairs.
708 * @param string Foreign table (the one used for positive numbers)
709 * @param string NEGative foreign table
710 * @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.
712 function convertPosNeg($valueArray,$fTable,$nfTable) {
713 if (is_array($valueArray) && $fTable) {
714 foreach($valueArray as $key => $val) {
716 $parts = explode('_',$val,2);
717 $theID = strrev($parts[0]);
718 $theTable = strrev($parts[1]);
720 if ( t3lib_div
::testInt($theID) && (!$theTable ||
!strcmp($theTable,$fTable) ||
!strcmp($theTable,$nfTable)) ) {
721 $valueArray[$key]= $theTable && strcmp($theTable,$fTable) ?
$theID*-1 : $theID;
729 * 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.
730 * If $this->fromTC is set you can save a little memory since only uid,pid and a few other fields are selected.
734 function getFromDB() {
735 // Traverses the tables listed:
736 foreach($this->tableArray
as $key => $val) {
737 if (is_array($val)) {
738 $itemList = implode(',',$val);
743 if ($GLOBALS['TCA'][$key]['ctrl']['label']) {
744 $from.= ','.$GLOBALS['TCA'][$key]['ctrl']['label']; // Titel
746 if ($GLOBALS['TCA'][$key]['ctrl']['label_alt']) {
747 $from.= ','.$GLOBALS['TCA'][$key]['ctrl']['label_alt']; // Alternative Title-Fields
749 if ($GLOBALS['TCA'][$key]['ctrl']['thumbnail']) {
750 $from.= ','.$GLOBALS['TCA'][$key]['ctrl']['thumbnail']; // Thumbnail
753 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($from, $key, 'uid IN ('.$itemList.')'.$this->additionalWhere
[$key]);
754 while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
755 $this->results
[$key][$row['uid']]=$row;
760 return $this->results
;
764 * Prepare items from itemArray to be transferred to the TCEforms interface (as a comma list)
767 * @see t3lib_transferdata::renderRecord()
769 function readyForInterface() {
772 if (!is_array($this->itemArray
)) {return false
;}
775 $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1); // For use when getting the paths....
776 $titleLen=intval($GLOBALS['BE_USER']->uc
['titleLen']);
778 foreach($this->itemArray
as $key => $val) {
779 $theRow = $this->results
[$val['table']][$val['id']];
780 if ($theRow && is_array($TCA[$val['table']])) {
781 $label = t3lib_div
::fixed_lgd_cs(strip_tags(t3lib_BEfunc
::getRecordTitle($val['table'], $theRow)),$titleLen);
782 $label = ($label)?
$label:'[...]';
783 $output[]=str_replace(',','',$val['table'].'_'.$val['id'].'|'.rawurlencode($label));
786 return implode(',',$output);
790 * Counts the items in $this->itemArray and puts this value in an array by default.
792 * @param boolean Whether to put the count value in an array
793 * @return mixed The plain count as integer or the same inside an array
795 function countItems($returnAsArray = true
) {
796 $count = count($this->itemArray
);
797 if ($returnAsArray) $count = array($count);
802 * Update Reference Index (sys_refindex) for a record
803 * Should be called any almost any update to a record which could affect references inside the record.
804 * (copied from TCEmain)
806 * @param string Table name
807 * @param integer Record UID
810 function updateRefIndex($table,$id) {
811 $refIndexObj = t3lib_div
::makeInstance('t3lib_refindex');
812 $result = $refIndexObj->updateRefIndexTable($table,$id);
816 * Checks, if we're looking from the "other" side, the symmetric side, to a symmetric relation.
818 * @param string $parentUid: The uid of the parent record
819 * @param array $parentConf: The TCA configuration of the parent field embedding the child records
820 * @param array $childRec: The record row of the child record
821 * @return boolean Returns true if looking from the symmetric ("other") side to the relation.
823 function isOnSymmetricSide($parentUid, $parentConf, $childRec) {
824 return t3lib_div
::testInt($childRec['uid']) && $parentConf['symmetric_field'] && $parentUid == $childRec[$parentConf['symmetric_field']]
831 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_loaddbgroup.php']) {
832 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_loaddbgroup.php']);