[!!!][FEATURE] ElementBrowser refactoring, LinkBrowser API - Part 1
[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 $this->determineScriptUrl();
275 }
276
277 /**
278 * Sets the script url depending on being a module or script request
279 */
280 protected function determineScriptUrl() {
281 if ($routePath = GeneralUtility::_GP('route')) {
282 $router = GeneralUtility::makeInstance(Router::class);
283 $route = $router->match($routePath);
284 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
285 $this->thisScript = (string)$uriBuilder->buildUriFromRoute($route->getOption('_identifier'));
286 } elseif ($moduleName = GeneralUtility::_GP('M')) {
287 $this->thisScript = BackendUtility::getModuleUrl($moduleName);
288 } else {
289 $this->thisScript = GeneralUtility::getIndpEnv('SCRIPT_NAME');
290 }
291 }
292
293 /**
294 * @return string
295 */
296 protected function getThisScript() {
297 return strpos($this->thisScript, '?') === FALSE ? $this->thisScript . '?' : $this->thisScript . '&';
298 }
299
300 /**
301 * Initialize the tree class. Needs to be overwritten
302 *
303 * @param string $clause Record WHERE clause
304 * @param string $orderByFields Record ORDER BY field
305 * @return void
306 */
307 public function init($clause = '', $orderByFields = '') {
308 // Setting BE_USER by default
309 $this->BE_USER = $GLOBALS['BE_USER'];
310 // Setting clause
311 if ($clause) {
312 $this->clause = $clause;
313 }
314 if ($orderByFields) {
315 $this->orderByFields = $orderByFields;
316 }
317 if (!is_array($this->MOUNTS)) {
318 // Dummy
319 $this->MOUNTS = array(0 => 0);
320 }
321 // Sets the tree name which is used to identify the tree, used for JavaScript and other things
322 $this->treeName = str_replace('_', '', $this->treeName ?: $this->table);
323 // Setting this to FALSE disables the use of array-trees by default
324 $this->data = FALSE;
325 $this->dataLookup = FALSE;
326 }
327
328 /**
329 * Adds a fieldname to the internal array ->fieldArray
330 *
331 * @param string $field Field name to
332 * @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
333 * @return void
334 */
335 public function addField($field, $noCheck = FALSE) {
336 if ($noCheck || is_array($GLOBALS['TCA'][$this->table]['columns'][$field]) || GeneralUtility::inList($this->defaultList, $field)) {
337 $this->fieldArray[] = $field;
338 }
339 }
340
341 /**
342 * Resets the tree, recs, ids, ids_hierarchy and orig_ids_hierarchy internal variables. Use it if you need it.
343 *
344 * @return void
345 */
346 public function reset() {
347 $this->tree = array();
348 $this->recs = array();
349 $this->ids = array();
350 $this->ids_hierarchy = array();
351 $this->orig_ids_hierarchy = array();
352 }
353
354 /*******************************************
355 *
356 * output
357 *
358 *******************************************/
359 /**
360 * Will create and return the HTML code for a browsable tree
361 * Is based on the mounts found in the internal array ->MOUNTS (set in the constructor)
362 *
363 * @return string HTML code for the browsable tree
364 */
365 public function getBrowsableTree() {
366 // Get stored tree structure AND updating it if needed according to incoming PM GET var.
367 $this->initializePositionSaving();
368 // Init done:
369 $treeArr = array();
370 // Traverse mounts:
371 foreach ($this->MOUNTS as $idx => $uid) {
372 // Set first:
373 $this->bank = $idx;
374 $isOpen = $this->stored[$idx][$uid] || $this->expandFirst;
375 // Save ids while resetting everything else.
376 $curIds = $this->ids;
377 $this->reset();
378 $this->ids = $curIds;
379 // Set PM icon for root of mount:
380 $cmd = $this->bank . '_' . ($isOpen ? '0_' : '1_') . $uid . '_' . $this->treeName;
381
382 $firstHtml = $this->PM_ATagWrap('', $cmd, '', $isOpen);
383 // Preparing rootRec for the mount
384 if ($uid) {
385 $rootRec = $this->getRecord($uid);
386 $firstHtml .= $this->getIcon($rootRec);
387 } else {
388 // Artificial record for the tree root, id=0
389 $rootRec = $this->getRootRecord();
390 $firstHtml .= $this->getRootIcon($rootRec);
391 }
392 if (is_array($rootRec)) {
393 // In case it was swapped inside getRecord due to workspaces.
394 $uid = $rootRec['uid'];
395 // Add the root of the mount to ->tree
396 $this->tree[] = array('HTML' => $firstHtml, 'row' => $rootRec, 'hasSub' => $isOpen, 'bank' => $this->bank);
397 // If the mount is expanded, go down:
398 if ($isOpen) {
399 $depthData = '<span class="treeline-icon treeline-icon-clear"></span>';
400 if ($this->addSelfId) {
401 $this->ids[] = $uid;
402 }
403 $this->getTree($uid, 999, $depthData);
404 }
405 // Add tree:
406 $treeArr = array_merge($treeArr, $this->tree);
407 }
408 }
409 return $this->printTree($treeArr);
410 }
411
412 /**
413 * Compiles the HTML code for displaying the structure found inside the ->tree array
414 *
415 * @param array|string $treeArr "tree-array" - if blank string, the internal ->tree array is used.
416 * @return string The HTML code for the tree
417 */
418 public function printTree($treeArr = '') {
419 $titleLen = (int)$this->BE_USER->uc['titleLen'];
420 if (!is_array($treeArr)) {
421 $treeArr = $this->tree;
422 }
423 $out = '';
424 $closeDepth = array();
425 foreach ($treeArr as $treeItem) {
426 $classAttr = '';
427 if ($treeItem['isFirst']) {
428 $out .= '<ul class="list-tree">';
429 }
430
431 // Add CSS classes to the list item
432 if ($treeItem['hasSub']) {
433 $classAttr .= ' list-tree-control-open';
434 }
435
436 $idAttr = htmlspecialchars($this->domIdPrefix . $this->getId($treeItem['row']) . '_' . $treeItem['bank']);
437 $out .= '
438 <li id="' . $idAttr . '"' . ($classAttr ? ' class="' . trim($classAttr) . '"' : '') . '>
439 <span class="list-tree-group">
440 <span class="list-tree-icon">' . $treeItem['HTML'] . '</span>
441 <span class="list-tree-title">' .$this->wrapTitle($this->getTitleStr($treeItem['row'], $titleLen), $treeItem['row'], $treeItem['bank']) . '</span>
442 </span>';
443
444 if (!$treeItem['hasSub']) {
445 $out .= '</li>';
446 }
447
448 // We have to remember if this is the last one
449 // on level X so the last child on level X+1 closes the <ul>-tag
450 if ($treeItem['isLast']) {
451 $closeDepth[$treeItem['invertedDepth']] = 1;
452 }
453 // If this is the last one and does not have subitems, we need to close
454 // the tree as long as the upper levels have last items too
455 if ($treeItem['isLast'] && !$treeItem['hasSub']) {
456 for ($i = $treeItem['invertedDepth']; $closeDepth[$i] == 1; $i++) {
457 $closeDepth[$i] = 0;
458 $out .= '</ul></li>';
459 }
460 }
461 }
462 $out = '<ul class="list-tree list-tree-root list-tree-root-clean">' . $out . '</ul>';
463 return $out;
464 }
465
466 /*******************************************
467 *
468 * rendering parts
469 *
470 *******************************************/
471 /**
472 * Generate the plus/minus icon for the browsable tree.
473 *
474 * @param array $row Record for the entry
475 * @param int $a The current entry number
476 * @param int $c The total number of entries. If equal to $a, a "bottom" element is returned.
477 * @param int $nextCount The number of sub-elements to the current element.
478 * @param bool $isOpen The element was expanded to render subelements if this flag is set.
479 * @return string Image tag with the plus/minus icon.
480 * @access private
481 * @see \TYPO3\CMS\Backend\Tree\View\PageTreeView::PMicon()
482 */
483 public function PMicon($row, $a, $c, $nextCount, $isOpen) {
484 if ($nextCount) {
485 $cmd = $this->bank . '_' . ($isOpen ? '0_' : '1_') . $row['uid'] . '_' . $this->treeName;
486 $bMark = $this->bank . '_' . $row['uid'];
487 return $this->PM_ATagWrap('', $cmd, $bMark, $isOpen);
488 } else {
489 return '';
490 }
491 }
492
493 /**
494 * Wrap the plus/minus icon in a link
495 *
496 * @param string $icon HTML string to wrap, probably an image tag.
497 * @param string $cmd Command for 'PM' get var
498 * @param string $bMark If set, the link will have an anchor point (=$bMark) and a name attribute (=$bMark)
499 * @param bool $isOpen
500 * @return string Link-wrapped input string
501 * @access private
502 */
503 public function PM_ATagWrap($icon, $cmd, $bMark = '', $isOpen = FALSE) {
504 if ($this->thisScript) {
505 $anchor = $bMark ? '#' . $bMark : '';
506 $name = $bMark ? ' name="' . $bMark . '"' : '';
507 $aUrl = $this->getThisScript() . 'PM=' . $cmd . $anchor;
508 return '<a class="list-tree-control ' . ($isOpen ? 'list-tree-control-open' : 'list-tree-control-closed') . ' href="' . htmlspecialchars($aUrl) . '"' . $name . '><i class="fa"></i></a>';
509 } else {
510 return $icon;
511 }
512 }
513
514 /**
515 * Wrapping $title in a-tags.
516 *
517 * @param string $title Title string
518 * @param string $row Item record
519 * @param int $bank Bank pointer (which mount point number)
520 * @return string
521 * @access private
522 */
523 public function wrapTitle($title, $row, $bank = 0) {
524 $aOnClick = 'return jumpTo(' . GeneralUtility::quoteJSvalue($this->getJumpToParam($row)) . ',this,' . GeneralUtility::quoteJSvalue($this->domIdPrefix . $this->getId($row)) . ',' . $bank . ');';
525 return '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . $title . '</a>';
526 }
527
528 /**
529 * Wrapping the image tag, $icon, for the row, $row (except for mount points)
530 *
531 * @param string $icon The image tag for the icon
532 * @param array $row The row for the current element
533 * @return string The processed icon input value.
534 * @access private
535 */
536 public function wrapIcon($icon, $row) {
537 return $icon;
538 }
539
540 /**
541 * Adds attributes to image tag.
542 *
543 * @param string $icon Icon image tag
544 * @param string $attr Attributes to add, eg. ' border="0"'
545 * @return string Image tag, modified with $attr attributes added.
546 */
547 public function addTagAttributes($icon, $attr) {
548 return preg_replace('/ ?\\/?>$/', '', $icon) . ' ' . $attr . ' />';
549 }
550
551 /**
552 * Adds a red "+" to the input string, $str, if the field "php_tree_stop" in the $row (pages) is set
553 *
554 * @param string $str Input string, like a page title for the tree
555 * @param array $row record row with "php_tree_stop" field
556 * @return string Modified string
557 * @access private
558 */
559 public function wrapStop($str, $row) {
560 if ($row['php_tree_stop']) {
561 $str .= '<a href="' . htmlspecialchars(GeneralUtility::linkThisScript(array('setTempDBmount' => $row['uid']))) . '" class="text-danger">+</a> ';
562 }
563 return $str;
564 }
565
566 /*******************************************
567 *
568 * tree handling
569 *
570 *******************************************/
571 /**
572 * Returns TRUE/FALSE if the next level for $id should be expanded - based on
573 * data in $this->stored[][] and ->expandAll flag.
574 * Extending parent function
575 *
576 * @param int $id Record id/key
577 * @return bool
578 * @access private
579 * @see \TYPO3\CMS\Backend\Tree\View\PageTreeView::expandNext()
580 */
581 public function expandNext($id) {
582 return $this->stored[$this->bank][$id] || $this->expandAll ? 1 : 0;
583 }
584
585 /**
586 * Get stored tree structure AND updating it if needed according to incoming PM GET var.
587 *
588 * @return void
589 * @access private
590 */
591 public function initializePositionSaving() {
592 // Get stored tree structure:
593 $this->stored = unserialize($this->BE_USER->uc['browseTrees'][$this->treeName]);
594 // PM action
595 // (If an plus/minus icon has been clicked, the PM GET var is sent and we
596 // must update the stored positions in the tree):
597 // 0: mount key, 1: set/clear boolean, 2: item ID (cannot contain "_"), 3: treeName
598 $PM = explode('_', GeneralUtility::_GP('PM'));
599 if (count($PM) === 4 && $PM[3] == $this->treeName) {
600 if (isset($this->MOUNTS[$PM[0]])) {
601 // set
602 if ($PM[1]) {
603 $this->stored[$PM[0]][$PM[2]] = 1;
604 $this->savePosition();
605 } else {
606 unset($this->stored[$PM[0]][$PM[2]]);
607 $this->savePosition();
608 }
609 }
610 }
611 }
612
613 /**
614 * Saves the content of ->stored (keeps track of expanded positions in the tree)
615 * $this->treeName will be used as key for BE_USER->uc[] to store it in
616 *
617 * @return void
618 * @access private
619 */
620 public function savePosition() {
621 $this->BE_USER->uc['browseTrees'][$this->treeName] = serialize($this->stored);
622 $this->BE_USER->writeUC();
623 }
624
625 /******************************
626 *
627 * Functions that might be overwritten by extended classes
628 *
629 ********************************/
630 /**
631 * Returns the root icon for a tree/mountpoint (defaults to the globe)
632 *
633 * @param array $rec Record for root.
634 * @return string Icon image tag.
635 */
636 public function getRootIcon($rec) {
637 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
638 return $this->wrapIcon($iconFactory->getIcon('apps-pagetree-root', Icon::SIZE_SMALL)->render(), $rec);
639 }
640
641 /**
642 * Get icon for the row.
643 *
644 * @param array $row Item row.
645 * @return string Image tag.
646 */
647 public function getIcon($row) {
648 if (is_int($row)) {
649 $row = BackendUtility::getRecord($this->table, $row);
650 }
651 $title = $this->showDefaultTitleAttribute ? htmlspecialchars('UID: ' . $row['uid']) : $this->getTitleAttrib($row);
652 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
653 $icon = '<span title="' . $title. '">' . $iconFactory->getIconForRecord($this->table, $row, Icon::SIZE_SMALL)->render() . '</span>';
654 return $this->wrapIcon($icon, $row);
655 }
656
657 /**
658 * Returns the title for the input record. If blank, a "no title" label (localized) will be returned.
659 * Do NOT htmlspecialchar the string from this function - has already been done.
660 *
661 * @param array $row The input row array (where the key "title" is used for the title)
662 * @param int $titleLen Title length (30)
663 * @return string The title.
664 */
665 public function getTitleStr($row, $titleLen = 30) {
666 $title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['title'], $titleLen));
667 $title = trim($row['title']) === '' ? '<em>[' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', TRUE) . ']</em>' : $title;
668 return $title;
669 }
670
671 /**
672 * Returns the value for the image "title" attribute
673 *
674 * @param array $row The input row array (where the key "title" is used for the title)
675 * @return string The attribute value (is htmlspecialchared() already)
676 * @see wrapIcon()
677 */
678 public function getTitleAttrib($row) {
679 return htmlspecialchars($row['title']);
680 }
681
682 /**
683 * Returns the id from the record (typ. uid)
684 *
685 * @param array $row Record array
686 * @return int The "uid" field value.
687 */
688 public function getId($row) {
689 return $row['uid'];
690 }
691
692 /**
693 * Returns jump-url parameter value.
694 *
695 * @param array $row The record array.
696 * @return string The jump-url parameter.
697 */
698 public function getJumpToParam($row) {
699 return $this->getId($row);
700 }
701
702 /********************************
703 *
704 * tree data buidling
705 *
706 ********************************/
707 /**
708 * Fetches the data for the tree
709 *
710 * @param int $uid item id for which to select subitems (parent id)
711 * @param int $depth Max depth (recursivity limit)
712 * @param string $depthData HTML-code prefix for recursive calls.
713
714 * @return int The count of items on the level
715 */
716 public function getTree($uid, $depth = 999, $depthData = '') {
717 // Buffer for id hierarchy is reset:
718 $this->buffer_idH = array();
719 // Init vars
720 $depth = (int)$depth;
721 $HTML = '';
722 $a = 0;
723 $res = $this->getDataInit($uid);
724 $c = $this->getDataCount($res);
725 $crazyRecursionLimiter = 999;
726 $idH = array();
727 // Traverse the records:
728 while ($crazyRecursionLimiter > 0 && ($row = $this->getDataNext($res))) {
729 $pageUid = ($this->table === 'pages') ? $row['uid'] : $row['pid'];
730 if (!$this->getBackendUser()->isInWebMount($pageUid)) {
731 // Current record is not within web mount => skip it
732 continue;
733 }
734
735 $a++;
736 $crazyRecursionLimiter--;
737 $newID = $row['uid'];
738 if ($newID == 0) {
739 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);
740 }
741 // Reserve space.
742 $this->tree[] = array();
743 end($this->tree);
744 // Get the key for this space
745 $treeKey = key($this->tree);
746 // If records should be accumulated, do so
747 if ($this->setRecs) {
748 $this->recs[$row['uid']] = $row;
749 }
750 // Accumulate the id of the element in the internal arrays
751 $this->ids[] = ($idH[$row['uid']]['uid'] = $row['uid']);
752 $this->ids_hierarchy[$depth][] = $row['uid'];
753 $this->orig_ids_hierarchy[$depth][] = $row['_ORIG_uid'] ?: $row['uid'];
754
755 // Make a recursive call to the next level
756 $nextLevelDepthData = $depthData . '<span class="treeline-icon treeline-icon-' . ($a === $c ? 'clear' : 'line') .'"></span>';
757 $hasSub = $this->expandNext($newID) && !$row['php_tree_stop'];
758 if ($depth > 1 && $hasSub) {
759 $nextCount = $this->getTree($newID, $depth - 1, $nextLevelDepthData);
760 if (!empty($this->buffer_idH)) {
761 $idH[$row['uid']]['subrow'] = $this->buffer_idH;
762 }
763 // Set "did expand" flag
764 $isOpen = 1;
765 } else {
766 $nextCount = $this->getCount($newID);
767 // Clear "did expand" flag
768 $isOpen = 0;
769 }
770 // Set HTML-icons, if any:
771 if ($this->makeHTML) {
772 $HTML = $this->PMicon($row, $a, $c, $nextCount, $isOpen) . $this->wrapStop($this->getIcon($row), $row);
773 }
774 // Finally, add the row/HTML content to the ->tree array in the reserved key.
775 $this->tree[$treeKey] = array(
776 'row' => $row,
777 'HTML' => $HTML,
778 'invertedDepth' => $depth,
779 'depthData' => $depthData,
780 'bank' => $this->bank,
781 'hasSub' => $nextCount && $hasSub,
782 'isFirst' => $a === 1,
783 'isLast' => $a === $c,
784 );
785 }
786
787 $this->getDataFree($res);
788 $this->buffer_idH = $idH;
789 return $c;
790 }
791
792 /********************************
793 *
794 * Data handling
795 * Works with records and arrays
796 *
797 ********************************/
798 /**
799 * Returns the number of records having the parent id, $uid
800 *
801 * @param int $uid Id to count subitems for
802 * @return int
803 * @access private
804 */
805 public function getCount($uid) {
806 if (is_array($this->data)) {
807 $res = $this->getDataInit($uid);
808 return $this->getDataCount($res);
809 } else {
810 $db = $this->getDatabaseConnection();
811 $where = $this->parentField . '=' . $db->fullQuoteStr($uid, $this->table) . BackendUtility::deleteClause($this->table) . BackendUtility::versioningPlaceholderClause($this->table) . $this->clause;
812 return $db->exec_SELECTcountRows('uid', $this->table, $where);
813 }
814 }
815
816 /**
817 * Returns root record for uid (<=0)
818 *
819 * @return array Array with title/uid keys with values of $this->title/0 (zero)
820 */
821 public function getRootRecord() {
822 return array('title' => $this->title, 'uid' => 0);
823 }
824
825 /**
826 * Returns the record for a uid.
827 * For tables: Looks up the record in the database.
828 * For arrays: Returns the fake record for uid id.
829 *
830 * @param int $uid UID to look up
831 * @return array The record
832 */
833 public function getRecord($uid) {
834 if (is_array($this->data)) {
835 return $this->dataLookup[$uid];
836 } else {
837 return BackendUtility::getRecordWSOL($this->table, $uid);
838 }
839 }
840
841 /**
842 * Getting the tree data: Selecting/Initializing data pointer to items for a certain parent id.
843 * For tables: This will make a database query to select all children to "parent"
844 * For arrays: This will return key to the ->dataLookup array
845 *
846 * @param int $parentId parent item id
847 *
848 * @return mixed Data handle (Tables: An sql-resource, arrays: A parentId integer. -1 is returned if there were NO subLevel.)
849 * @access private
850 */
851 public function getDataInit($parentId) {
852 if (is_array($this->data)) {
853 if (!is_array($this->dataLookup[$parentId][$this->subLevelID])) {
854 $parentId = -1;
855 } else {
856 reset($this->dataLookup[$parentId][$this->subLevelID]);
857 }
858 return $parentId;
859 } else {
860 $db = $this->getDatabaseConnection();
861 $where = $this->parentField . '=' . $db->fullQuoteStr($parentId, $this->table) . BackendUtility::deleteClause($this->table) . BackendUtility::versioningPlaceholderClause($this->table) . $this->clause;
862 return $db->exec_SELECTquery(implode(',', $this->fieldArray), $this->table, $where, '', $this->orderByFields);
863 }
864 }
865
866 /**
867 * Getting the tree data: Counting elements in resource
868 *
869 * @param mixed $res Data handle
870 * @return int number of items
871 * @access private
872 * @see getDataInit()
873 */
874 public function getDataCount(&$res) {
875 if (is_array($this->data)) {
876 return count($this->dataLookup[$res][$this->subLevelID]);
877 } else {
878 return $this->getDatabaseConnection()->sql_num_rows($res);
879 }
880 }
881
882 /**
883 * Getting the tree data: next entry
884 *
885 * @param mixed $res Data handle
886 *
887 * @return array item data array OR FALSE if end of elements.
888 * @access private
889 * @see getDataInit()
890 */
891 public function getDataNext(&$res) {
892 if (is_array($this->data)) {
893 if ($res < 0) {
894 $row = FALSE;
895 } else {
896 list(, $row) = each($this->dataLookup[$res][$this->subLevelID]);
897 }
898 return $row;
899 } else {
900 while ($row = @$this->getDatabaseConnection()->sql_fetch_assoc($res)) {
901 BackendUtility::workspaceOL($this->table, $row, $this->BE_USER->workspace, TRUE);
902 if (is_array($row)) {
903 break;
904 }
905 }
906 return $row;
907 }
908 }
909
910 /**
911 * Getting the tree data: frees data handle
912 *
913 * @param mixed $res Data handle
914 * @return void
915 * @access private
916 */
917 public function getDataFree(&$res) {
918 if (!is_array($this->data)) {
919 $this->getDatabaseConnection()->sql_free_result($res);
920 }
921 }
922
923 /**
924 * Used to initialize class with an array to browse.
925 * The array inputted will be traversed and an internal index for lookup is created.
926 * The keys of the input array are perceived as "uid"s of records which means that keys GLOBALLY must be unique like uids are.
927 * "uid" and "pid" "fakefields" are also set in each record.
928 * All other fields are optional.
929 *
930 * @param array $dataArr The input array, see examples below in this script.
931 * @param bool $traverse Internal, for recursion.
932 * @param int $pid Internal, for recursion.
933 * @return void
934 */
935 public function setDataFromArray(&$dataArr, $traverse = FALSE, $pid = 0) {
936 if (!$traverse) {
937 $this->data = &$dataArr;
938 $this->dataLookup = array();
939 // Add root
940 $this->dataLookup[0][$this->subLevelID] = &$dataArr;
941 }
942 foreach ($dataArr as $uid => $val) {
943 $dataArr[$uid]['uid'] = $uid;
944 $dataArr[$uid]['pid'] = $pid;
945 // Gives quick access to id's
946 $this->dataLookup[$uid] = &$dataArr[$uid];
947 if (is_array($val[$this->subLevelID])) {
948 $this->setDataFromArray($dataArr[$uid][$this->subLevelID], TRUE, $uid);
949 }
950 }
951 }
952
953 /**
954 * Sets the internal data arrays
955 *
956 * @param array $treeArr Content for $this->data
957 * @param array $treeLookupArr Content for $this->dataLookup
958 * @return void
959 */
960 public function setDataFromTreeArray(&$treeArr, &$treeLookupArr) {
961 $this->data = &$treeArr;
962 $this->dataLookup = &$treeLookupArr;
963 }
964
965 /**
966 * @return LanguageService
967 */
968 protected function getLanguageService() {
969 return $GLOBALS['LANG'];
970 }
971
972 /**
973 * @return BackendUserAuthentication
974 */
975 protected function getBackendUser() {
976 return $GLOBALS['BE_USER'];
977 }
978
979 /**
980 * @return DatabaseConnection
981 */
982 protected function getDatabaseConnection() {
983 return $GLOBALS['TYPO3_DB'];
984 }
985
986 }