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