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