added @var phpDoc comments to various variables
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_treeview.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2005 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 base class for creating a browsable array/page/folder tree in HTML
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 November/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
34 * @coauthor René Fritz <r.fritz@colorcube.de>
35 */
36 /**
37 * [CLASS/FUNCTION INDEX of SCRIPT]
38 *
39 *
40 *
41 * 115: class t3lib_treeView
42 * 270: function init($clause='', $orderByFields='')
43 * 301: function setTreeName($treeName='')
44 * 315: function addField($field,$noCheck=0)
45 * 329: function reset()
46 *
47 * SECTION: output
48 * 349: function getBrowsableTree()
49 * 412: function printTree($treeArr='')
50 *
51 * SECTION: rendering parts
52 * 467: function PMicon($row,$a,$c,$nextCount,$exp)
53 * 489: function PM_ATagWrap($icon,$cmd,$bMark='')
54 * 511: function wrapTitle($title,$row,$bank=0)
55 * 524: function wrapIcon($icon,$row)
56 * 535: function addTagAttributes($icon,$attr)
57 * 547: function wrapStop($str,$row)
58 *
59 * SECTION: tree handling
60 * 575: function expandNext($id)
61 * 585: function initializePositionSaving()
62 * 612: function savePosition()
63 *
64 * SECTION: Functions that might be overwritten by extended classes
65 * 641: function getRootIcon($rec)
66 * 654: function getIcon($row)
67 * 673: function getTitleStr($row,$titleLen=30)
68 * 685: function getTitleAttrib($row)
69 * 695: function getId($row)
70 * 705: function getJumpToParam($row)
71 *
72 * SECTION: tree data buidling
73 * 739: function getTree($uid, $depth=999, $depthData='',$blankLineCode='',$subCSSclass='')
74 *
75 * SECTION: Data handling
76 * 839: function getCount($uid)
77 * 865: function getRootRecord($uid)
78 * 878: function getRecord($uid)
79 * 898: function getDataInit($parentId,$subCSSclass='')
80 * 929: function getDataCount(&$res)
81 * 947: function getDataNext(&$res,$subCSSclass='')
82 * 986: function getDataFree(&$res)
83 * 1006: function setDataFromArray(&$dataArr,$traverse=FALSE,$pid=0)
84 * 1035: function setDataFromTreeArray(&$treeArr, &$treeLookupArr)
85 *
86 * TOTAL FUNCTIONS: 31
87 * (This index is automatically created/updated by the extension "extdeveval")
88 *
89 */
90
91
92
93
94
95
96
97
98
99
100
101 require_once (PATH_t3lib.'class.t3lib_iconworks.php');
102 require_once (PATH_t3lib.'class.t3lib_befunc.php');
103 require_once (PATH_t3lib.'class.t3lib_div.php');
104
105
106 /**
107 * Base class for creating a browsable array/page/folder tree in HTML
108 *
109 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
110 * @coauthor René Fritz <r.fritz@colorcube.de>
111 * @package TYPO3
112 * @subpackage t3lib
113 * @see t3lib_browsetree, t3lib_pagetree, t3lib_foldertree
114 */
115 class t3lib_treeView {
116
117 // EXTERNAL, static:
118 var $expandFirst=0; // If set, the first element in the tree is always expanded.
119 var $expandAll=0; // If set, then ALL items will be expanded, regardless of stored settings.
120 var $thisScript=''; // Holds the current script to reload to.
121 var $titleAttrib = 'title'; // Which HTML attribute to use: alt/title. See init().
122 var $ext_IconMode = false; // If true, no context menu is rendered on icons. If set to "titlelink" the icon is linked as the title is.
123 var $addSelfId = 0; // If set, the id of the mounts will be added to the internal ids array
124 var $title='no title'; // Used if the tree is made of records (not folders for ex.)
125 var $showDefaultTitleAttribute = FALSE; // If true, a default title attribute showing the UID of the record is shown. This cannot be enabled by default because it will destroy many applications where another title attribute is in fact applied later.
126 var $highlightPagesWithVersions = TRUE; // If true, pages containing child records which has versions will be highlighted in yellow. This might be too expensive in terms of processing power.
127
128 /**
129 * Needs to be initialized with $GLOBALS['BE_USER']
130 * Done by default in init()
131 *
132 * @var t3lib_beUserAuth
133 */
134 var $BE_USER='';
135
136 /**
137 * Needs to be initialized with e.g. $GLOBALS['WEBMOUNTS']
138 * Default setting in init() is 0 => 0
139 * The keys are mount-ids (can be anything basically) and the values are the ID of the root element (COULD be zero or anything else. For pages that would be the uid of the page, zero for the pagetree root.)
140 */
141 var $MOUNTS='';
142
143
144
145 /**
146 * Database table to get the tree data from.
147 * Leave blank if data comes from an array.
148 */
149 var $table='';
150
151 /**
152 * Defines the field of $table which is the parent id field (like pid for table pages).
153 */
154 var $parentField='pid';
155
156 /**
157 * WHERE clause used for selecting records for the tree. Is set by function init.
158 * Only makes sense when $this->table is set.
159 * @see init()
160 */
161 var $clause='';
162
163 /**
164 * Field for ORDER BY. Is set by function init.
165 * Only makes sense when $this->table is set.
166 * @see init()
167 */
168 var $orderByFields='';
169
170 /**
171 * Default set of fields selected from the tree table.
172 * Make SURE that these fields names listed herein are actually possible to select from $this->table (if that variable is set to a TCA table name)
173 * @see addField()
174 */
175 var $fieldArray = Array('uid','title');
176
177 /**
178 * List of other fields which are ALLOWED to set (here, based on the "pages" table!)
179 * @see addField()
180 */
181 var $defaultList = 'uid,pid,tstamp,sorting,deleted,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,crdate,cruser_id';
182
183
184 /**
185 * Unique name for the tree.
186 * Used as key for storing the tree into the BE users settings.
187 * Used as key to pass parameters in links.
188 * MUST NOT contain underscore chars.
189 * etc.
190 */
191 var $treeName = '';
192
193 /**
194 * A prefix for table cell id's which will be wrapped around an item.
195 * Can be used for highlighting by JavaScript.
196 * Needs to be unique if multiple trees are on one HTML page.
197 * @see printTree()
198 */
199 var $domIdPrefix = 'row';
200
201 /**
202 * Back path for icons
203 */
204 var $backPath;
205
206 /**
207 * Icon file path.
208 */
209 var $iconPath = '';
210
211
212 /**
213 * Icon file name for item icons.
214 */
215 var $iconName = 'default.gif';
216
217 /**
218 * If true, HTML code is also accumulated in ->tree array during rendering of the tree.
219 * If 2, then also the icon prefix code (depthData) is stored
220 */
221 var $makeHTML=1;
222
223 /**
224 * If true, records as selected will be stored internally in the ->recs array
225 */
226 var $setRecs = 0;
227
228 /**
229 * Sets the associative array key which identifies a new sublevel if arrays are used for trees.
230 * This value has formerly been "subLevel" and "--sublevel--"
231 */
232 var $subLevelID = '_SUB_LEVEL';
233
234
235
236
237 // *********
238 // Internal
239 // *********
240 // For record trees:
241 var $ids = Array(); // one-dim array of the uid's selected.
242 var $ids_hierarchy = array(); // The hierarchy of element uids
243 var $orig_ids_hierarchy = array(); // The hierarchy of versioned element uids
244 var $buffer_idH = array(); // Temporary, internal array
245
246 // For FOLDER trees:
247 var $specUIDmap=array(); // Special UIDs for folders (integer-hashes of paths)
248
249 // For arrays:
250 var $data = false; // Holds the input data array
251 var $dataLookup = false; // Holds an index with references to the data array.
252
253 // For both types
254 var $tree = Array(); // Tree is accumulated in this variable
255 var $stored = array(); // Holds (session stored) information about which items in the tree are unfolded and which are not.
256 var $bank=0; // Points to the current mountpoint key
257 var $recs = array(); // Accumulates the displayed records.
258
259
260
261
262
263
264
265 /**
266 * Initialize the tree class. Needs to be overwritten
267 * Will set ->fieldsArray, ->backPath and ->clause
268 *
269 * @param string record WHERE clause
270 * @param string record ORDER BY field
271 * @return void
272 */
273 function init($clause='', $orderByFields='') {
274 $this->BE_USER = $GLOBALS['BE_USER']; // Setting BE_USER by default
275 $this->titleAttrib = 'title'; // Setting title attribute to use.
276 $this->backPath = $GLOBALS['BACK_PATH']; // Setting backpath.
277
278 if ($clause) $this->clause = $clause; // Setting clause
279 if ($orderByFields) $this->orderByFields = $orderByFields;
280
281 if (!is_array($this->MOUNTS)) {
282 $this->MOUNTS = array(0 => 0); // dummy
283 }
284
285 $this->setTreeName();
286
287 if($this->table) {
288 t3lib_div::loadTCA($this->table);
289 }
290
291 // setting this to false disables the use of array-trees by default
292 $this->data = false;
293 $this->dataLookup = false;
294 }
295
296
297 /**
298 * Sets the tree name which is used to identify the tree
299 * Used for JavaScript and other things
300 *
301 * @param string Default is the table name. Underscores are stripped.
302 * @return void
303 */
304 function setTreeName($treeName='') {
305 $this->treeName = $treeName ? $treeName : $this->treeName;
306 $this->treeName = $this->treeName ? $this->treeName : $this->table;
307 $this->treeName = str_replace('_','',$this->treeName);
308 }
309
310
311 /**
312 * Adds a fieldname to the internal array ->fieldArray
313 *
314 * @param string Field name to
315 * @param boolean If set, the fieldname will be set no matter what. Otherwise the field name must either be found as key in $TCA[$table]['columns'] or in the list ->defaultList
316 * @return void
317 */
318 function addField($field,$noCheck=0) {
319 global $TCA;
320 if ($noCheck || is_array($TCA[$this->table]['columns'][$field]) || t3lib_div::inList($this->defaultList,$field)) {
321 $this->fieldArray[]=$field;
322 }
323 }
324
325
326
327 /**
328 * Resets the tree, recs, ids, ids_hierarchy and orig_ids_hierarchy internal variables. Use it if you need it.
329 *
330 * @return void
331 */
332 function reset() {
333 $this->tree = array();
334 $this->recs = array();
335 $this->ids = array();
336 $this->ids_hierarchy = array();
337 $this->orig_ids_hierarchy = array();
338 }
339
340
341 /*******************************************
342 *
343 * output
344 *
345 *******************************************/
346
347 /**
348 * Will create and return the HTML code for a browsable tree
349 * Is based on the mounts found in the internal array ->MOUNTS (set in the constructor)
350 *
351 * @return string HTML code for the browsable tree
352 */
353 function getBrowsableTree() {
354
355 // Get stored tree structure AND updating it if needed according to incoming PM GET var.
356 $this->initializePositionSaving();
357
358 // Init done:
359 $titleLen=intval($this->BE_USER->uc['titleLen']);
360 $treeArr=array();
361
362 // Traverse mounts:
363 foreach($this->MOUNTS as $idx => $uid) {
364
365 // Set first:
366 $this->bank=$idx;
367 $isOpen = $this->stored[$idx][$uid] || $this->expandFirst;
368
369 // Save ids while resetting everything else.
370 $curIds = $this->ids;
371 $this->reset();
372 $this->ids = $curIds;
373
374 // Set PM icon for root of mount:
375 $cmd=$this->bank.'_'.($isOpen?"0_":"1_").$uid.'_'.$this->treeName;
376 $icon='<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/ol/'.($isOpen?'minus':'plus').'only.gif','width="18" height="16"').' alt="" />';
377 $firstHtml= $this->PM_ATagWrap($icon,$cmd);
378
379 // Preparing rootRec for the mount
380 if ($uid) {
381 $rootRec = $this->getRecord($uid);
382 $firstHtml.=$this->getIcon($rootRec);
383 } else {
384 // Artificial record for the tree root, id=0
385 $rootRec = $this->getRootRecord($uid);
386 $firstHtml.=$this->getRootIcon($rootRec);
387 }
388
389 if (is_array($rootRec)) {
390 $uid = $rootRec['uid']; // In case it was swapped inside getRecord due to workspaces.
391
392 // Add the root of the mount to ->tree
393 $this->tree[]=array('HTML'=>$firstHtml, 'row'=>$rootRec, 'bank'=>$this->bank);
394
395 // If the mount is expanded, go down:
396 if ($isOpen) {
397 // Set depth:
398 $depthD='<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/ol/blank.gif','width="18" height="16"').' alt="" />';
399 if ($this->addSelfId) $this->ids[] = $uid;
400 $this->getTree($uid,999,$depthD,'',$rootRec['_SUBCSSCLASS']);
401 }
402
403 // Add tree:
404 $treeArr=array_merge($treeArr,$this->tree);
405 }
406 }
407 return $this->printTree($treeArr);
408 }
409
410 /**
411 * Compiles the HTML code for displaying the structure found inside the ->tree array
412 *
413 * @param array "tree-array" - if blank string, the internal ->tree array is used.
414 * @return string The HTML code for the tree
415 */
416 function printTree($treeArr='') {
417 $titleLen=intval($this->BE_USER->uc['titleLen']);
418 if (!is_array($treeArr)) $treeArr=$this->tree;
419 $out='';
420
421 // put a table around it with IDs to access the rows from JS
422 // not a problem if you don't need it
423 // In XHTML there is no "name" attribute of <td> elements - but Mozilla will not be able to highlight rows if the name attribute is NOT there.
424 $out .= '
425
426 <!--
427 TYPO3 tree structure.
428 -->
429 <table cellpadding="0" cellspacing="0" border="0" id="typo3-tree">';
430
431 foreach($treeArr as $k => $v) {
432 $idAttr = htmlspecialchars($this->domIdPrefix.$this->getId($v['row']).'_'.$v['bank']);
433
434 $out.='
435 <tr>
436 <td id="'.$idAttr.'"'.
437 ($v['row']['_CSSCLASS'] ? ' class="'.$v['row']['_CSSCLASS'].'"' : '').'>'.
438 $v['HTML'].
439 $this->wrapTitle($this->getTitleStr($v['row'],$titleLen),$v['row'],$v['bank']).
440 '</td>
441 </tr>
442 ';
443 }
444 $out .= '
445 </table>';
446 return $out;
447 }
448
449
450
451 /*******************************************
452 *
453 * rendering parts
454 *
455 *******************************************/
456
457
458
459 /**
460 * Generate the plus/minus icon for the browsable tree.
461 *
462 * @param array record for the entry
463 * @param integer The current entry number
464 * @param integer The total number of entries. If equal to $a, a "bottom" element is returned.
465 * @param integer The number of sub-elements to the current element.
466 * @param boolean The element was expanded to render subelements if this flag is set.
467 * @return string Image tag with the plus/minus icon.
468 * @access private
469 * @see t3lib_pageTree::PMicon()
470 */
471 function PMicon($row,$a,$c,$nextCount,$exp) {
472 $PM = $nextCount ? ($exp?'minus':'plus') : 'join';
473 $BTM = ($a==$c)?'bottom':'';
474 $icon = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/ol/'.$PM.$BTM.'.gif','width="18" height="16"').' alt="" />';
475
476 if ($nextCount) {
477 $cmd=$this->bank.'_'.($exp?'0_':'1_').$row['uid'].'_'.$this->treeName;
478 $bMark=($this->bank.'_'.$row['uid']);
479 $icon = $this->PM_ATagWrap($icon,$cmd,$bMark);
480 }
481 return $icon;
482 }
483
484 /**
485 * Wrap the plus/minus icon in a link
486 *
487 * @param string HTML string to wrap, probably an image tag.
488 * @param string Command for 'PM' get var
489 * @param boolean If set, the link will have a anchor point (=$bMark) and a name attribute (=$bMark)
490 * @return string Link-wrapped input string
491 * @access private
492 */
493 function PM_ATagWrap($icon,$cmd,$bMark='') {
494 if ($this->thisScript) {
495 if ($bMark) {
496 $anchor = '#'.$bMark;
497 $name=' name="'.$bMark.'"';
498 }
499 $aUrl = $this->thisScript.'?PM='.$cmd.$anchor;
500 return '<a href="'.htmlspecialchars($aUrl).'"'.$name.'>'.$icon.'</a>';
501 } else {
502 return $icon;
503 }
504 }
505
506 /**
507 * Wrapping $title in a-tags.
508 *
509 * @param string Title string
510 * @param string Item record
511 * @param integer Bank pointer (which mount point number)
512 * @return string
513 * @access private
514 */
515 function wrapTitle($title,$row,$bank=0) {
516 $aOnClick = 'return jumpTo(\''.$this->getJumpToParam($row).'\',this,\''.$this->domIdPrefix.$this->getId($row).'\','.$bank.');';
517 return '<a href="#" onclick="'.htmlspecialchars($aOnClick).'">'.$title.'</a>';
518 }
519
520 /**
521 * Wrapping the image tag, $icon, for the row, $row (except for mount points)
522 *
523 * @param string The image tag for the icon
524 * @param array The row for the current element
525 * @return string The processed icon input value.
526 * @access private
527 */
528 function wrapIcon($icon,$row) {
529 return $icon;
530 }
531
532 /**
533 * Adds attributes to image tag.
534 *
535 * @param string Icon image tag
536 * @param string Attributes to add, eg. ' border="0"'
537 * @return string Image tag, modified with $attr attributes added.
538 */
539 function addTagAttributes($icon,$attr) {
540 return ereg_replace(' ?\/?>$','',$icon).' '.$attr.' />';
541 }
542
543 /**
544 * Adds a red "+" to the input string, $str, if the field "php_tree_stop" in the $row (pages) is set
545 *
546 * @param string Input string, like a page title for the tree
547 * @param array record row with "php_tree_stop" field
548 * @return string Modified string
549 * @access private
550 */
551 function wrapStop($str,$row) {
552 if ($row['php_tree_stop']) {
553 $str.='<span class="typo3-red">+ </span>';
554 }
555 return $str;
556 }
557
558
559
560
561
562
563 /*******************************************
564 *
565 * tree handling
566 *
567 *******************************************/
568
569
570 /**
571 * Returns true/false if the next level for $id should be expanded - based on data in $this->stored[][] and ->expandAll flag.
572 * Extending parent function
573 *
574 * @param integer record id/key
575 * @return boolean
576 * @access private
577 * @see t3lib_pageTree::expandNext()
578 */
579 function expandNext($id) {
580 return ($this->stored[$this->bank][$id] || $this->expandAll)? 1 : 0;
581 }
582
583 /**
584 * Get stored tree structure AND updating it if needed according to incoming PM GET var.
585 *
586 * @return void
587 * @access private
588 */
589 function initializePositionSaving() {
590 // Get stored tree structure:
591 $this->stored=unserialize($this->BE_USER->uc['browseTrees'][$this->treeName]);
592
593 // PM action
594 // (If an plus/minus icon has been clicked, the PM GET var is sent and we must update the stored positions in the tree):
595 $PM = explode('_',t3lib_div::_GP('PM')); // 0: mount key, 1: set/clear boolean, 2: item ID (cannot contain "_"), 3: treeName
596 if (count($PM)==4 && $PM[3]==$this->treeName) {
597 if (isset($this->MOUNTS[$PM[0]])) {
598 if ($PM[1]) { // set
599 $this->stored[$PM[0]][$PM[2]]=1;
600 $this->savePosition();
601 } else { // clear
602 unset($this->stored[$PM[0]][$PM[2]]);
603 $this->savePosition();
604 }
605 }
606 }
607 }
608
609 /**
610 * Saves the content of ->stored (keeps track of expanded positions in the tree)
611 * $this->treeName will be used as key for BE_USER->uc[] to store it in
612 *
613 * @return void
614 * @access private
615 */
616 function savePosition() {
617 $this->BE_USER->uc['browseTrees'][$this->treeName] = serialize($this->stored);
618 $this->BE_USER->writeUC();
619 }
620
621
622
623
624
625
626
627
628
629
630
631
632
633 /******************************
634 *
635 * Functions that might be overwritten by extended classes
636 *
637 ********************************/
638
639 /**
640 * Returns the root icon for a tree/mountpoint (defaults to the globe)
641 *
642 * @param array Record for root.
643 * @return string Icon image tag.
644 */
645 function getRootIcon($rec) {
646 return $this->wrapIcon('<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/i/_icon_website.gif','width="18" height="16"').' alt="" />',$rec);
647 }
648
649
650
651 /**
652 * Get icon for the row.
653 * If $this->iconPath and $this->iconName is set, try to get icon based on those values.
654 *
655 * @param array Item row.
656 * @return string Image tag.
657 */
658 function getIcon($row) {
659 if ($this->iconPath && $this->iconName) {
660 $icon = '<img'.t3lib_iconWorks::skinImg('',$this->iconPath.$this->iconName,'width="18" height="16"').' alt=""'.($this->showDefaultTitleAttribute ? ' title="UID: '.$row['uid'].'"':'').' />';
661 } else {
662 $icon = t3lib_iconWorks::getIconImage($this->table,$row,$this->backPath,'align="top" class="c-recIcon"'.($this->showDefaultTitleAttribute ? ' title="UID: '.$row['uid'].'"':''));
663 }
664
665 return $this->wrapIcon($icon,$row);
666 }
667
668
669 /**
670 * Returns the title for the input record. If blank, a "no title" labele (localized) will be returned.
671 * Do NOT htmlspecialchar the string from this function - has already been done.
672 *
673 * @param array The input row array (where the key "title" is used for the title)
674 * @param integer Title length (30)
675 * @return string The title.
676 */
677 function getTitleStr($row,$titleLen=30) {
678 $title = (!strcmp(trim($row['title']),'')) ? '<em>['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title',1).']</em>' : htmlspecialchars(t3lib_div::fixed_lgd_cs($row['title'],$titleLen));
679 return $title;
680 }
681
682 /**
683 * Returns the value for the image "title" attribute
684 *
685 * @param array The input row array (where the key "title" is used for the title)
686 * @return string The attribute value (is htmlspecialchared() already)
687 * @see wrapIcon()
688 */
689 function getTitleAttrib($row) {
690 return htmlspecialchars($row['title']);
691 }
692
693 /**
694 * Returns the id from the record (typ. uid)
695 *
696 * @param array Record array
697 * @return integer The "uid" field value.
698 */
699 function getId($row) {
700 return $row['uid'];
701 }
702
703 /**
704 * Returns jump-url parameter value.
705 *
706 * @param array The record array.
707 * @return string The jump-url parameter.
708 */
709 function getJumpToParam($row) {
710 return $this->getId($row);
711 }
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727 /********************************
728 *
729 * tree data buidling
730 *
731 ********************************/
732
733 /**
734 * Fetches the data for the tree
735 *
736 * @param integer item id for which to select subitems (parent id)
737 * @param integer Max depth (recursivity limit)
738 * @param string HTML-code prefix for recursive calls.
739 * @param string ? (internal)
740 * @param string CSS class to use for <td> sub-elements
741 * @return integer The count of items on the level
742 */
743 function getTree($uid, $depth=999, $depthData='',$blankLineCode='',$subCSSclass='') {
744
745 // Buffer for id hierarchy is reset:
746 $this->buffer_idH=array();
747
748 // Init vars
749 $depth=intval($depth);
750 $HTML='';
751 $a=0;
752
753 $res = $this->getDataInit($uid,$subCSSclass);
754 $c = $this->getDataCount($res);
755 $crazyRecursionLimiter = 999;
756
757 // Traverse the records:
758 while ($crazyRecursionLimiter>0 && $row = $this->getDataNext($res,$subCSSclass)) {
759 $a++;
760 $crazyRecursionLimiter--;
761
762 $newID = $row['uid'];
763
764 if ($newID==0) {
765 t3lib_BEfunc::typo3PrintError ('Endless recursion detected', 'TYPO3 has detected an error in the database. Please fix it manually (e.g. using phpMyAdmin) and change the UID of '.$this->table.':0 to a new value.<br /><br />See <a href="http://bugs.typo3.org/view.php?id=3495" target="_blank">bugs.typo3.org/view.php?id=3495</a> to get more information about a possible cause.',0);
766 exit;
767 }
768
769 $this->tree[]=array(); // Reserve space.
770 end($this->tree);
771 $treeKey = key($this->tree); // Get the key for this space
772 $LN = ($a==$c)?'blank':'line';
773
774 // If records should be accumulated, do so
775 if ($this->setRecs) {
776 $this->recs[$row['uid']] = $row;
777 }
778
779 // Accumulate the id of the element in the internal arrays
780 $this->ids[] = $idH[$row['uid']]['uid'] = $row['uid'];
781 $this->ids_hierarchy[$depth][] = $row['uid'];
782 $this->orig_ids_hierarchy[$depth][] = $row['_ORIG_uid'] ? $row['_ORIG_uid'] : $row['uid'];
783
784 // Make a recursive call to the next level
785 $HTML_depthData = $depthData.'<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/ol/'.$LN.'.gif','width="18" height="16"').' alt="" />';
786 if ($depth>1 && $this->expandNext($newID) && !$row['php_tree_stop']) {
787 $nextCount=$this->getTree(
788 $newID,
789 $depth-1,
790 $this->makeHTML ? $HTML_depthData : '',
791 $blankLineCode.','.$LN,
792 $row['_SUBCSSCLASS']
793 );
794 if (count($this->buffer_idH)) $idH[$row['uid']]['subrow']=$this->buffer_idH;
795 $exp=1; // Set "did expand" flag
796 } else {
797 $nextCount=$this->getCount($newID);
798 $exp=0; // Clear "did expand" flag
799 }
800
801 // Set HTML-icons, if any:
802 if ($this->makeHTML) {
803 $HTML = $depthData.$this->PMicon($row,$a,$c,$nextCount,$exp);
804 $HTML.=$this->wrapStop($this->getIcon($row),$row);
805 # $HTML.=$this->wrapStop($this->wrapIcon($this->getIcon($row),$row),$row);
806 }
807
808 // Finally, add the row/HTML content to the ->tree array in the reserved key.
809 $this->tree[$treeKey] = Array(
810 'row'=>$row,
811 'HTML'=>$HTML,
812 'HTML_depthData' => $this->makeHTML==2 ? $HTML_depthData : '',
813 'invertedDepth'=>$depth,
814 'blankLineCode'=>$blankLineCode,
815 'bank' => $this->bank
816 );
817 }
818
819 $this->getDataFree($res);
820 $this->buffer_idH=$idH;
821 return $c;
822 }
823
824
825
826
827
828
829
830
831
832
833
834
835 /********************************
836 *
837 * Data handling
838 * Works with records and arrays
839 *
840 ********************************/
841
842 /**
843 * Returns the number of records having the parent id, $uid
844 *
845 * @param integer id to count subitems for
846 * @return integer
847 * @access private
848 */
849 function getCount($uid) {
850 if (is_array($this->data)) {
851 $res = $this->getDataInit($uid);
852 return $this->getDataCount($res);
853 } else {
854 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
855 'count(*)',
856 $this->table,
857 $this->parentField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($uid, $this->table).
858 t3lib_BEfunc::deleteClause($this->table).
859 t3lib_BEfunc::versioningPlaceholderClause($this->table).
860 $this->clause // whereClauseMightContainGroupOrderBy
861 );
862 $row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
863 return $row[0];
864 }
865 }
866
867
868
869 /**
870 * Returns root record for uid (<=0)
871 *
872 * @param integer uid, <= 0 (normally, this does not matter)
873 * @return array Array with title/uid keys with values of $this->title/0 (zero)
874 */
875 function getRootRecord($uid) {
876 return array('title'=>$this->title, 'uid'=>0);
877 }
878
879
880 /**
881 * Returns the record for a uid.
882 * For tables: Looks up the record in the database.
883 * For arrays: Returns the fake record for uid id.
884 *
885 * @param integer UID to look up
886 * @return array The record
887 */
888 function getRecord($uid) {
889 if (is_array($this->data)) {
890 return $this->dataLookup[$uid];
891 } else {
892 $row = t3lib_befunc::getRecordWSOL($this->table,$uid);
893
894 return $row;
895 }
896 }
897
898 /**
899 * Getting the tree data: Selecting/Initializing data pointer to items for a certain parent id.
900 * For tables: This will make a database query to select all children to "parent"
901 * For arrays: This will return key to the ->dataLookup array
902 *
903 * @param integer parent item id
904 * @param string Class for sub-elements.
905 * @return mixed data handle (Tables: An sql-resource, arrays: A parentId integer. -1 is returned if there were NO subLevel.)
906 * @access private
907 */
908 function getDataInit($parentId,$subCSSclass='') {
909 if (is_array($this->data)) {
910 if (!is_array($this->dataLookup[$parentId][$this->subLevelID])) {
911 $parentId = -1;
912 } else {
913 reset($this->dataLookup[$parentId][$this->subLevelID]);
914 }
915 return $parentId;
916 } else {
917 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
918 implode(',',$this->fieldArray),
919 $this->table,
920 $this->parentField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($parentId, $this->table).
921 t3lib_BEfunc::deleteClause($this->table).
922 t3lib_BEfunc::versioningPlaceholderClause($this->table).
923 $this->clause, // whereClauseMightContainGroupOrderBy
924 '',
925 $this->orderByFields
926 );
927 return $res;
928 }
929 }
930
931 /**
932 * Getting the tree data: Counting elements in resource
933 *
934 * @param mixed data handle
935 * @return integer number of items
936 * @access private
937 * @see getDataInit()
938 */
939 function getDataCount(&$res) {
940 if (is_array($this->data)) {
941 return count($this->dataLookup[$res][$this->subLevelID]);
942 } else {
943 $c = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
944 return $c;
945 }
946 }
947
948 /**
949 * Getting the tree data: next entry
950 *
951 * @param mixed data handle
952 * @param string CSS class for sub elements (workspace related)
953 * @return array item data array OR FALSE if end of elements.
954 * @access private
955 * @see getDataInit()
956 */
957 function getDataNext(&$res,$subCSSclass='') {
958 if (is_array($this->data)) {
959 if ($res<0) {
960 $row=FALSE;
961 } else {
962 list(,$row) = each($this->dataLookup[$res][$this->subLevelID]);
963
964 // Passing on default <td> class for subelements:
965 if (is_array($row) && $subCSSclass!=='') {
966 $row['_CSSCLASS'] = $row['_SUBCSSCLASS'] = $subCSSclass;
967 }
968 }
969 return $row;
970 } else {
971 $row = @$GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
972 t3lib_BEfunc::workspaceOL($this->table, $row, $this->BE_USER->workspace);
973
974 // Passing on default <td> class for subelements:
975 if (is_array($row) && $subCSSclass!=='') {
976
977 if ($this->table==='pages' && $this->highlightPagesWithVersions && !isset($row['_CSSCLASS']) && count(t3lib_BEfunc::countVersionsOfRecordsOnPage($this->BE_USER->workspace, $row['uid'], TRUE))) {
978 $row['_CSSCLASS'] = 'ver-versions';
979 }
980
981 if (!isset($row['_CSSCLASS'])) $row['_CSSCLASS'] = $subCSSclass;
982 if (!isset($row['_SUBCSSCLASS'])) $row['_SUBCSSCLASS'] = $subCSSclass;
983 }
984
985 return $row;
986 }
987 }
988
989 /**
990 * Getting the tree data: frees data handle
991 *
992 * @param mixed data handle
993 * @return void
994 * @access private
995 */
996 function getDataFree(&$res){
997 if (is_array($this->data)) {
998 # unset();
999 } else {
1000 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1001 }
1002 }
1003
1004 /**
1005 * Used to initialize class with an array to browse.
1006 * The array inputted will be traversed and an internal index for lookup is created.
1007 * The keys of the input array are perceived as "uid"s of records which means that keys GLOBALLY must be unique like uids are.
1008 * "uid" and "pid" "fakefields" are also set in each record.
1009 * All other fields are optional.
1010 *
1011 * @param array The input array, see examples below in this script.
1012 * @param boolean Internal, for recursion.
1013 * @param integer Internal, for recursion.
1014 * @return void
1015 */
1016 function setDataFromArray(&$dataArr,$traverse=FALSE,$pid=0) {
1017 if (!$traverse) {
1018 $this->data = &$dataArr;
1019 $this->dataLookup=array();
1020 // add root
1021 $this->dataLookup[0][$this->subLevelID]=&$dataArr;
1022 }
1023
1024 foreach($dataArr as $uid => $val) {
1025
1026 $dataArr[$uid]['uid']=$uid;
1027 $dataArr[$uid]['pid']=$pid;
1028
1029 // gives quick access to id's
1030 $this->dataLookup[$uid] = &$dataArr[$uid];
1031
1032 if (is_array($val[$this->subLevelID])) {
1033 $this->setDataFromArray($dataArr[$uid][$this->subLevelID],TRUE,$uid);
1034 }
1035 }
1036 }
1037
1038 /**
1039 * Sets the internal data arrays
1040 *
1041 * @param array Content for $this->data
1042 * @param array Content for $this->dataLookup
1043 * @return void
1044 */
1045 function setDataFromTreeArray(&$treeArr, &$treeLookupArr) {
1046 $this->data = &$treeArr;
1047 $this->dataLookup=&$treeLookupArr;
1048 }
1049
1050
1051 /*
1052 array(
1053 [id1] => array(
1054 'title'=>'title...',
1055 'id' => 'id1',
1056 'icon' => 'icon ref, relative to typo3/ folder...'
1057 ),
1058 [id2] => array(
1059 'title'=>'title...',
1060 'id' => 'id2',
1061 'icon' => 'icon ref, relative to typo3/ folder...'
1062 ),
1063 [id3] => array(
1064 'title'=>'title...',
1065 'id' => 'id3',
1066 'icon' => 'icon ref, relative to typo3/ folder...'
1067 $this->subLevelID => array(
1068 [id3_asdf#1] => array(
1069 'title'=>'title...',
1070 'id' => 'asdf#1',
1071 'icon' => 'icon ref, relative to typo3/ folder...'
1072 ),
1073 [5] => array(
1074 'title'=>'title...',
1075 'id' => 'id...',
1076 'icon' => 'icon ref, relative to typo3/ folder...'
1077 ),
1078 [6] => array(
1079 'title'=>'title...',
1080 'id' => 'id...',
1081 'icon' => 'icon ref, relative to typo3/ folder...'
1082 ),
1083 )
1084 ),
1085 )
1086 */
1087 }
1088
1089
1090 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_treeview.php']) {
1091 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_treeview.php']);
1092 }
1093 ?>