AbstractTreeView.php 27.7 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Backend\Tree\View;

4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
Christian Kuhn's avatar
Christian Kuhn committed
16

Nicole Cordes's avatar
Nicole Cordes committed
17
18
19
20
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Backend\Utility\IconUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;

21
22
23
24
25
26
27
28
/**
 * Base class for creating a browsable array/page/folder tree in HTML
 */
abstract class AbstractTreeView {

	// EXTERNAL, static:
	// If set, the first element in the tree is always expanded.
	/**
29
	 * @var int
30
31
32
33
34
	 */
	public $expandFirst = 0;

	// If set, then ALL items will be expanded, regardless of stored settings.
	/**
35
	 * @var int
36
37
38
39
40
	 */
	public $expandAll = 0;

	// Holds the current script to reload to.
	/**
41
	 * @var string
42
43
44
45
46
	 */
	public $thisScript = '';

	// Which HTML attribute to use: alt/title. See init().
	/**
47
	 * @var string
48
49
50
51
52
53
	 */
	public $titleAttrib = 'title';

	// If TRUE, no context menu is rendered on icons. If set to "titlelink" the
	// icon is linked as the title is.
	/**
54
	 * @var bool
55
56
57
58
59
	 */
	public $ext_IconMode = FALSE;

	// If set, the id of the mounts will be added to the internal ids array
	/**
60
	 * @var int
61
62
63
64
65
	 */
	public $addSelfId = 0;

	// Used if the tree is made of records (not folders for ex.)
	/**
66
	 * @var string
67
68
69
70
71
72
73
	 */
	public $title = 'no title';

	// If TRUE, a default title attribute showing the UID of the record is shown.
	// This cannot be enabled by default because it will destroy many applications
	// where another title attribute is in fact applied later.
	/**
74
	 * @var bool
75
76
77
78
79
80
81
82
83
84
85
86
	 */
	public $showDefaultTitleAttribute = FALSE;

	/**
	 * Needs to be initialized with $GLOBALS['BE_USER']
	 * Done by default in init()
	 *
	 * @var \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
	 */
	public $BE_USER = '';

	/**
87
	 * Needs to be initialized with e.g. $GLOBALS['BE_USER']->returnWebmounts()
88
89
90
91
92
	 * Default setting in init() is 0 => 0
	 * The keys are mount-ids (can be anything basically) and the
	 * values are the ID of the root element (COULD be zero or anything else.
	 * For pages that would be the uid of the page, zero for the pagetree root.)
	 *
93
	 * @var string
94
95
96
97
98
99
100
	 */
	public $MOUNTS = '';

	/**
	 * Database table to get the tree data from.
	 * Leave blank if data comes from an array.
	 *
101
	 * @var string
102
103
104
105
106
107
	 */
	public $table = '';

	/**
	 * Defines the field of $table which is the parent id field (like pid for table pages).
	 *
108
	 * @var string
109
110
111
112
113
114
115
116
	 */
	public $parentField = 'pid';

	/**
	 * WHERE clause used for selecting records for the tree. Is set by function init.
	 * Only makes sense when $this->table is set.
	 *
	 * @see init()
117
	 * @var string
118
119
120
121
122
123
124
125
	 */
	public $clause = '';

	/**
	 * Field for ORDER BY. Is set by function init.
	 * Only makes sense when $this->table is set.
	 *
	 * @see init()
126
	 * @var string
127
128
129
130
131
132
133
134
	 */
	public $orderByFields = '';

	/**
	 * Default set of fields selected from the tree table.
	 * 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)
	 *
	 * @see addField()
135
	 * @var array
136
	 */
137
	public $fieldArray = array('uid', 'pid', 'title');
138
139
140
141
142

	/**
	 * List of other fields which are ALLOWED to set (here, based on the "pages" table!)
	 *
	 * @see addField()
143
	 * @var array
144
145
146
147
148
149
150
151
152
153
	 */
	public $defaultList = 'uid,pid,tstamp,sorting,deleted,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,crdate,cruser_id';

	/**
	 * Unique name for the tree.
	 * Used as key for storing the tree into the BE users settings.
	 * Used as key to pass parameters in links.
	 * MUST NOT contain underscore chars.
	 * etc.
	 *
154
	 * @var string
155
156
157
158
159
160
161
162
163
	 */
	public $treeName = '';

