Cleanup: Updated copyright notices
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_loaddbgroup.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2009 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 if ($MMuid) {
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);
179 }
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);
183 } else {
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']);
189 }
190 }
191 }
192
193 /**
194 * Explodes the item list and stores the parts in the internal arrays itemArray and tableArray from MM records.
195 *
196 * @param string Item list
197 * @return void
198 */
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:
204
205 // Extract table name and id. This is un the formular [tablename]_[id] where table name MIGHT contain "_", hence the reversion of the string!
206 $val = strrev($val);
207 $parts = explode('_',$val,2);
208 $theID = strrev($parts[0]);
209
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;
222 // Set update-flag:
223 $isSet=1;
224 }
225 }
226
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];
232 }
233 }
234 }
235 }
236
237 /**
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!
241 *
242 * @param string $sortby: The default_sortby field/command (e.g. 'price DESC')
243 * @return void
244 */
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));
254
255 if ($uidList) {
256 $this->itemArray = array();
257 $this->tableArray = array();
258
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'];
263 }
264 $GLOBALS['TYPO3_DB']->sql_free_result($res);
265 }
266 }
267 }
268
269 /**
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()
272 *
273 * @param string MM Tablename
274 * @param integer Local UID
275 * @return void
276 */
277 function readMM($tableName,$uid) {
278 $key=0;
279 $additionalWhere = '';
280
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';
285
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=""';
290 }
291 $additionalWhere .= ' ) ';
292 }
293 $theTable = $this->MM_oppositeTable;
294 } else { // default
295 $uidLocal_field = 'uid_local';
296 $uidForeign_field = 'uid_foreign';
297 $sorting_field = 'sorting';
298 }
299
300
301 if ($this->MM_table_where) {
302 $additionalWhere.= "\n".str_replace('###THIS_UID###', intval($uid), $this->MM_table_where);
303 }
304 foreach ($this->MM_match_fields as $field => $value) {
305 $additionalWhere.= ' AND '.$field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $tableName);
306 }
307
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...
313 }
314 if (($row[$uidForeign_field] || $theTable=='pages') && $theTable && isset($this->tableArray[$theTable])) {
315
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];
323 }
324 $key++;
325 }
326 $GLOBALS['TYPO3_DB']->sql_free_result($res);
327 }
328
329 /**
330 * Writes the internal itemArray to MM table:
331 *
332 * @param string MM table name
333 * @param integer Local UID
334 * @param boolean If set, then table names will always be written.
335 * @return void
336 */
337 function writeMM($MM_tableName,$uid,$prependTableName=0) {
338
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';
343 } else { // default
344 $uidLocal_field = 'uid_local';
345 $uidForeign_field = 'uid_foreign';
346 $sorting_field = 'sorting';
347 }
348
349 // If there are tables...
350 $tableC = count($this->tableArray);
351 if ($tableC) {
352 $prep = ($tableC>1||$prependTableName||$this->MM_isMultiTableRelationship) ? 1 : 0; // boolean: does the field "tablename" need to be filled?
353 $c=0;
354
355 $additionalWhere_tablenames = '';
356 if ($this->MM_is_foreign && $prep) {
357 $additionalWhere_tablenames = ' AND tablenames="'.$this->currentTable.'"';
358 }
359
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);
364 }
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);
368 }
369
370 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
371 $uidForeign_field.($prep?', tablenames':'').($this->MM_hasUidField?', uid':''),
372 $MM_tableName,
373 $uidLocal_field.'='.$uid.$additionalWhere_tablenames.$additionalWhere,
374 '',
375 $sorting_field
376 );
377
378 $oldMMs = array();
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]);
383 } else {
384 $oldMMs[] = $row[$uidForeign_field];
385 }
386 $oldMMs_inclUid[] = array($row['tablenames'], $row[$uidForeign_field], $row['uid']);
387 }
388
389 // For each item, insert it:
390 foreach($this->itemArray as $val) {
391 $c++;
392
393 if ($prep || $val['table']=='_NO_TABLE') {
394 if ($this->MM_is_foreign) { // insert current table if needed
395 $tablename = $this->currentTable;
396 } else {
397 $tablename = $val['table'];
398 }
399 } else {
400 $tablename = '';
401 }
402
403 if(!$this->MM_is_foreign && $prep) {
404 $item = array($val['table'], $val['id']);
405 } else {
406 $item = $val['id'];
407 }
408
409 if (in_array($item, $oldMMs)) {
410 $oldMMs_index = array_search($item, $oldMMs);
411
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.
414 if ($tablename) {
415 $whereClause .= ' AND tablenames="'.$tablename.'"';
416 }
417 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($MM_tableName, $whereClause.$additionalWhere, array($sorting_field => $c));
418
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.
421 } else {
422
423 $insertFields = $this->MM_insert_fields;
424 $insertFields[$uidLocal_field] = $uid;
425 $insertFields[$uidForeign_field] = $val['id'];
426 $insertFields[$sorting_field] = $c;
427 if($tablename) {
428 $insertFields['tablenames'] = $tablename;
429 }
430
431 $GLOBALS['TYPO3_DB']->exec_INSERTquery($MM_tableName, $insertFields);
432
433 if ($this->MM_is_foreign) {
434 $this->updateRefIndex($val['table'], $val['id']);
435 }
436 }
437 }
438
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];
447 } else {
448 if(is_array($mmItem)) {
449 $removeClauses[] = 'tablenames="'.$mmItem[0].'" AND '.$uidForeign_field.'='.$mmItem[1];
450 } else {
451 $removeClauses[] = $uidForeign_field.'='.$mmItem;
452 }
453 }
454 if ($this->MM_is_foreign) {
455 if(is_array($mmItem)) {
456 $updateRefIndex_records[] = array($mmItem[0],$mmItem[1]);
457 } else {
458 $updateRefIndex_records[] = array($this->firstTable,$mmItem);
459 }
460 }
461 }
462 $deleteAddWhere = ' AND ('.implode(' OR ', $removeClauses).')';
463 $GLOBALS['TYPO3_DB']->exec_DELETEquery($MM_tableName, $uidLocal_field.'='.intval($uid).$deleteAddWhere.$additionalWhere_tablenames.$additionalWhere);
464
465 // Update ref index:
466 foreach($updateRefIndex_records as $pair) {
467 $this->updateRefIndex($pair[0],$pair[1]);
468 }
469 }
470
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);
473 }
474 }
475
476 /**
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!
479 *
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.
484 * @return void
485 */
486 function remapMM($MM_tableName,$uid,$newUid,$prependTableName=0) {
487
488 if ($this->MM_is_foreign) { // in case of a reverse relation
489 $uidLocal_field = 'uid_foreign';
490 } else { // default
491 $uidLocal_field = 'uid_local';
492 }
493
494 // If there are tables...
495 $tableC = count($this->tableArray);
496 if ($tableC) {
497 $prep = ($tableC>1||$prependTableName||$this->MM_isMultiTableRelationship) ? 1 : 0; // boolean: does the field "tablename" need to be filled?
498 $c=0;
499
500 $additionalWhere_tablenames = '';
501 if ($this->MM_is_foreign && $prep) {
502 $additionalWhere_tablenames = ' AND tablenames="'.$this->currentTable.'"';
503 }
504
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);
509 }
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);
513 }
514
515 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($MM_tableName, $uidLocal_field.'='.intval($uid).$additionalWhere_tablenames.$additionalWhere, array($uidLocal_field => $newUid));
516 }
517 }
518
519 /**
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.
522 *
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
525 * @return void
526 */
527 function readForeignField($uid, $conf) {
528 $key = 0;
529 $uid = intval($uid);
530 $whereClause = '';
531 $foreign_table = $conf['foreign_table'];
532 $foreign_table_field = $conf['foreign_table_field'];
533 $useDeleteClause = $this->undeleteRecord ? false : true;
534
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.')';
538 } else {
539 $whereClause = $conf['foreign_field'].'='.$uid;
540 }
541 // use the deleteClause (e.g. "deleted=0") on this table
542 if ($useDeleteClause) {
543 $whereClause .= t3lib_BEfunc::deleteClause($foreign_table);
544 }
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);
549 }
550
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
555 $sortby = '
556 CASE
557 WHEN '.$conf['foreign_field'].'='.$uid.'
558 THEN '.$conf['foreign_sortby'].'
559 ELSE '.$conf['symmetric_sortby'].'
560 END';
561 } else {
562 // regular single-side behaviour
563 $sortby = $conf['foreign_sortby'];
564 }
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'];
571 }
572
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);
577
578 if (count($rows)) {
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'];
583 $key++;
584 }
585 }
586 }
587
588 /**
589 * Write the sorting values to a foreign_table, that has a foreign_field (uid of the parent record)
590 *
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
595 * @return void
596 */
597 function writeForeignField($conf, $parentUid, $updateToUid=0, $skipSorting=false) {
598 $c = 0;
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'];
603
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)) {
608 $updateToUid = 0;
609 }
610 $fields = 'uid,'.$foreign_field.($symmetric_field ? ','.$symmetric_field : '');
611
612 // update all items
613 foreach ($this->itemArray as $val) {
614 $uid = $val['id'];
615 $table = $val['table'];
616
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);
621 }
622
623 $updateValues = array();
624
625 // no update to the uid is requested, so this is the normal behaviour
626 // just update the fields and care about sorting
627 if (!$updateToUid) {
628 // Always add the pointer to the parent uid
629 if ($isOnSymmetricSide) {
630 $updateValues[$symmetric_field] = $parentUid;
631 } else {
632 $updateValues[$foreign_field] = $parentUid;
633 }
634
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;
638 }
639
640 // update sorting columns if not to be skipped
641 if (!$skipSorting) {
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'];
647 }
648 // strip a possible "ORDER BY" in front of the $sortby value
649 $sortby = $GLOBALS['TYPO3_DB']->stripOrderBy($sortby);
650 $symSortby = $conf['symmetric_sortby'];
651
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;
655 } elseif ($sortby) {
656 $updateValues[$sortby] = ++$c;
657 }
658 }
659
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!
662 } else {
663 if ($isOnSymmetricSide) {
664 $updateValues[$symmetric_field] = $updateToUid;
665 } else {
666 $updateValues[$foreign_field] = $updateToUid;
667 }
668 }
669
670 if (count($updateValues)) {
671 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($uid), $updateValues);
672 $this->updateRefIndex($table, $uid);
673 }
674 }
675 }
676 }
677
678 /**
679 * After initialization you can extract an array of the elements from the object. Use this function for that.
680 *
681 * @param boolean If set, then table names will ALWAYS be prepended (unless its a _NO_TABLE value)
682 * @return array A numeric array.
683 */
684 function getValueArray($prependTableName='') {
685 // INIT:
686 $valueArray=Array();
687 $tableC = count($this->tableArray);
688
689 // If there are tables in the table array:
690 if ($tableC) {
691 // If there are more than ONE table in the table array, then always prepend table names:
692 $prep = ($tableC>1||$prependTableName) ? 1 : 0;
693
694 // Traverse the array of items:
695 foreach($this->itemArray as $val) {
696 $valueArray[]=(($prep && $val['table']!='_NO_TABLE') ? $val['table'].'_' : '').
697 $val['id'];
698 }
699 }
700 // Return the array
701 return $valueArray;
702 }
703
704 /**
705 * Converts id numbers from negative to positive.
706 *
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.
711 */
712 function convertPosNeg($valueArray,$fTable,$nfTable) {
713 if (is_array($valueArray) && $fTable) {
714 foreach($valueArray as $key => $val) {
715 $val = strrev($val);
716 $parts = explode('_',$val,2);
717 $theID = strrev($parts[0]);
718 $theTable = strrev($parts[1]);
719
720 if ( t3lib_div::testInt($theID) && (!$theTable || !strcmp($theTable,$fTable) || !strcmp($theTable,$nfTable)) ) {
721 $valueArray[$key]= $theTable && strcmp($theTable,$fTable) ? $theID*-1 : $theID;
722 }
723 }
724 }
725 return $valueArray;
726 }
727
728 /**
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.
731 *
732 * @return void
733 */
734 function getFromDB() {
735 // Traverses the tables listed:
736 foreach($this->tableArray as $key => $val) {
737 if (is_array($val)) {
738 $itemList = implode(',',$val);
739 if ($itemList) {
740 $from = '*';
741 if ($this->fromTC) {
742 $from = 'uid,pid';
743 if ($GLOBALS['TCA'][$key]['ctrl']['label']) {
744 $from.= ','.$GLOBALS['TCA'][$key]['ctrl']['label']; // Titel
745 }
746 if ($GLOBALS['TCA'][$key]['ctrl']['label_alt']) {
747 $from.= ','.$GLOBALS['TCA'][$key]['ctrl']['label_alt']; // Alternative Title-Fields
748 }
749 if ($GLOBALS['TCA'][$key]['ctrl']['thumbnail']) {
750 $from.= ','.$GLOBALS['TCA'][$key]['ctrl']['thumbnail']; // Thumbnail
751 }
752 }
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;
756 }
757 }
758 }
759 }
760 return $this->results;
761 }
762
763 /**
764 * Prepare items from itemArray to be transferred to the TCEforms interface (as a comma list)
765 *
766 * @return string
767 * @see t3lib_transferdata::renderRecord()
768 */
769 function readyForInterface() {
770 global $TCA;
771
772 if (!is_array($this->itemArray)) {return false;}
773
774 $output=array();
775 $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1); // For use when getting the paths....
776 $titleLen=intval($GLOBALS['BE_USER']->uc['titleLen']);
777
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));
784 }
785 }
786 return implode(',',$output);
787 }
788
789 /**
790 * Counts the items in $this->itemArray and puts this value in an array by default.
791 *
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
794 */
795 function countItems($returnAsArray = true) {
796 $count = count($this->itemArray);
797 if ($returnAsArray) $count = array($count);
798 return $count;
799 }
800
801 /**
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)
805 *
806 * @param string Table name
807 * @param integer Record UID
808 * @return void
809 */
810 function updateRefIndex($table,$id) {
811 $refIndexObj = t3lib_div::makeInstance('t3lib_refindex');
812 $result = $refIndexObj->updateRefIndexTable($table,$id);
813 }
814
815 /**
816 * Checks, if we're looking from the "other" side, the symmetric side, to a symmetric relation.
817 *
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.
822 */
823 function isOnSymmetricSide($parentUid, $parentConf, $childRec) {
824 return t3lib_div::testInt($childRec['uid']) && $parentConf['symmetric_field'] && $parentUid == $childRec[$parentConf['symmetric_field']]
825 ? true
826 : false;
827 }
828 }
829
830
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']);
833 }
834
835 ?>