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