	/**
	 * A prefix for table cell id's which will be wrapped around an item.
	 * Can be used for highlighting by JavaScript.
	 * Needs to be unique if multiple trees are on one HTML page.
	 *
	 * @see printTree()
164
	 * @var string
165
166
167
168
169
170
	 */
	public $domIdPrefix = 'row';

	/**
	 * Back path for icons
	 *
171
	 * @var string
172
173
174
175
176
177
178
	 */
	public $backPath;

	/**
	 * If TRUE, HTML code is also accumulated in ->tree array during rendering of the tree.
	 * If 2, then also the icon prefix code (depthData) is stored
	 *
179
	 * @var int
180
181
182
183
184
185
	 */
	public $makeHTML = 1;

	/**
	 * If TRUE, records as selected will be stored internally in the ->recs array
	 *
186
	 * @var int
187
188
189
190
191
192
193
	 */
	public $setRecs = 0;

	/**
	 * Sets the associative array key which identifies a new sublevel if arrays are used for trees.
	 * This value has formerly been "subLevel" and "--sublevel--"
	 *
194
	 * @var string
195
196
197
198
199
200
201
202
203
	 */
	public $subLevelID = '_SUB_LEVEL';

	// *********
	// Internal
	// *********
	// For record trees:
	// one-dim array of the uid's selected.
	/**
204
	 * @var array
205
206
207
208
209
	 */
	public $ids = array();

	// The hierarchy of element uids
	/**
210
	 * @var array
211
212
213
214
215
	 */
	public $ids_hierarchy = array();

	// The hierarchy of versioned element uids
	/**
216
	 * @var array
217
218
219
220
221
	 */
	public $orig_ids_hierarchy = array();

	// Temporary, internal array
	/**
222
	 * @var array
223
224
225
226
227
228
	 */
	public $buffer_idH = array();

	// For FOLDER trees:
	// Special UIDs for folders (integer-hashes of paths)
	/**
229
	 * @var array
230
231
232
233
234
235
	 */
	public $specUIDmap = array();

	// For arrays:
	// Holds the input data array
	/**
236
	 * @var bool
237
238
239
240
241
	 */
	public $data = FALSE;

	// Holds an index with references to the data array.
	/**
242
	 * @var bool
243
244
245
246
247
248
	 */
	public $dataLookup = FALSE;

	// For both types
	// Tree is accumulated in this variable
	/**
249
	 * @var array
250
251
252
253
254
	 */
	public $tree = array();

	// Holds (session stored) information about which items in the tree are unfolded and which are not.
	/**
255
	 * @var array
256
257
258
259
260
	 */
	public $stored = array();

	// Points to the current mountpoint key
	/**
261
	 * @var int
262
263
264
265
266
	 */
	public $bank = 0;

	// Accumulates the displayed records.
	/**
267
	 * @var array
268
269
270
	 */
	public $recs = array();

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
	/**
	 * Sets the script url depending on being a module or script request
	 */
	protected function determineScriptUrl() {
		if ($moduleName = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('M')) {
			$this->thisScript = \TYPO3\CMS\Backend\Utility\BackendUtility::getModuleUrl($moduleName);
		} else {
			$this->thisScript = \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('SCRIPT_NAME');
		}
	}

	/**
	 * @return string
	 */
	protected function getThisScript() {
		return strpos($this->thisScript, '?') === FALSE ? $this->thisScript . '?' : $this->thisScript . '&';
	}

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
	/**
	 * Initialize the tree class. Needs to be overwritten
	 * Will set ->fieldsArray, ->backPath and ->clause
	 *
	 * @param string Record WHERE clause
	 * @param string Record ORDER BY field
	 * @return void
	 */
	public function init($clause = '', $orderByFields = '') {
		// Setting BE_USER by default
		$this->BE_USER = $GLOBALS['BE_USER'];
		// Setting backpath.
		$this->backPath = $GLOBALS['BACK_PATH'];
		// Setting clause
		if ($clause) {
			$this->clause = $clause;
		}
		if ($orderByFields) {
			$this->orderByFields = $orderByFields;
		}
		if (!is_array($this->MOUNTS)) {
			// Dummy
			$this->MOUNTS = array(0 => 0);
		}
Thomas Schlumberger's avatar
Thomas Schlumberger committed
313
314
		// Sets the tree name which is used to identify the tree, used for JavaScript and other things
		$this->treeName = str_replace('_', '', $this->treeName ?: $this->table);
315
316
317
318
319
320
321
322
323
		// Setting this to FALSE disables the use of array-trees by default
		$this->data = FALSE;
		$this->dataLookup = FALSE;
	}

