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