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