	/**
	 * Adds a fieldname to the internal array ->fieldArray
	 *
	 * @param string $field Field name to
324
	 * @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
325
326
327
	 * @return void
	 */
	public function addField($field, $noCheck = 0) {
Nicole Cordes's avatar
Nicole Cordes committed
328
		if ($noCheck || is_array($GLOBALS['TCA'][$this->table]['columns'][$field]) || GeneralUtility::inList($this->defaultList, $field)) {
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
			$this->fieldArray[] = $field;
		}
	}

	/**
	 * Resets the tree, recs, ids, ids_hierarchy and orig_ids_hierarchy internal variables. Use it if you need it.
	 *
	 * @return void
	 */
	public function reset() {
		$this->tree = array();
		$this->recs = array();
		$this->ids = array();
		$this->ids_hierarchy = array();
		$this->orig_ids_hierarchy = array();
	}

	/*******************************************
	 *
	 * output
	 *
	 *******************************************/
	/**
	 * Will create and return the HTML code for a browsable tree
	 * Is based on the mounts found in the internal array ->MOUNTS (set in the constructor)
	 *
	 * @return string HTML code for the browsable tree
	 */
	public function getBrowsableTree() {
		// Get stored tree structure AND updating it if needed according to incoming PM GET var.
		$this->initializePositionSaving();
		// Init done:
		$treeArr = array();
		// Traverse mounts:
		foreach ($this->MOUNTS as $idx => $uid) {
			// Set first:
			$this->bank = $idx;
			$isOpen = $this->stored[$idx][$uid] || $this->expandFirst;
			// Save ids while resetting everything else.
			$curIds = $this->ids;
			$this->reset();
			$this->ids = $curIds;
			// Set PM icon for root of mount:
372
			$cmd = $this->bank . '_' . ($isOpen ? '0_' : '1_') . $uid . '_' . $this->treeName;
373

374
			$firstHtml = $this->PM_ATagWrap('', $cmd, '', $isOpen);
375
376
377
378
379
380
381
382
383
384
385
386
387
			// Preparing rootRec for the mount
			if ($uid) {
				$rootRec = $this->getRecord($uid);
				$firstHtml .= $this->getIcon($rootRec);
			} else {
				// Artificial record for the tree root, id=0
				$rootRec = $this->getRootRecord($uid);
				$firstHtml .= $this->getRootIcon($rootRec);
			}
			if (is_array($rootRec)) {
				// In case it was swapped inside getRecord due to workspaces.
				$uid = $rootRec['uid'];
				// Add the root of the mount to ->tree
388
				$this->tree[] = array('HTML' => $firstHtml, 'row' => $rootRec, 'hasSub' => $isOpen, 'bank' => $this->bank);
389
390
				// If the mount is expanded, go down:
				if ($isOpen) {
Benni Mack's avatar
Benni Mack committed
391
					$depthData = '<span class="treeline-icon treeline-icon-clear"></span>';
392
393
394
					if ($this->addSelfId) {
						$this->ids[] = $uid;
					}
Benni Mack's avatar
Benni Mack committed
395
					$this->getTree($uid, 999, $depthData);
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
				}
				// Add tree:
				$treeArr = array_merge($treeArr, $this->tree);
			}
		}
		return $this->printTree($treeArr);
	}

