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