[TASK] Clean up tree code
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Tree / View / AbstractTreeView.php
1 <?php
2 namespace TYPO3\CMS\Backend\Tree\View;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Backend\Utility\IconUtility;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Base class for creating a browsable array/page/folder tree in HTML
23 */
24 abstract class AbstractTreeView {
25
26 // EXTERNAL, static:
27 // If set, the first element in the tree is always expanded.
28 /**
29 * @var int
30 */
31 public $expandFirst = 0;
32
33 // If set, then ALL items will be expanded, regardless of stored settings.
34 /**
35 * @var int
36 */
37 public $expandAll = 0;
38
39 // Holds the current script to reload to.
40 /**
41 * @var string
42 */
43 public $thisScript = '';
44
45 // Which HTML attribute to use: alt/title. See init().
46 /**
47 * @var string
48 */
49 public $titleAttrib = 'title';
50
51 // If TRUE, no context menu is rendered on icons. If set to "titlelink" the
52 // icon is linked as the title is.
53 /**
54 * @var bool
55 */
56 public $ext_IconMode = FALSE;
57
58 // If set, the id of the mounts will be added to the internal ids array
59 /**
60 * @var int
61 */
62 public $addSelfId = 0;
63
64 // Used if the tree is made of records (not folders for ex.)
65 /**
66 * @var string
67 */
68 public $title = 'no title';
69
70 // If TRUE, a default title attribute showing the UID of the record is shown.
71 // This cannot be enabled by default because it will destroy many applications
72 // where another title attribute is in fact applied later.
73 /**
74 * @var bool
75 */
76 public $showDefaultTitleAttribute = FALSE;
77
78 /**
79 * Needs to be initialized with $GLOBALS['BE_USER']
80 * Done by default in init()
81 *
82 * @var \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
83 */
84 public $BE_USER = '';
85
86 /**
87 * Needs to be initialized with e.g. $GLOBALS['BE_USER']->returnWebmounts()
88 * Default setting in init() is 0 => 0
89 * The keys are mount-ids (can be anything basically) and the
90 * values are the ID of the root element (COULD be zero or anything else.
91 * For pages that would be the uid of the page, zero for the pagetree root.)
92 *
93 * @var string
94 */
95 public $MOUNTS = '';
96
97 /**
98 * Database table to get the tree data from.
99 * Leave blank if data comes from an array.
100 *
101 * @var string
102 */
103 public $table = '';
104
105 /**
106 * Defines the field of $table which is the parent id field (like pid for table pages).
107 *
108 * @var string
109 */
110 public $parentField = 'pid';
111
112 /**
113 * WHERE clause used for selecting records for the tree. Is set by function init.
114 * Only makes sense when $this->table is set.
115 *
116 * @see init()
117 * @var string
118 */
119 public $clause = '';
120
121 /**
122 * Field for ORDER BY. Is set by function init.
123 * Only makes sense when $this->table is set.
124 *
125 * @see init()
126 * @var string
127 */
128 public $orderByFields = '';
129
130 /**
131 * Default set of fields selected from the tree table.
132 * 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)
133 *
134 * @see addField()
135 * @var array
136 */
137 public $fieldArray = array('uid', 'pid', 'title');
138
139 /**
140 * List of other fields which are ALLOWED to set (here, based on the "pages" table!)
141 *
142 * @see addField()
143 * @var array
144 */
145 public $defaultList = 'uid,pid,tstamp,sorting,deleted,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,crdate,cruser_id';
146
147 /**
148 * Unique name for the tree.
149 * Used as key for storing the tree into the BE users settings.
150 * Used as key to pass parameters in links.
151 * MUST NOT contain underscore chars.
152 * etc.
153 *
154 * @var string
155 */
156 public $treeName = '';
157
158 /**
159 * A prefix for table cell id's which will be wrapped around an item.
160 * Can be used for highlighting by JavaScript.
161 * Needs to be unique if multiple trees are on one HTML page.
162 *
163 * @see printTree()
164 * @var string
165 */
166 public $domIdPrefix = 'row';
167
168 /**
169 * Back path for icons
170 *
171 * @var string
172 */
173 public $backPath;
174
175 /**
176 * If TRUE, HTML code is also accumulated in ->tree array during rendering of the tree.
177 * If 2, then also the icon prefix code (depthData) is stored
178 *
179 * @var int
180 */
181 public $makeHTML = 1;
182
183 /**
184 * If TRUE, records as selected will be stored internally in the ->recs array
185 *
186 * @var int
187 */
188 public $setRecs = 0;
189
190 /**
191 * Sets the associative array key which identifies a new sublevel if arrays are used for trees.
192 * This value has formerly been "subLevel" and "--sublevel--"
193 *
194 * @var string
195 */
196 public $subLevelID = '_SUB_LEVEL';
197
198 // *********
199 // Internal
200 // *********
201 // For record trees:
202 // one-dim array of the uid's selected.
203 /**
204 * @var array
205 */
206 public $ids = array();
207
208 // The hierarchy of element uids
209 /**
210 * @var array
211 */
212 public $ids_hierarchy = array();
213
214 // The hierarchy of versioned element uids
215 /**
216 * @var array
217 */
218 public $orig_ids_hierarchy = array();
219
220 // Temporary, internal array
221 /**
222 * @var array
223 */
224 public $buffer_idH = array();
225
226 // For FOLDER trees:
227 // Special UIDs for folders (integer-hashes of paths)
228 /**
229 * @var array
230 */
231 public $specUIDmap = array();
232
233 // For arrays:
234 // Holds the input data array
235 /**
236 * @var bool
237 */
238 public $data = FALSE;
239
240 // Holds an index with references to the data array.
241 /**
242 * @var bool
243 */
244 public $dataLookup = FALSE;
245
246 // For both types
247 // Tree is accumulated in this variable
248 /**
249 * @var array
250 */
251 public $tree = array();
252
253 // Holds (session stored) information about which items in the tree are unfolded and which are not.
254 /**
255 * @var array
256 */
257 public $stored = array();
258
259 // Points to the current mountpoint key
260 /**
261 * @var int
262 */
263 public $bank = 0;
264
265 // Accumulates the displayed records.
266 /**
267 * @var array
268 */
269 public $recs = array();
270
271 /**
272 * Sets the script url depending on being a module or script request
273 */
274 protected function determineScriptUrl() {
275 if ($moduleName = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('M')) {
276 $this->thisScript = \TYPO3\CMS\Backend\Utility\BackendUtility::getModuleUrl($moduleName);
277 } else {
278 $this->thisScript = \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('SCRIPT_NAME');
279 }
280 }
281
282 /**
283 * @return string
284 */
285 protected function getThisScript() {
286 return strpos($this->thisScript, '?') === FALSE ? $this->thisScript . '?' : $this->thisScript . '&';
287 }
288
289 /**
290 * Initialize the tree class. Needs to be overwritten
291 * Will set ->fieldsArray, ->backPath and ->clause
292 *
293 * @param string Record WHERE clause
294 * @param string Record ORDER BY field
295 * @return void
296 */
297 public function init($clause = '', $orderByFields = '') {
298 // Setting BE_USER by default
299 $this->BE_USER = $GLOBALS['BE_USER'];
300 // Setting backpath.
301 $this->backPath = $GLOBALS['BACK_PATH'];
302 // Setting clause
303 if ($clause) {
304 $this->clause = $clause;
305 }
306 if ($orderByFields) {
307 $this->orderByFields = $orderByFields;
308 }
309 if (!is_array($this->MOUNTS)) {
310 // Dummy
311 $this->MOUNTS = array(0 => 0);
312 }
313 // Sets the tree name which is used to identify the tree, used for JavaScript and other things
314 $this->treeName = str_replace('_', '', $this->treeName ?: $this->table);
315 // Setting this to FALSE disables the use of array-trees by default
316 $this->data = FALSE;
317 $this->dataLookup = FALSE;
318 }
319
320 /**
321 * Adds a fieldname to the internal array ->fieldArray
322 *
323 * @param string $field Field name to
324 * @param bool $noCheck If set, the fieldname will be set no matter what. Otherwise the field name must either be found as key in $GLOBALS['TCA'][$table]['columns'] or in the list ->defaultList
325 * @return void
326 */
327 public function addField($field, $noCheck = 0) {
328 if ($noCheck || is_array($GLOBALS['TCA'][$this->table]['columns'][$field]) || GeneralUtility::inList($this->defaultList, $field)) {
329 $this->fieldArray[] = $field;
330 }
331 }
332
333 /**
334 * Resets the tree, recs, ids, ids_hierarchy and orig_ids_hierarchy internal variables. Use it if you need it.
335 *
336 * @return void
337 */
338 public function reset() {
339 $this->tree = array();
340 $this->recs = array();
341 $this->ids = array();
342 $this->ids_hierarchy = array();
343 $this->orig_ids_hierarchy = array();
344 }
345
346 /*******************************************
347 *
348 * output
349 *
350 *******************************************/
351 /**
352 * Will create and return the HTML code for a browsable tree
353 * Is based on the mounts found in the internal array ->MOUNTS (set in the constructor)
354 *
355 * @return string HTML code for the browsable tree
356 */
357 public function getBrowsableTree() {
358 // Get stored tree structure AND updating it if needed according to incoming PM GET var.
359 $this->initializePositionSaving();
360 // Init done:
361 $treeArr = array();
362 // Traverse mounts:
363 foreach ($this->MOUNTS as $idx => $uid) {
364 // Set first:
365 $this->bank = $idx;
366 $isOpen = $this->stored[$idx][$uid] || $this->expandFirst;
367 // Save ids while resetting everything else.
368 $curIds = $this->ids;
369 $this->reset();
370 $this->ids = $curIds;
371 // Set PM icon for root of mount:
372 $cmd = $this->bank . '_' . ($isOpen ? '0_' : '1_') . $uid . '_' . $this->treeName;
373
374 $firstHtml = $this->PM_ATagWrap('', $cmd, '', $isOpen);
375 // Preparing rootRec for the mount
376 if ($uid) {
377 $rootRec = $this->getRecord($uid);
378 $firstHtml .= $this->getIcon($rootRec);
379 } else {
380 // Artificial record for the tree root, id=0
381 $rootRec = $this->getRootRecord($uid);
382 $firstHtml .= $this->getRootIcon($rootRec);
383 }
384 if (is_array($rootRec)) {
385 // In case it was swapped inside getRecord due to workspaces.
386 $uid = $rootRec['uid'];
387 // Add the root of the mount to ->tree
388 $this->tree[] = array('HTML' => $firstHtml, 'row' => $rootRec, 'hasSub' => $isOpen, 'bank' => $this->bank);
389 // If the mount is expanded, go down:
390 if ($isOpen) {
391 if ($this->addSelfId) {
392 $this->ids[] = $uid;
393 }
394 $this->getTree($uid);
395 }
396 // Add tree:
397 $treeArr = array_merge($treeArr, $this->tree);
398 }
399 }
400 return $this->printTree($treeArr);
401 }
402
403 /**
404 * Compiles the HTML code for displaying the structure found inside the ->tree array
405 *
406 * @param array $treeArr "tree-array" - if blank string, the internal ->tree array is used.
407 * @return string The HTML code for the tree
408 */
409 public function printTree($treeArr = '') {
410 $titleLen = (int)$this->BE_USER->uc['titleLen'];
411 if (!is_array($treeArr)) {
412 $treeArr = $this->tree;
413 }
414 $out = '';
415 $closeDepth = array();
416 foreach ($treeArr as $treeItem) {
417 $classAttr = '';
418 if ($treeItem['isFirst']) {
419 $out .= '<ul class="list-tree">';
420 }
421
422 // Add CSS classes to the list item
423 if ($treeItem['hasSub']) {
424 $classAttr .= ' list-tree-control-open';
425 }
426
427 $idAttr = htmlspecialchars($this->domIdPrefix . $this->getId($treeItem['row']) . '_' . $treeItem['bank']);
428 $out .= '<li id="' . $idAttr . '"' . ($classAttr ? ' class="' . trim($classAttr) . '"' : '') . '><span class="list-tree-group">' . $treeItem['HTML'] . $this->wrapTitle($this->getTitleStr($treeItem['row'], $titleLen), $treeItem['row'], $treeItem['bank']) . '</span>';
429
430 if (!$treeItem['hasSub']) {
431 $out .= '</li>';
432 }
433
434 // We have to remember if this is the last one
435 // on level X so the last child on level X+1 closes the <ul>-tag
436 if ($treeItem['isLast']) {
437 $closeDepth[$treeItem['invertedDepth']] = 1;
438 }
439 // If this is the last one and does not have subitems, we need to close
440 // the tree as long as the upper levels have last items too
441 if ($treeItem['isLast'] && !$treeItem['hasSub']) {
442 for ($i = $treeItem['invertedDepth']; $closeDepth[$i] == 1; $i++) {
443 $closeDepth[$i] = 0;
444 $out .= '</ul></li>';
445 }
446 }
447 }
448 $out = '<ul class="list-tree list-tree-root">' . $out . '</ul>';
449 return $out;
450 }
451
452 /*******************************************
453 *
454 * rendering parts
455 *
456 *******************************************/
457 /**
458 * Generate the plus/minus icon for the browsable tree.
459 *
460 * @param array $row Record for the entry
461 * @param int $a The current entry number
462 * @param int $c The total number of entries. If equal to $a, a "bottom" element is returned.
463 * @param int $nextCount The number of sub-elements to the current element.
464 * @param bool $isOpen 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 \TYPO3\CMS\Backend\Tree\View\PageTreeView::PMicon()
468 */
469 public function PMicon($row, $a, $c, $nextCount, $isOpen) {
470 if ($nextCount) {
471 $cmd = $this->bank . '_' . ($isOpen ? '0_' : '1_') . $row['uid'] . '_' . $this->treeName;
472 $bMark = $this->bank . '_' . $row['uid'];
473 return $this->PM_ATagWrap('', $cmd, $bMark, $isOpen);
474 } else {
475 return '';
476 }
477 }
478
479 /**
480 * Wrap the plus/minus icon in a link
481 *
482 * @param string $icon HTML string to wrap, probably an image tag.
483 * @param string $cmd Command for 'PM' get var
484 * @param bool $bMark If set, the link will have a anchor point (=$bMark) and a name attribute (=$bMark)
485 * @param bool $isOpen
486 * @return string Link-wrapped input string
487 * @access private
488 */
489 public function PM_ATagWrap($icon, $cmd, $bMark = '', $isOpen = FALSE) {
490 if ($this->thisScript) {
491 if ($bMark) {
492 $anchor = '#' . $bMark;
493 $name = ' name="' . $bMark . '"';
494 }
495 $aUrl = $this->getThisScript() . 'PM=' . $cmd . $anchor;
496 return '<a class="list-tree-control ' . ($isOpen ? 'list-tree-control-open' : 'list-tree-control-closed') . ' href="' . htmlspecialchars($aUrl) . '"' . $name . '><i class="fa"></i></a>';
497 } else {
498 return $icon;
499 }
500 }
501
502 /**
503 * Wrapping $title in a-tags.
504 *
505 * @param string $title Title string
506 * @param string $row Item record
507 * @param int $bank Bank pointer (which mount point number)
508 * @return string
509 * @access private
510 */
511 public function wrapTitle($title, $row, $bank = 0) {
512 $aOnClick = 'return jumpTo(' . GeneralUtility::quoteJSvalue($this->getJumpToParam($row)) . ',this,' . GeneralUtility::quoteJSvalue($this->domIdPrefix . $this->getId($row)) . ',' . $bank . ');';
513 return '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . $title . '</a>';
514 }
515
516 /**
517 * Wrapping the image tag, $icon, for the row, $row (except for mount points)
518 *
519 * @param string $icon The image tag for the icon
520 * @param array $row The row for the current element
521 * @return string The processed icon input value.
522 * @access private
523 */
524 public function wrapIcon($icon, $row) {
525 return $icon;
526 }
527
528 /**
529 * Adds attributes to image tag.
530 *
531 * @param string $icon Icon image tag
532 * @param string $attr Attributes to add, eg. ' border="0"'
533 * @return string Image tag, modified with $attr attributes added.
534 */
535 public function addTagAttributes($icon, $attr) {
536 return preg_replace('/ ?\\/?>$/', '', $icon) . ' ' . $attr . ' />';
537 }
538
539 /**
540 * Adds a red "+" to the input string, $str, if the field "php_tree_stop" in the $row (pages) is set
541 *
542 * @param string $str Input string, like a page title for the tree
543 * @param array $row record row with "php_tree_stop" field
544 * @return string Modified string
545 * @access private
546 */
547 public function wrapStop($str, $row) {
548 if ($row['php_tree_stop']) {
549 $str .= '<a href="' . htmlspecialchars(GeneralUtility::linkThisScript(array('setTempDBmount' => $row['uid']))) . '" class="text-danger">+</a> ';
550 }
551 return $str;
552 }
553
554 /*******************************************
555 *
556 * tree handling
557 *
558 *******************************************/
559 /**
560 * Returns TRUE/FALSE if the next level for $id should be expanded - based on
561 * data in $this->stored[][] and ->expandAll flag.
562 * Extending parent function
563 *
564 * @param int $id Record id/key
565 * @return bool
566 * @access private
567 * @see \TYPO3\CMS\Backend\Tree\View\PageTreeView::expandNext()
568 */
569 public function expandNext($id) {
570 return $this->stored[$this->bank][$id] || $this->expandAll ? 1 : 0;
571 }
572
573 /**
574 * Get stored tree structure AND updating it if needed according to incoming PM GET var.
575 *
576 * @return void
577 * @access private
578 */
579 public function initializePositionSaving() {
580 // Get stored tree structure:
581 $this->stored = unserialize($this->BE_USER->uc['browseTrees'][$this->treeName]);
582 // PM action
583 // (If an plus/minus icon has been clicked, the PM GET var is sent and we
584 // must update the stored positions in the tree):
585 // 0: mount key, 1: set/clear boolean, 2: item ID (cannot contain "_"), 3: treeName
586 $PM = explode('_', GeneralUtility::_GP('PM'));
587 if (count($PM) === 4 && $PM[3] == $this->treeName) {
588 if (isset($this->MOUNTS[$PM[0]])) {
589 // set
590 if ($PM[1]) {
591 $this->stored[$PM[0]][$PM[2]] = 1;
592 $this->savePosition();
593 } else {
594 unset($this->stored[$PM[0]][$PM[2]]);
595 $this->savePosition();
596 }
597 }
598 }
599 }
600
601 /**
602 * Saves the content of ->stored (keeps track of expanded positions in the tree)
603 * $this->treeName will be used as key for BE_USER->uc[] to store it in
604 *
605 * @return void
606 * @access private
607 */
608 public function savePosition() {
609 $this->BE_USER->uc['browseTrees'][$this->treeName] = serialize($this->stored);
610 $this->BE_USER->writeUC();
611 }
612
613 /******************************
614 *
615 * Functions that might be overwritten by extended classes
616 *
617 ********************************/
618 /**
619 * Returns the root icon for a tree/mountpoint (defaults to the globe)
620 *
621 * @param array $rec Record for root.
622 * @return string Icon image tag.
623 */
624 public function getRootIcon($rec) {
625 return $this->wrapIcon(IconUtility::getSpriteIcon('apps-pagetree-root'), $rec);
626 }
627
628 /**
629 * Get icon for the row.
630 *
631 * @param array $row Item row.
632 * @return string Image tag.
633 */
634 public function getIcon($row) {
635 $icon = IconUtility::getSpriteIconForRecord($this->table, $row, array(
636 'title' => $this->showDefaultTitleAttribute ? 'UID: ' . $row['uid'] : $this->getTitleAttrib($row)
637 ));
638 return $this->wrapIcon($icon, $row);
639 }
640
641 /**
642 * Returns the title for the input record. If blank, a "no title" label (localized) will be returned.
643 * Do NOT htmlspecialchar the string from this function - has already been done.
644 *
645 * @param array $row The input row array (where the key "title" is used for the title)
646 * @param int $titleLen Title length (30)
647 * @return string The title.
648 */
649 public function getTitleStr($row, $titleLen = 30) {
650 $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['title'], $titleLen));
651 $title = trim($row['title']) === '' ? '<em>[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', TRUE) . ']</em>' : $title;
652 return $title;
653 }
654
655 /**
656 * Returns the value for the image "title" attribute
657 *
658 * @param array $row The input row array (where the key "title" is used for the title)
659 * @return string The attribute value (is htmlspecialchared() already)
660 * @see wrapIcon()
661 */
662 public function getTitleAttrib($row) {
663 return htmlspecialchars($row['title']);
664 }
665
666 /**
667 * Returns the id from the record (typ. uid)
668 *
669 * @param array $row Record array
670 * @return int The "uid" field value.
671 */
672 public function getId($row) {
673 return $row['uid'];
674 }
675
676 /**
677 * Returns jump-url parameter value.
678 *
679 * @param array $row The record array.
680 * @return string The jump-url parameter.
681 */
682 public function getJumpToParam($row) {
683 return $this->getId($row);
684 }
685
686 /********************************
687 *
688 * tree data buidling
689 *
690 ********************************/
691 /**
692 * Fetches the data for the tree
693 *
694 * @param int $uid item id for which to select subitems (parent id)
695 * @param int $depth Max depth (recursivity limit)
696 * @param string $depthData HTML-code prefix for recursive calls.
697 * @param string $blankLineCode ? (internal)
698 * @param string $subCSSclass CSS class to use for <td> sub-elements
699 * @return int The count of items on the level
700 */
701 public function getTree($uid, $depth = 999, $depthData = '', $blankLineCode = '', $subCSSclass = '') {
702 // Buffer for id hierarchy is reset:
703 $this->buffer_idH = array();
704 // Init vars
705 $depth = (int)$depth;
706 $HTML = '';
707 $a = 0;
708 $res = $this->getDataInit($uid);
709 $c = $this->getDataCount($res);
710 $crazyRecursionLimiter = 999;
711 $idH = array();
712 // Traverse the records:
713 while ($crazyRecursionLimiter > 0 && ($row = $this->getDataNext($res, ''))) {
714 $pageUid = ($this->table === 'pages') ? $row['uid'] : $row['pid'];
715 if (!$GLOBALS['BE_USER']->isInWebMount($pageUid)) {
716 // Current record is not within web mount => skip it
717 continue;
718 }
719
720 $a++;
721 $crazyRecursionLimiter--;
722 $newID = $row['uid'];
723 if ($newID == 0) {
724 throw new \RuntimeException('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. See http://forge.typo3.org/issues/16150 to get more information about a possible cause.', 1294586383);
725 }
726 // Reserve space.
727 $this->tree[] = array();
728 end($this->tree);
729 // Get the key for this space
730 $treeKey = key($this->tree);
731 // If records should be accumulated, do so
732 if ($this->setRecs) {
733 $this->recs[$row['uid']] = $row;
734 }
735 // Accumulate the id of the element in the internal arrays
736 $this->ids[] = ($idH[$row['uid']]['uid'] = $row['uid']);
737 $this->ids_hierarchy[$depth][] = $row['uid'];
738 $this->orig_ids_hierarchy[$depth][] = $row['_ORIG_uid'] ?: $row['uid'];
739
740 // Make a recursive call to the next level
741 $hasSub = $this->expandNext($newID) && !$row['php_tree_stop'];
742 if ($depth > 1 && $hasSub) {
743 $nextCount = $this->getTree($newID, $depth - 1);
744 if (!empty($this->buffer_idH)) {
745 $idH[$row['uid']]['subrow'] = $this->buffer_idH;
746 }
747 // Set "did expand" flag
748 $isOpen = 1;
749 } else {
750 $nextCount = $this->getCount($newID);
751 // Clear "did expand" flag
752 $isOpen = 0;
753 }
754 // Set HTML-icons, if any:
755 if ($this->makeHTML) {
756 $HTML = $this->PMicon($row, $a, $c, $nextCount, $isOpen) . $this->wrapStop($this->getIcon($row), $row);
757 }
758 // Finally, add the row/HTML content to the ->tree array in the reserved key.
759 $this->tree[$treeKey] = array(
760 'row' => $row,
761 'HTML' => $HTML,
762 'invertedDepth' => $depth,
763 'bank' => $this->bank,
764 'hasSub' => $nextCount && $hasSub,
765 'isFirst' => $a === 1,
766 'isLast' => $a === $c,
767 );
768 }
769
770 $this->getDataFree($res);
771 $this->buffer_idH = $idH;
772 return $c;
773 }
774
775 /********************************
776 *
777 * Data handling
778 * Works with records and arrays
779 *
780 ********************************/
781 /**
782 * Returns the number of records having the parent id, $uid
783 *
784 * @param int $uid Id to count subitems for
785 * @return int
786 * @access private
787 */
788 public function getCount($uid) {
789 if (is_array($this->data)) {
790 $res = $this->getDataInit($uid);
791 return $this->getDataCount($res);
792 } else {
793 return $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', $this->table, $this->parentField . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($uid, $this->table) . BackendUtility::deleteClause($this->table) . BackendUtility::versioningPlaceholderClause($this->table) . $this->clause);
794 }
795 }
796
797 /**
798 * Returns root record for uid (<=0)
799 *
800 * @param int $uid uid, <= 0 (normally, this does not matter)
801 * @return array Array with title/uid keys with values of $this->title/0 (zero)
802 */
803 public function getRootRecord($uid) {
804 return array('title' => $this->title, 'uid' => 0);
805 }
806
807 /**
808 * Returns the record for a uid.
809 * For tables: Looks up the record in the database.
810 * For arrays: Returns the fake record for uid id.
811 *
812 * @param int $uid UID to look up
813 * @return array The record
814 */
815 public function getRecord($uid) {
816 if (is_array($this->data)) {
817 return $this->dataLookup[$uid];
818 } else {
819 return BackendUtility::getRecordWSOL($this->table, $uid);
820 }
821 }
822
823 /**
824 * Getting the tree data: Selecting/Initializing data pointer to items for a certain parent id.
825 * For tables: This will make a database query to select all children to "parent"
826 * For arrays: This will return key to the ->dataLookup array
827 *
828 * @param int $parentId parent item id
829 * @param string $subCSSclass Class for sub-elements.
830 * @return mixed Data handle (Tables: An sql-resource, arrays: A parentId integer. -1 is returned if there were NO subLevel.)
831 * @access private
832 */
833 public function getDataInit($parentId, $subCSSclass = '') {
834 if (is_array($this->data)) {
835 if (!is_array($this->dataLookup[$parentId][$this->subLevelID])) {
836 $parentId = -1;
837 } else {
838 reset($this->dataLookup[$parentId][$this->subLevelID]);
839 }
840 return $parentId;
841 } else {
842 return $GLOBALS['TYPO3_DB']->exec_SELECTquery(implode(',', $this->fieldArray), $this->table, $this->parentField . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($parentId, $this->table) . BackendUtility::deleteClause($this->table) . BackendUtility::versioningPlaceholderClause($this->table) . $this->clause, '', $this->orderByFields);
843 }
844 }
845
846 /**
847 * Getting the tree data: Counting elements in resource
848 *
849 * @param mixed $res Data handle
850 * @return int number of items
851 * @access private
852 * @see getDataInit()
853 */
854 public function getDataCount(&$res) {
855 if (is_array($this->data)) {
856 return count($this->dataLookup[$res][$this->subLevelID]);
857 } else {
858 return $GLOBALS['TYPO3_DB']->sql_num_rows($res);
859 }
860 }
861
862 /**
863 * Getting the tree data: next entry
864 *
865 * @param mixed $res Data handle
866 * @param string $subCSSclass CSS class for sub elements (workspace related)
867 * @return array item data array OR FALSE if end of elements.
868 * @access private
869 * @see getDataInit()
870 */
871 public function getDataNext(&$res, $subCSSclass = '') {
872 if (is_array($this->data)) {
873 if ($res < 0) {
874 $row = FALSE;
875 } else {
876 list(, $row) = each($this->dataLookup[$res][$this->subLevelID]);
877 }
878 return $row;
879 } else {
880 while ($row = @$GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
881 BackendUtility::workspaceOL($this->table, $row, $this->BE_USER->workspace, TRUE);
882 if (is_array($row)) {
883 break;
884 }
885 }
886 return $row;
887 }
888 }
889
890 /**
891 * Getting the tree data: frees data handle
892 *
893 * @param mixed $res Data handle
894 * @return void
895 * @access private
896 */
897 public function getDataFree(&$res) {
898 if (!is_array($this->data)) {
899 $GLOBALS['TYPO3_DB']->sql_free_result($res);
900 }
901 }
902
903 /**
904 * Used to initialize class with an array to browse.
905 * The array inputted will be traversed and an internal index for lookup is created.
906 * The keys of the input array are perceived as "uid"s of records which means that keys GLOBALLY must be unique like uids are.
907 * "uid" and "pid" "fakefields" are also set in each record.
908 * All other fields are optional.
909 *
910 * @param array $dataArr The input array, see examples below in this script.
911 * @param bool $traverse Internal, for recursion.
912 * @param int $pid Internal, for recursion.
913 * @return void
914 */
915 public function setDataFromArray(&$dataArr, $traverse = FALSE, $pid = 0) {
916 if (!$traverse) {
917 $this->data = &$dataArr;
918 $this->dataLookup = array();
919 // Add root
920 $this->dataLookup[0][$this->subLevelID] = &$dataArr;
921 }
922 foreach ($dataArr as $uid => $val) {
923 $dataArr[$uid]['uid'] = $uid;
924 $dataArr[$uid]['pid'] = $pid;
925 // Gives quick access to id's
926 $this->dataLookup[$uid] = &$dataArr[$uid];
927 if (is_array($val[$this->subLevelID])) {
928 $this->setDataFromArray($dataArr[$uid][$this->subLevelID], TRUE, $uid);
929 }
930 }
931 }
932
933 /**
934 * Sets the internal data arrays
935 *
936 * @param array $treeArr Content for $this->data
937 * @param array $treeLookupArr Content for $this->dataLookup
938 * @return void
939 */
940 public function setDataFromTreeArray(&$treeArr, &$treeLookupArr) {
941 $this->data = &$treeArr;
942 $this->dataLookup = &$treeLookupArr;
943 }
944
945 }