	/**
	 * Compiles the HTML code for displaying the structure found inside the ->tree array
	 *
	 * @param array $treeArr "tree-array" - if blank string, the internal ->tree array is used.
	 * @return string The HTML code for the tree
	 */
	public function printTree($treeArr = '') {
411
		$titleLen = (int)$this->BE_USER->uc['titleLen'];
412
413
414
415
		if (!is_array($treeArr)) {
			$treeArr = $this->tree;
		}
		$out = '';
416
417
		$closeDepth = array();
		foreach ($treeArr as $treeItem) {
Benni Mack's avatar
Benni Mack committed
418
			$classAttr = '';
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
			if ($treeItem['isFirst']) {
				$out .= '<ul class="list-tree">';
			}

			// Add CSS classes to the list item
			if ($treeItem['hasSub']) {
				$classAttr .= ' list-tree-control-open';
			}

			$idAttr = htmlspecialchars($this->domIdPrefix . $this->getId($treeItem['row']) . '_' . $treeItem['bank']);
			$out .= '<li id="' . $idAttr . '"' . ($classAttr ? ' class="' . trim($classAttr) . '"' : '') . '><span class="list-tree-group">' . $treeItem['HTML'] . $this->wrapTitle($this->getTitleStr($treeItem['row'], $titleLen), $treeItem['row'], $treeItem['bank']) . '</span>';

			if (!$treeItem['hasSub']) {
				$out .= '</li>';
			}

			// We have to remember if this is the last one
			// on level X so the last child on level X+1 closes the <ul>-tag
			if ($treeItem['isLast']) {
				$closeDepth[$treeItem['invertedDepth']] = 1;
			}
			// If this is the last one and does not have subitems, we need to close
			// the tree as long as the upper levels have last items too
			if ($treeItem['isLast'] && !$treeItem['hasSub']) {
				for ($i = $treeItem['invertedDepth']; $closeDepth[$i] == 1; $i++) {
					$closeDepth[$i] = 0;
					$out .= '</ul></li>';
				}
			}
448
		}
Benni Mack's avatar
Benni Mack committed
449
		$out = '<ul class="list-tree list-tree-root">' . $out . '</ul>';
450
451
452
453
454
455
456
457
458
459
460
461
		return $out;
	}

	/*******************************************
	 *
	 * rendering parts
	 *
	 *******************************************/
	/**
	 * Generate the plus/minus icon for the browsable tree.
	 *
	 * @param array $row Record for the entry
462
463
464
	 * @param int $a The current entry number
	 * @param int $c The total number of entries. If equal to $a, a "bottom" element is returned.
	 * @param int $nextCount The number of sub-elements to the current element.
465
	 * @param bool $isOpen The element was expanded to render subelements if this flag is set.
466
467
	 * @return string Image tag with the plus/minus icon.
	 * @access private
Christian Kuhn's avatar
Christian Kuhn committed
468
	 * @see \TYPO3\CMS\Backend\Tree\View\PageTreeView::PMicon()
469
	 */
470
	public function PMicon($row, $a, $c, $nextCount, $isOpen) {
471
		if ($nextCount) {
472
			$cmd = $this->bank . '_' . ($isOpen ? '0_' : '1_') . $row['uid'] . '_' . $this->treeName;
473
			$bMark = $this->bank . '_' . $row['uid'];
474
475
476
			return $this->PM_ATagWrap('', $cmd, $bMark, $isOpen);
		} else {
			return '';
477
478
479
480
481
482
483
484
		}
	}

	/**
	 * Wrap the plus/minus icon in a link
	 *
	 * @param string $icon HTML string to wrap, probably an image tag.
	 * @param string $cmd Command for 'PM' get var
485
	 * @param bool $bMark If set, the link will have an anchor point (=$bMark) and a name attribute (=$bMark)
486
	 * @param bool $isOpen
487
488
489
	 * @return string Link-wrapped input string
	 * @access private
	 */
490
	public function PM_ATagWrap($icon, $cmd, $bMark = '', $isOpen = FALSE) {
491
492
493
		if ($this->thisScript) {
			if ($bMark) {
				$anchor = '#' . $bMark;
494
				$name = ' name="' . $bMark . '"';
495
			}
496
			$aUrl = $this->getThisScript() . 'PM=' . $cmd . $anchor;
497
			return '<a class="list-tree-control ' . ($isOpen ? 'list-tree-control-open' : 'list-tree-control-closed') . ' href="' . htmlspecialchars($aUrl) . '"' . $name . '><i class="fa"></i></a>';
498
499
500
501
502
503
504
505
506
507
		} else {
			return $icon;
		}
	}

	/**
	 * Wrapping $title in a-tags.
	 *
	 * @param string $title Title string
	 * @param string $row Item record
508
	 * @param int $bank Bank pointer (which mount point number)
509
510
511
512
	 * @return string
	 * @access private
	 */
	public function wrapTitle($title, $row, $bank = 0) {
513
		$aOnClick = 'return jumpTo(' . GeneralUtility::quoteJSvalue($this->getJumpToParam($row)) . ',this,' . GeneralUtility::quoteJSvalue($this->domIdPrefix . $this->getId($row)) . ',' . $bank . ');';
514
		return '<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . $title . '</a>';
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
	}

	/**
	 * Wrapping the image tag, $icon, for the row, $row (except for mount points)
	 *
	 * @param string $icon The image tag for the icon
	 * @param array $row The row for the current element
	 * @return string The processed icon input value.
	 * @access private
	 */
	public function wrapIcon($icon, $row) {
		return $icon;
	}

	/**
	 * Adds attributes to image tag.
	 *
	 * @param string $icon Icon image tag
	 * @param string $attr Attributes to add, eg. ' border="0"'
	 * @return string Image tag, modified with $attr attributes added.
	 */
	public function addTagAttributes($icon, $attr) {
537
		return preg_replace('/ ?\\/?>$/', '', $icon) . ' ' . $attr . ' />';
538
539
540
541
542
543
544
545
546
547
548
549
	}

	/**
	 * Adds a red "+" to the input string, $str, if the field "php_tree_stop" in the $row (pages) is set
	 *
	 * @param string $str Input string, like a page title for the tree
	 * @param array $row record row with "php_tree_stop" field
	 * @return string Modified string
	 * @access private
	 */
	public function wrapStop($str, $row) {
		if ($row['php_tree_stop']) {
550
			$str .= '<a href="' . htmlspecialchars(GeneralUtility::linkThisScript(array('setTempDBmount' => $row['uid']))) . '" class="text-danger">+</a> ';
551
552
553
554
555
556
557
558
559
560
561
562
563
564
		}
		return $str;
	}

	/*******************************************
	 *
	 * tree handling
	 *
	 *******************************************/
	/**
	 * Returns TRUE/FALSE if the next level for $id should be expanded - based on
	 * data in $this->stored[][] and ->expandAll flag.
	 * Extending parent function
	 *
565
	 * @param int $id Record id/key
566
	 * @return bool
567
	 * @access private
Christian Kuhn's avatar
Christian Kuhn committed
568
	 * @see \TYPO3\CMS\Backend\Tree\View\PageTreeView::expandNext()
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
	 */
	public function expandNext($id) {
		return $this->stored[$this->bank][$id] || $this->expandAll ? 1 : 0;
	}

	/**
	 * Get stored tree structure AND updating it if needed according to incoming PM GET var.
	 *
	 * @return void
	 * @access private
	 */
	public function initializePositionSaving() {
		// Get stored tree structure:
		$this->stored = unserialize($this->BE_USER->uc['browseTrees'][$this->treeName]);
		// PM action
		// (If an plus/minus icon has been clicked, the PM GET var is sent and we
		// must update the stored positions in the tree):
		// 0: mount key, 1: set/clear boolean, 2: item ID (cannot contain "_"), 3: treeName
Nicole Cordes's avatar
Nicole Cordes committed
587
		$PM = explode('_', GeneralUtility::_GP('PM'));
588
		if (count($PM) === 4 && $PM[3] == $this->treeName) {
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
			if (isset($this->MOUNTS[$PM[0]])) {
				// set
				if ($PM[1]) {
					$this->stored[$PM[0]][$PM[2]] = 1;
					$this->savePosition();
				} else {
					unset($this->stored[$PM[0]][$PM[2]]);
					$this->savePosition();
				}
			}
		}
	}

	/**
	 * Saves the content of ->stored (keeps track of expanded positions in the tree)
	 * $this->treeName will be used as key for BE_USER->uc[] to store it in
	 *
	 * @return void
	 * @access private
	 */
	public function savePosition() {
		$this->BE_USER->uc['browseTrees'][$this->treeName] = serialize($this->stored);
		$this->BE_USER->writeUC();
	}

	/******************************
	 *
	 * Functions that might be overwritten by extended classes
	 *
	 ********************************/
	/**
	 * Returns the root icon for a tree/mountpoint (defaults to the globe)
	 *
	 * @param array $rec Record for root.
	 * @return string Icon image tag.
	 */
	public function getRootIcon($rec) {
Nicole Cordes's avatar
Nicole Cordes committed
626
		return $this->wrapIcon(IconUtility::getSpriteIcon('apps-pagetree-root'), $rec);
627
628
629
630
631
632
633
634
635
	}

	/**
	 * Get icon for the row.
	 *
	 * @param array $row Item row.
	 * @return string Image tag.
	 */
	public function getIcon($row) {
Benni Mack's avatar
Benni Mack committed
636
637
638
		if (is_int($row)) {
			$row = BackendUtility::getRecord($this->table, $row);
		}
Thomas Schlumberger's avatar
Thomas Schlumberger committed
639
		$icon = IconUtility::getSpriteIconForRecord($this->table, $row, array(
Benni Mack's avatar
Benni Mack committed
640
			'title' => $this->showDefaultTitleAttribute ? 'UID: ' . $row['uid'] : $this->getTitleAttrib($row)
Thomas Schlumberger's avatar
Thomas Schlumberger committed
641
		));
642
643
644
645
646
647
648
649
		return $this->wrapIcon($icon, $row);
	}

	/**
	 * Returns the title for the input record. If blank, a "no title" label (localized) will be returned.
	 * Do NOT htmlspecialchar the string from this function - has already been done.
	 *
	 * @param array $row The input row array (where the key "title" is used for the title)
650
	 * @param int $titleLen Title length (30)
651
652
653
	 * @return string The title.
	 */
	public function getTitleStr($row, $titleLen = 30) {
654
655
		$title = htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['title'], $titleLen));
		$title = trim($row['title']) === '' ? '<em>[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', TRUE) . ']</em>' : $title;
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
		return $title;
	}

	/**
	 * Returns the value for the image "title" attribute
	 *
	 * @param array $row The input row array (where the key "title" is used for the title)
	 * @return string The attribute value (is htmlspecialchared() already)
	 * @see wrapIcon()
	 */
	public function getTitleAttrib($row) {
		return htmlspecialchars($row['title']);
	}

	/**
	 * Returns the id from the record (typ. uid)
	 *
	 * @param array $row Record array
674
	 * @return int The "uid" field value.
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
	 */
	public function getId($row) {
		return $row['uid'];
	}

	/**
	 * Returns jump-url parameter value.
	 *
	 * @param array $row The record array.
	 * @return string The jump-url parameter.
	 */
	public function getJumpToParam($row) {
		return $this->getId($row);
	}

	/********************************
	 *
	 * tree data buidling
	 *
	 ********************************/
	/**
	 * Fetches the data for the tree
	 *
698
699
	 * @param int $uid item id for which to select subitems (parent id)
	 * @param int $depth Max depth (recursivity limit)
700
701
702
	 * @param string $depthData HTML-code prefix for recursive calls.
	 * @param string $blankLineCode ? (internal)
	 * @param string $subCSSclass CSS class to use for <td> sub-elements
703
	 * @return int The count of items on the level
704
705
706
707
708
	 */
	public function getTree($uid, $depth = 999, $depthData = '', $blankLineCode = '', $subCSSclass = '') {
		// Buffer for id hierarchy is reset:
		$this->buffer_idH = array();
		// Init vars
709
		$depth = (int)$depth;
710
711
		$HTML = '';
		$a = 0;
Benni Mack's avatar
Benni Mack committed
712
		$res = $this->getDataInit($uid);
713
714
715
716
		$c = $this->getDataCount($res);
		$crazyRecursionLimiter = 999;
		$idH = array();
		// Traverse the records:
Benni Mack's avatar
Benni Mack committed
717
		while ($crazyRecursionLimiter > 0 && ($row = $this->getDataNext($res, ''))) {
718
719
			$pageUid = ($this->table === 'pages') ? $row['uid'] : $row['pid'];
			if (!$GLOBALS['BE_USER']->isInWebMount($pageUid)) {
720
721
722
723
				// Current record is not within web mount => skip it
				continue;
			}

724
725
726
727
			$a++;
			$crazyRecursionLimiter--;
			$newID = $row['uid'];
			if ($newID == 0) {
728
				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);
729
730
731
732
733
734
735
736
737
738
739
740
741
			}
			// Reserve space.
			$this->tree[] = array();
			end($this->tree);
			// Get the key for this space
			$treeKey = key($this->tree);
			// If records should be accumulated, do so
			if ($this->setRecs) {
				$this->recs[$row['uid']] = $row;
			}
			// Accumulate the id of the element in the internal arrays
			$this->ids[] = ($idH[$row['uid']]['uid'] = $row['uid']);
			$this->ids_hierarchy[$depth][] = $row['uid'];
742
			$this->orig_ids_hierarchy[$depth][] = $row['_ORIG_uid'] ?: $row['uid'];
743

744
			// Make a recursive call to the next level
Benni Mack's avatar
Benni Mack committed
745
			$nextLevelDepthData = $depthData . '<span class="treeline-icon treeline-icon-' . ($a === $c ? 'clear' : 'line') .'"></span>';
746
747
			$hasSub = $this->expandNext($newID) && !$row['php_tree_stop'];
			if ($depth > 1 && $hasSub) {
Benni Mack's avatar
Benni Mack committed
748
				$nextCount = $this->getTree($newID, $depth - 1, $nextLevelDepthData);
749
				if (!empty($this->buffer_idH)) {
750
751
752
					$idH[$row['uid']]['subrow'] = $this->buffer_idH;
				}
				// Set "did expand" flag
753
				$isOpen = 1;
754
755
756
			} else {
				$nextCount = $this->getCount($newID);
				// Clear "did expand" flag
757
				$isOpen = 0;
758
759
760
			}
			// Set HTML-icons, if any:
			if ($this->makeHTML) {
761
				$HTML = $this->PMicon($row, $a, $c, $nextCount, $isOpen) . $this->wrapStop($this->getIcon($row), $row);
762
763
764
765
766
767
			}
			// Finally, add the row/HTML content to the ->tree array in the reserved key.
			$this->tree[$treeKey] = array(
				'row' => $row,
				'HTML' => $HTML,
				'invertedDepth' => $depth,
Benni Mack's avatar
Benni Mack committed
768
				'depthData' => $depthData,
769
770
771
772
				'bank' => $this->bank,
				'hasSub' => $nextCount && $hasSub,
				'isFirst' => $a === 1,
				'isLast' => $a === $c,
773
774
			);
		}
775

776
777
778
779
780
781
782
783
784
785
786
787
788
789
		$this->getDataFree($res);
		$this->buffer_idH = $idH;
		return $c;
	}

	/********************************
	 *
	 * Data handling
	 * Works with records and arrays
	 *
	 ********************************/
	/**
	 * Returns the number of records having the parent id, $uid
	 *
790
	 * @param int $uid Id to count subitems for
791
	 * @return int
792
793
794
795
796
797
798
	 * @access private
	 */
	public function getCount($uid) {
		if (is_array($this->data)) {
			$res = $this->getDataInit($uid);
			return $this->getDataCount($res);
		} else {
Nicole Cordes's avatar
Nicole Cordes committed
799
			return $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', $this->table, $this->parentField . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($uid, $this->table) . BackendUtility::deleteClause($this->table) . BackendUtility::versioningPlaceholderClause($this->table) . $this->clause);
800
801
802
803
804
805
		}
	}

	/**
	 * Returns root record for uid (<=0)
	 *
806
	 * @param int $uid uid, <= 0 (normally, this does not matter)
807
808
809
810
811
812
813
814
815
816
817
	 * @return array Array with title/uid keys with values of $this->title/0 (zero)
	 */
	public function getRootRecord($uid) {
		return array('title' => $this->title, 'uid' => 0);
	}

	/**
	 * Returns the record for a uid.
	 * For tables: Looks up the record in the database.
	 * For arrays: Returns the fake record for uid id.
	 *
818
	 * @param int $uid UID to look up
819
820
821
822
823
824
	 * @return array The record
	 */
	public function getRecord($uid) {
		if (is_array($this->data)) {
			return $this->dataLookup[$uid];
		} else {
Nicole Cordes's avatar
Nicole Cordes committed
825
			return BackendUtility::getRecordWSOL($this->table, $uid);
826
827
828
829
830
831
832
833
		}
	}

	/**
	 * Getting the tree data: Selecting/Initializing data pointer to items for a certain parent id.
	 * For tables: This will make a database query to select all children to "parent"
	 * For arrays: This will return key to the ->dataLookup array
	 *
834
	 * @param int $parentId parent item id
835
836
837
838
839
840
841
842
843
844
845
846
847
	 * @param string $subCSSclass Class for sub-elements.
	 * @return mixed Data handle (Tables: An sql-resource, arrays: A parentId integer. -1 is returned if there were NO subLevel.)
	 * @access private
	 */
	public function getDataInit($parentId, $subCSSclass = '') {
		if (is_array($this->data)) {
			if (!is_array($this->dataLookup[$parentId][$this->subLevelID])) {
				$parentId = -1;
			} else {
				reset($this->dataLookup[$parentId][$this->subLevelID]);
			}
			return $parentId;
		} else {
848
			return $GLOBALS['TYPO3_DB']->exec_SELECTquery(implode(',', $this->fieldArray), $this->table, $this->parentField . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($parentId, $this->table) . BackendUtility::deleteClause($this->table) . BackendUtility::versioningPlaceholderClause($this->table) . $this->clause, '', $this->orderByFields);
849
850
851
852
853
854
855
		}
	}

	/**
	 * Getting the tree data: Counting elements in resource
	 *
	 * @param mixed $res Data handle
856
	 * @return int number of items
857
858
859
860
861
862
863
	 * @access private
	 * @see getDataInit()
	 */
	public function getDataCount(&$res) {
		if (is_array($this->data)) {
			return count($this->dataLookup[$res][$this->subLevelID]);
		} else {
864
			return $GLOBALS['TYPO3_DB']->sql_num_rows($res);
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
		}
	}

	/**
	 * Getting the tree data: next entry
	 *
	 * @param mixed $res Data handle
	 * @param string $subCSSclass CSS class for sub elements (workspace related)
	 * @return array item data array OR FALSE if end of elements.
	 * @access private
	 * @see getDataInit()
	 */
	public function getDataNext(&$res, $subCSSclass = '') {
		if (is_array($this->data)) {
			if ($res < 0) {
				$row = FALSE;
			} else {
				list(, $row) = each($this->dataLookup[$res][$this->subLevelID]);
			}
			return $row;
		} else {
			while ($row = @$GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
Nicole Cordes's avatar
Nicole Cordes committed
887
				BackendUtility::workspaceOL($this->table, $row, $this->BE_USER->workspace, TRUE);
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
				if (is_array($row)) {
					break;
				}
			}
			return $row;
		}
	}

	/**
	 * Getting the tree data: frees data handle
	 *
	 * @param mixed $res Data handle
	 * @return void
	 * @access private
	 */
	public function getDataFree(&$res) {
		if (!is_array($this->data)) {
			$GLOBALS['TYPO3_DB']->sql_free_result($res);
		}
	}

	/**
	 * Used to initialize class with an array to browse.
	 * The array inputted will be traversed and an internal index for lookup is created.
	 * The keys of the input array are perceived as "uid"s of records which means that keys GLOBALLY must be unique like uids are.
	 * "uid" and "pid" "fakefields" are also set in each record.
	 * All other fields are optional.
	 *
	 * @param array $dataArr The input array, see examples below in this script.
917
	 * @param bool $traverse Internal, for recursion.
918
	 * @param int $pid Internal, for recursion.
919
920
921
922
	 * @return void
	 */
	public function setDataFromArray(&$dataArr, $traverse = FALSE, $pid = 0) {
		if (!$traverse) {
923
			$this->data = &$dataArr;
924
925
			$this->dataLookup = array();
			// Add root
926
			$this->dataLookup[0][$this->subLevelID] = &$dataArr;
927
928
929
930
931
		}
		foreach ($dataArr as $uid => $val) {
			$dataArr[$uid]['uid'] = $uid;
			$dataArr[$uid]['pid'] = $pid;
			// Gives quick access to id's
932
			$this->dataLookup[$uid] = &$dataArr[$uid];
933
934
935
936
937
938
939
940
941
942
943
944
945
946
			if (is_array($val[$this->subLevelID])) {
				$this->setDataFromArray($dataArr[$uid][$this->subLevelID], TRUE, $uid);
			}
		}
	}

	/**
	 * Sets the internal data arrays
	 *
	 * @param array $treeArr Content for $this->data
	 * @param array $treeLookupArr Content for $this->dataLookup
	 * @return void
	 */
	public function setDataFromTreeArray(&$treeArr, &$treeLookupArr) {
947
948
		$this->data = &$treeArr;
		$this->dataLookup = &$treeLookupArr;
949
950
951
	}

}