01337f7e252f6fbd76b00996fdadd3892420b537
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / TypoScript / ExtendedTemplateService.php
1 <?php
2 namespace TYPO3\CMS\Core\TypoScript;
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\Template\DocumentTemplate;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Core\Database\ConnectionPool;
20 use TYPO3\CMS\Core\Database\Query\QueryBuilder;
21 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
22 use TYPO3\CMS\Core\Exception;
23 use TYPO3\CMS\Core\Imaging\Icon;
24 use TYPO3\CMS\Core\Imaging\IconFactory;
25 use TYPO3\CMS\Core\Utility\GeneralUtility;
26 use TYPO3\CMS\Core\Utility\MathUtility;
27 use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
28 use TYPO3\CMS\Lang\LanguageService;
29
30 /**
31 * TSParser extension class to TemplateService
32 * Contains functions for the TS module in TYPO3 backend
33 */
34 class ExtendedTemplateService extends TemplateService
35 {
36 /**
37 * This string is used to indicate the point in a template from where the editable constants are listed.
38 * Any vars before this point (if it exists though) is regarded as default values.
39 *
40 * @var string
41 */
42 public $edit_divider = '###MOD_TS:EDITABLE_CONSTANTS###';
43
44 /**
45 * Disabled in backend context
46 *
47 * @var bool
48 */
49 public $tt_track = false;
50
51 /**
52 * @var array
53 */
54 public $categories = [
55 'basic' => [],
56 // Constants of superior importance for the template-layout. This is dimensions, imagefiles and enabling of various features. The most basic constants, which you would almost always want to configure.
57 'menu' => [],
58 // Menu setup. This includes fontfiles, sizes, background images. Depending on the menutype.
59 'content' => [],
60 // All constants related to the display of pagecontent elements
61 'page' => [],
62 // General configuration like metatags, link targets
63 'advanced' => [],
64 // Advanced functions, which are used very seldom.
65 'all' => []
66 ];
67
68 /**
69 * Translated categories
70 *
71 * @var array
72 */
73 protected $categoryLabels = [];
74
75 /**
76 * This will be filled with the available categories of the current template.
77 *
78 * @var array
79 */
80 public $subCategories = [
81 // Standard categories:
82 'enable' => ['Enable features', 'a'],
83 'dims' => ['Dimensions, widths, heights, pixels', 'b'],
84 'file' => ['Files', 'c'],
85 'typo' => ['Typography', 'd'],
86 'color' => ['Colors', 'e'],
87 'links' => ['Links and targets', 'f'],
88 'language' => ['Language specific constants', 'g'],
89 // subcategories based on the default content elements
90 'cheader' => ['Content: \'Header\'', 'ma'],
91 'cheader_g' => ['Content: \'Header\', Graphical', 'ma'],
92 'ctext' => ['Content: \'Text\'', 'mb'],
93 'cimage' => ['Content: \'Image\'', 'md'],
94 'ctextmedia' => ['Content: \'Textmedia\'', 'ml'],
95 'cbullets' => ['Content: \'Bullet list\'', 'me'],
96 'ctable' => ['Content: \'Table\'', 'mf'],
97 'cuploads' => ['Content: \'Filelinks\'', 'mg'],
98 'cmultimedia' => ['Content: \'Multimedia\'', 'mh'],
99 'cmedia' => ['Content: \'Media\'', 'mr'],
100 'cmailform' => ['Content: \'Form\'', 'mi'],
101 'csearch' => ['Content: \'Search\'', 'mj'],
102 'clogin' => ['Content: \'Login\'', 'mk'],
103 'cmenu' => ['Content: \'Menu/Sitemap\'', 'mm'],
104 'cshortcut' => ['Content: \'Insert records\'', 'mn'],
105 'clist' => ['Content: \'List of records\'', 'mo'],
106 'chtml' => ['Content: \'HTML\'', 'mq']
107 ];
108
109 /**
110 * Tsconstanteditor
111 *
112 * @var int
113 */
114 public $ext_inBrace = 0;
115
116 /**
117 * Tsbrowser
118 *
119 * @var array
120 */
121 public $tsbrowser_searchKeys = [];
122
123 /**
124 * @var array
125 */
126 public $tsbrowser_depthKeys = [];
127
128 /**
129 * @var string
130 */
131 public $constantMode = '';
132
133 /**
134 * @var string
135 */
136 public $regexMode = '';
137
138 /**
139 * @var string
140 */
141 public $fixedLgd = '';
142
143 /**
144 * @var int
145 */
146 public $ext_lineNumberOffset = 0;
147
148 /**
149 * @var int
150 */
151 public $ext_expandAllNotes = 0;
152
153 /**
154 * @var int
155 */
156 public $ext_noPMicons = 0;
157
158 /**
159 * @var array
160 */
161 public $ext_listOfTemplatesArr = [];
162
163 /**
164 * @var string
165 */
166 public $ext_lineNumberOffset_mode = '';
167
168 /**
169 * Don't change
170 *
171 * @var int
172 */
173 public $ext_dontCheckIssetValues = 0;
174
175 /**
176 * @var int
177 */
178 public $ext_printAll = 0;
179
180 /**
181 * @var string
182 */
183 public $ext_CEformName = 'forms[0]';
184
185 /**
186 * @var bool
187 */
188 public $doNotSortCategoriesBeforeMakingForm = false;
189
190 /**
191 * Ts analyzer
192 *
193 * @var array
194 */
195 public $templateTitles = [];
196
197 /**
198 * @var array|NULL
199 */
200 protected $lnToScript = null;
201
202 /**
203 * @var array
204 */
205 public $clearList_const_temp;
206
207 /**
208 * @var array
209 */
210 public $clearList_setup_temp;
211
212 /**
213 * @var string
214 */
215 public $bType = '';
216
217 /**
218 * @var bool
219 */
220 public $linkObjects = false;
221
222 /**
223 * @var array
224 */
225 public $helpConfig = [];
226
227 /**
228 * @var bool
229 */
230 public $changed = false;
231
232 /**
233 * @var int[]
234 */
235 protected $objReg = [];
236
237 /**
238 * @var array
239 */
240 public $raw = [];
241
242 /**
243 * @var int
244 */
245 public $rawP = 0;
246
247 /**
248 * @var string
249 */
250 public $lastComment = '';
251
252 /**
253 * @var array
254 */
255 protected $inlineJavaScript = [];
256
257 /**
258 * Gets the inline JavaScript.
259 *
260 * @return array
261 */
262 public function getInlineJavaScript()
263 {
264 return $this->inlineJavaScript;
265 }
266
267 /**
268 * Substitute constant
269 *
270 * @param string $all
271 * @return string
272 */
273 public function substituteConstants($all)
274 {
275 return preg_replace_callback('/\\{\\$(.[^}]+)\\}/', [$this, 'substituteConstantsCallBack'], $all);
276 }
277
278 /**
279 * Call back method for preg_replace_callback in substituteConstants
280 *
281 * @param array $matches Regular expression matches
282 * @return string Replacement
283 * @see substituteConstants()
284 */
285 public function substituteConstantsCallBack($matches)
286 {
287 $marker = substr(md5($matches[0]), 0, 6);
288 switch ($this->constantMode) {
289 case 'const':
290 $ret_val = isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? '##' . $marker . '_B##' . $matches[0] . '##' . $marker . '_E##' : $matches[0];
291 break;
292 case 'subst':
293 $ret_val = isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? '##' . $marker . '_B##' . $this->flatSetup[$matches[1]] . '##' . $marker . '_E##' : $matches[0];
294 break;
295 case 'untouched':
296 $ret_val = $matches[0];
297 break;
298 default:
299 $ret_val = isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
300 }
301 return $ret_val;
302 }
303
304 /**
305 * Substitute markers
306 *
307 * @param string $all
308 * @return string
309 */
310 public function substituteCMarkers($all)
311 {
312 switch ($this->constantMode) {
313 case 'const':
314 case 'subst':
315 $all = preg_replace(
316 '/##[a-z0-9]{6}_B##((?:(?!##[a-z0-9]{6}_E##).)+)##[a-z0-9]{6}_E##/',
317 '<strong style="color: green;">$1</strong>',
318 $all
319 );
320 break;
321 default:
322 }
323 return $all;
324 }
325
326 /**
327 * Parse constants with respect to the constant-editor in this module.
328 * In particular comments in the code are registered and the edit_divider is taken into account.
329 *
330 * @return array
331 */
332 public function generateConfig_constants()
333 {
334 // These vars are also set lateron...
335 $this->setup['sitetitle'] = $this->sitetitle;
336 // Parse constants
337 $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
338 // Register comments!
339 $constants->regComments = 1;
340 $constants->setup = $this->mergeConstantsFromPageTSconfig([]);
341 /** @var ConditionMatcher $matchObj */
342 $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
343 // Matches ALL conditions in TypoScript
344 $matchObj->setSimulateMatchResult(true);
345 $c = 0;
346 $cc = count($this->constants);
347 $defaultConstants = [];
348 foreach ($this->constants as $str) {
349 $c++;
350 if ($c == $cc) {
351 if (strstr($str, $this->edit_divider)) {
352 $parts = explode($this->edit_divider, $str, 2);
353 $str = $parts[1];
354 $constants->parse($parts[0], $matchObj);
355 }
356 $this->flatSetup = [];
357 $this->flattenSetup($constants->setup, '');
358 $defaultConstants = $this->flatSetup;
359 }
360 $constants->parse($str, $matchObj);
361 }
362 $this->flatSetup = [];
363 $this->flattenSetup($constants->setup, '');
364 $this->setup['constants'] = $constants->setup;
365 return $this->ext_compareFlatSetups($defaultConstants);
366 }
367
368 /**
369 * @param array $theSetup
370 * @param string $theKey
371 * @return array
372 */
373 public function ext_getSetup($theSetup, $theKey)
374 {
375 $parts = explode('.', $theKey, 2);
376 if ((string)$parts[0] !== '' && is_array($theSetup[$parts[0] . '.'])) {
377 if (trim($parts[1]) !== '') {
378 return $this->ext_getSetup($theSetup[$parts[0] . '.'], trim($parts[1]));
379 } else {
380 return [$theSetup[$parts[0] . '.'], $theSetup[$parts[0]]];
381 }
382 } else {
383 if (trim($theKey) !== '') {
384 return [[], $theSetup[$theKey]];
385 } else {
386 return [$theSetup, ''];
387 }
388 }
389 }
390
391 /**
392 * Get object tree
393 *
394 * @param array $arr
395 * @param string $depth_in
396 * @param string $depthData
397 * @param string $parentType (unused)
398 * @param string $parentValue (unused)
399 * @param string $alphaSort sorts the array keys / tree by alphabet when set to 1
400 * @return array
401 */
402 public function ext_getObjTree($arr, $depth_in, $depthData, $parentType = '', $parentValue = '', $alphaSort = '0')
403 {
404 $HTML = '';
405 if ($alphaSort == '1') {
406 ksort($arr);
407 }
408 $keyArr_num = [];
409 $keyArr_alpha = [];
410 foreach ($arr as $key => $value) {
411 // Don't do anything with comments / linenumber registrations...
412 if (substr($key, -2) !== '..') {
413 $key = preg_replace('/\\.$/', '', $key);
414 if (substr($key, -1) !== '.') {
415 if (MathUtility::canBeInterpretedAsInteger($key)) {
416 $keyArr_num[$key] = $arr[$key];
417 } else {
418 $keyArr_alpha[$key] = $arr[$key];
419 }
420 }
421 }
422 }
423 ksort($keyArr_num);
424 $keyArr = $keyArr_num + $keyArr_alpha;
425 if ($depth_in) {
426 $depth_in = $depth_in . '.';
427 }
428 foreach ($keyArr as $key => $value) {
429 $depth = $depth_in . $key;
430 // This excludes all constants starting with '_' from being shown.
431 if ($this->bType !== 'const' || $depth[0] !== '_') {
432 $goto = substr(md5($depth), 0, 6);
433 $deeper = is_array($arr[$key . '.']) && ($this->tsbrowser_depthKeys[$depth] || $this->ext_expandAllNotes) ? 1 : 0;
434 $PM = is_array($arr[$key . '.']) && !$this->ext_noPMicons ? ($deeper ? 'minus' : 'plus') : 'join';
435 $HTML .= $depthData . '<li>';
436 if ($PM !== 'join') {
437 $urlParameters = [
438 'id' => $GLOBALS['SOBE']->id,
439 'tsbr[' . $depth . ']' => $deeper ? 0 : 1
440 ];
441 if (GeneralUtility::_GP('breakPointLN')) {
442 $urlParameters['breakPointLN'] = GeneralUtility::_GP('breakPointLN');
443 }
444 $aHref = BackendUtility::getModuleUrl('web_ts', $urlParameters) . '#' . $goto;
445 $HTML .= '<a class="list-tree-control' . ($PM === 'minus' ? ' list-tree-control-open' : ' list-tree-control-closed') . '" name="' . $goto . '" href="' . htmlspecialchars($aHref) . '"><i class="fa"></i></a>';
446 }
447 $label = $key;
448 // Read only...
449 if (($depth === 'types' || $depth === 'resources' || $depth === 'sitetitle') && $this->bType === 'setup') {
450 $label = '<span style="color: #666666;">' . $label . '</span>';
451 } else {
452 if ($this->linkObjects) {
453 $urlParameters = [
454 'id' => $GLOBALS['SOBE']->id,
455 'sObj' => $depth
456 ];
457 if (GeneralUtility::_GP('breakPointLN')) {
458 $urlParameters['breakPointLN'] = GeneralUtility::_GP('breakPointLN');
459 }
460 $aHref = BackendUtility::getModuleUrl('web_ts', $urlParameters);
461 if ($this->bType !== 'const') {
462 $ln = is_array($arr[$key . '.ln..']) ? 'Defined in: ' . $this->lineNumberToScript($arr[$key . '.ln..']) : 'N/A';
463 } else {
464 $ln = '';
465 }
466 if ($this->tsbrowser_searchKeys[$depth] & 4) {
467 $label = '<strong class="text-danger">' . $label . '</strong>';
468 }
469 // The key has matched the search string
470 $label = '<a href="' . htmlspecialchars($aHref) . '" title="' . htmlspecialchars($ln) . '">' . $label . '</a>';
471 }
472 }
473 $HTML .= '
474 <span class="list-tree-group">
475 <span class="list-tree-label">[' . $label . ']</span>';
476 if (isset($arr[$key])) {
477 $theValue = $arr[$key];
478 if ($this->fixedLgd) {
479 $imgBlocks = ceil(1 + strlen($depthData) / 77);
480 $lgdChars = 68 - ceil(strlen(('[' . $key . ']')) * 0.8) - $imgBlocks * 3;
481 $theValue = $this->ext_fixed_lgd($theValue, $lgdChars);
482 }
483 // The value has matched the search string
484 if ($this->tsbrowser_searchKeys[$depth] & 2) {
485 $HTML .= ' = <span class="list-tree-value text-danger">' . htmlspecialchars($theValue) . '</span>';
486 } else {
487 $HTML .= ' = <span class="list-tree-value">' . htmlspecialchars($theValue) . '</span>';
488 }
489 if ($this->ext_regComments && isset($arr[$key . '..'])) {
490 $comment = $arr[$key . '..'];
491 // Skip INCLUDE_TYPOSCRIPT comments, they are almost useless
492 if (!preg_match('/### <INCLUDE_TYPOSCRIPT:.*/', $comment)) {
493 // Remove linebreaks, replace with ' '
494 $comment = preg_replace('/[\\r\\n]/', ' ', $comment);
495 // Remove # and * if more than twice in a row
496 $comment = preg_replace('/[#\\*]{2,}/', '', $comment);
497 // Replace leading # (just if it exists) and add it again. Result: Every comment should be prefixed by a '#'.
498 $comment = preg_replace('/^[#\\*\\s]+/', '# ', $comment);
499 // Masking HTML Tags: Replace < with &lt; and > with &gt;
500 $comment = htmlspecialchars($comment);
501 $HTML .= ' <i class="text-muted">' . trim($comment) . '</i>';
502 }
503 }
504 }
505 $HTML .= '</span>';
506 if ($deeper) {
507 $HTML .= $this->ext_getObjTree($arr[$key . '.'], $depth, $depthData, '', $arr[$key], $alphaSort);
508 }
509 }
510 }
511 if ($HTML !== '') {
512 $HTML = '<ul class="list-tree text-monospace">' . $HTML . '</ul>';
513 }
514
515 return $HTML;
516 }
517
518 /**
519 * Find the originating template name for an array of line numbers (TypoScript setup only!)
520 * Given an array of linenumbers the method will try to find the corresponding template where this line originated
521 * The linenumber indicates the *last* lineNumber that is part of the template
522 *
523 * lineNumbers are in sync with the calculated lineNumbers '.ln..' in TypoScriptParser
524 *
525 * @param array $lnArr Array with linenumbers (might have some extra symbols, for example for unsetting) to be processed
526 * @return array The same array where each entry has been prepended by the template title if available
527 */
528 public function lineNumberToScript(array $lnArr)
529 {
530 // On the first call, construct the lnToScript array.
531 if (!is_array($this->lnToScript)) {
532 $this->lnToScript = [];
533
534 // aggregatedTotalLineCount
535 $c = 0;
536 foreach ($this->hierarchyInfo as $templateNumber => $info) {
537 // hierarchyInfo has the number of lines in configLines, but unfortunately this value
538 // was calculated *before* processing of any INCLUDE instructions
539 // for some yet unknown reason we have to add an extra +2 offset
540 $linecountAfterIncludeProcessing = substr_count($this->config[$templateNumber], LF) + 2;
541 $c += $linecountAfterIncludeProcessing;
542 $this->lnToScript[$c] = $info['title'];
543 }
544 }
545
546 foreach ($lnArr as $k => $ln) {
547 foreach ($this->lnToScript as $endLn => $title) {
548 if ($endLn >= (int)$ln) {
549 $lnArr[$k] = '"' . $title . '", ' . $ln;
550 break;
551 }
552 }
553 }
554
555 return implode('; ', $lnArr);
556 }
557
558 /**
559 * @param array $arr
560 * @param string $depth_in
561 * @param string $searchString
562 * @param array $keyArray
563 * @return array
564 * @throws Exception
565 */
566 public function ext_getSearchKeys($arr, $depth_in, $searchString, $keyArray)
567 {
568 $keyArr = [];
569 foreach ($arr as $key => $value) {
570 $key = preg_replace('/\\.$/', '', $key);
571 if (substr($key, -1) !== '.') {
572 $keyArr[$key] = 1;
573 }
574 }
575 if ($depth_in) {
576 $depth_in = $depth_in . '.';
577 }
578 $searchPattern = '';
579 if ($this->regexMode) {
580 $searchPattern = '/' . addcslashes($searchString, '/') . '/';
581 $matchResult = @preg_match($searchPattern, '');
582 if ($matchResult === false) {
583 throw new Exception(sprintf('Error evaluating regular expression "%s".', $searchPattern), 1446559458);
584 }
585 }
586 foreach ($keyArr as $key => $value) {
587 $depth = $depth_in . $key;
588 $deeper = is_array($arr[$key . '.']);
589 if ($this->regexMode) {
590 // The value has matched
591 if (preg_match($searchPattern, $arr[$key])) {
592 $this->tsbrowser_searchKeys[$depth] += 2;
593 }
594 // The key has matched
595 if (preg_match($searchPattern, $key)) {
596 $this->tsbrowser_searchKeys[$depth] += 4;
597 }
598 // Just open this subtree if the parent key has matched the search
599 if (preg_match($searchPattern, $depth_in)) {
600 $this->tsbrowser_searchKeys[$depth] = 1;
601 }
602 } else {
603 // The value has matched
604 if (stristr($arr[$key], $searchString)) {
605 $this->tsbrowser_searchKeys[$depth] += 2;
606 }
607 // The key has matches
608 if (stristr($key, $searchString)) {
609 $this->tsbrowser_searchKeys[$depth] += 4;
610 }
611 // Just open this subtree if the parent key has matched the search
612 if (stristr($depth_in, $searchString)) {
613 $this->tsbrowser_searchKeys[$depth] = 1;
614 }
615 }
616 if ($deeper) {
617 $cS = count($this->tsbrowser_searchKeys);
618 $keyArray = $this->ext_getSearchKeys($arr[$key . '.'], $depth, $searchString, $keyArray);
619 if ($cS != count($this->tsbrowser_searchKeys)) {
620 $keyArray[$depth] = 1;
621 }
622 }
623 }
624 return $keyArray;
625 }
626
627 /**
628 * @param int $pid
629 * @return int
630 */
631 public function ext_getRootlineNumber($pid)
632 {
633 if ($pid) {
634 foreach ($this->getRootLine() as $key => $val) {
635 if ((int)$val['uid'] === (int)$pid) {
636 return (int)$key;
637 }
638 }
639 }
640 return -1;
641 }
642
643 /**
644 * @param array $arr
645 * @param string $depthData
646 * @param array $keyArray
647 * @param int $first
648 * @return array
649 */
650 public function ext_getTemplateHierarchyArr($arr, $depthData, $keyArray, $first = 0)
651 {
652 $keyArr = [];
653 foreach ($arr as $key => $value) {
654 $key = preg_replace('/\\.$/', '', $key);
655 if (substr($key, -1) !== '.') {
656 $keyArr[$key] = 1;
657 }
658 }
659 $a = 0;
660 $c = count($keyArr);
661 /** @var IconFactory $iconFactory */
662 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
663 foreach ($keyArr as $key => $value) {
664 $HTML = '';
665 $a++;
666 $deeper = is_array($arr[$key . '.']);
667 $row = $arr[$key];
668 $LN = $a == $c ? 'blank' : 'line';
669 $BTM = $a == $c ? 'top' : '';
670 $HTML .= $depthData;
671 $alttext = '[' . $row['templateID'] . ']';
672 $alttext .= $row['pid'] ? ' - ' . BackendUtility::getRecordPath($row['pid'], $GLOBALS['SOBE']->perms_clause, 20) : '';
673 $icon = substr($row['templateID'], 0, 3) === 'sys'
674 ? '<span title="' . htmlspecialchars($alttext) . '">' . $iconFactory->getIconForRecord('sys_template', $row, Icon::SIZE_SMALL)->render() . '</span>'
675 : '<span title="' . htmlspecialchars($alttext) . '">' . $iconFactory->getIcon('mimetypes-x-content-template-static', Icon::SIZE_SMALL)->render() . '</span>';
676 if (in_array($row['templateID'], $this->clearList_const) || in_array($row['templateID'], $this->clearList_setup)) {
677 $urlParameters = [
678 'id' => $GLOBALS['SOBE']->id,
679 'template' => $row['templateID']
680 ];
681 $aHref = BackendUtility::getModuleUrl('web_ts', $urlParameters);
682 $A_B = '<a href="' . htmlspecialchars($aHref) . '">';
683 $A_E = '</a>';
684 if (GeneralUtility::_GP('template') == $row['templateID']) {
685 $A_B = '<strong>' . $A_B;
686 $A_E .= '</strong>';
687 }
688 } else {
689 $A_B = '';
690 $A_E = '';
691 }
692 $HTML .= ($first ? '' : '<span class="treeline-icon treeline-icon-join' . $BTM . '"></span>') . $icon . ' ' . $A_B
693 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['title'], $GLOBALS['BE_USER']->uc['titleLen']))
694 . $A_E . '&nbsp;&nbsp;';
695 $RL = $this->ext_getRootlineNumber($row['pid']);
696 $statusCheckedIcon = $iconFactory->getIcon('status-status-checked', Icon::SIZE_SMALL)->render();
697 $keyArray[] = '<tr>
698 <td class="nowrap">' . $HTML . '</td>
699 <td align="center">' . ($row['root'] ? $statusCheckedIcon : '') . '</td>
700 <td align="center">' . ($row['clConf'] ? $statusCheckedIcon : '') . '</td>
701 <td align="center">' . ($row['clConst'] ? $statusCheckedIcon : '') . '</td>
702 <td align="center">' . ($row['pid'] ?: '') . '</td>
703 <td align="center">' . ($RL >= 0 ? $RL : '') . '</td>
704 <td>' . ($row['next'] ? $row['next'] : '') . '</td>
705 </tr>';
706 if ($deeper) {
707 $keyArray = $this->ext_getTemplateHierarchyArr($arr[$key . '.'], $depthData . ($first ? '' : '<span class="treeline-icon treeline-icon-' . $LN . '"></span>'), $keyArray);
708 }
709 }
710 return $keyArray;
711 }
712
713 /**
714 * Processes the flat array from TemplateService->hierarchyInfo
715 * and turns it into a hierarchical array to show dependencies (used by TemplateAnalyzer)
716 *
717 * @param array $depthDataArr (empty array on external call)
718 * @param int &$pointer Element number (1! to count()) of $this->hierarchyInfo that should be processed.
719 * @return array Processed hierachyInfo.
720 */
721 public function ext_process_hierarchyInfo(array $depthDataArr, &$pointer)
722 {
723 $parent = $this->hierarchyInfo[$pointer - 1]['templateParent'];
724 while ($pointer > 0 && $this->hierarchyInfo[$pointer - 1]['templateParent'] == $parent) {
725 $pointer--;
726 $row = $this->hierarchyInfo[$pointer];
727 $depthDataArr[$row['templateID']] = $row;
728 unset($this->clearList_setup_temp[$row['templateID']]);
729 unset($this->clearList_const_temp[$row['templateID']]);
730 $this->templateTitles[$row['templateID']] = $row['title'];
731 if ($row['templateID'] == $this->hierarchyInfo[$pointer - 1]['templateParent']) {
732 $depthDataArr[$row['templateID'] . '.'] = $this->ext_process_hierarchyInfo([], $pointer);
733 }
734 }
735 return $depthDataArr;
736 }
737
738 /**
739 * Get formatted HTML output for TypoScript either with Syntaxhiglighting or in plain mode
740 *
741 * @param array $config Array with simple strings of typoscript code.
742 * @param bool $lineNumbers Prepend linNumbers to each line.
743 * @param bool $comments Enable including comments in output.
744 * @param bool $crop Enable cropping of long lines.
745 * @param bool $syntaxHL Enrich output with syntaxhighlighting.
746 * @param int $syntaxHLBlockmode
747 * @return string
748 */
749 public function ext_outputTS(
750 array $config, $lineNumbers = false, $comments = false, $crop = false, $syntaxHL = false, $syntaxHLBlockmode = 0
751 ) {
752 $all = '';
753 foreach ($config as $str) {
754 $all .= '[GLOBAL]' . LF . $str;
755 }
756 if ($syntaxHL) {
757 $tsparser = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
758 $tsparser->lineNumberOffset = $this->ext_lineNumberOffset + 1;
759 $tsparser->parentObject = $this;
760 return $tsparser->doSyntaxHighlight($all, $lineNumbers ? [$this->ext_lineNumberOffset + 1] : '', $syntaxHLBlockmode);
761 } else {
762 return $this->ext_formatTS($all, $lineNumbers, $comments, $crop);
763 }
764 }
765
766 /**
767 * Returns a new string of max. $chars length
768 * If the string is longer, it will be truncated and prepended with '...'
769 * $chars must be an integer of at least 4
770 *
771 * @param string $string
772 * @param int $chars
773 * @return string
774 */
775 public function ext_fixed_lgd($string, $chars)
776 {
777 if ($chars >= 4) {
778 if (strlen($string) > $chars) {
779 if (strlen($string) > 24 && preg_match('/^##[a-z0-9]{6}_B##$/', substr($string, 0, 12))) {
780 $string = GeneralUtility::fixed_lgd_cs(substr($string, 12, -12), ($chars - 3));
781 $marker = substr(md5($string), 0, 6);
782 return '##' . $marker . '_B##' . $string . '##' . $marker . '_E##';
783 } else {
784 return GeneralUtility::fixed_lgd_cs($string, $chars - 3);
785 }
786 }
787 }
788 return $string;
789 }
790
791 /**
792 * @param int $lineNumber Line Number
793 * @param array $str
794 * @return string
795 */
796 public function ext_lnBreakPointWrap($lineNumber, $str)
797 {
798 return '<a href="#" id="line-' . $lineNumber . '" onClick="return brPoint(' . $lineNumber . ','
799 . ($this->ext_lineNumberOffset_mode === 'setup' ? 1 : 0) . ');">' . $str . '</a>';
800 }
801
802 /**
803 * @param string $input
804 * @param bool $ln
805 * @param bool $comments
806 * @param bool $crop
807 * @return string
808 */
809 public function ext_formatTS($input, $ln, $comments = true, $crop = false)
810 {
811 $cArr = explode(LF, $input);
812 $n = ceil(log10(count($cArr) + $this->ext_lineNumberOffset));
813 $lineNum = '';
814 foreach ($cArr as $k => $v) {
815 $lln = $k + $this->ext_lineNumberOffset + 1;
816 if ($ln) {
817 $lineNum = $this->ext_lnBreakPointWrap($lln, str_replace(' ', '&nbsp;', sprintf(('% ' . $n . 'd'), $lln))) . ': ';
818 }
819 $v = htmlspecialchars($v);
820 if ($crop) {
821 $v = $this->ext_fixed_lgd($v, $ln ? 71 : 77);
822 }
823 $cArr[$k] = $lineNum . str_replace(' ', '&nbsp;', $v);
824 $firstChar = substr(trim($v), 0, 1);
825 if ($firstChar === '[') {
826 $cArr[$k] = '<strong class="text-success">' . $cArr[$k] . '</strong>';
827 } elseif ($firstChar === '/' || $firstChar === '#') {
828 if ($comments) {
829 $cArr[$k] = '<span class="text-muted">' . $cArr[$k] . '</span>';
830 } else {
831 unset($cArr[$k]);
832 }
833 }
834 }
835 $output = implode($cArr, '<br />') . '<br />';
836 return $output;
837 }
838
839 /**
840 * Get a single sys_template record attached to a single page.
841 * If multiple template records are on this page, the first (order by sorting)
842 * record will be returned, unless a specific template uid is specified via $templateUid
843 *
844 * @param int $pid The pid to select sys_template records from
845 * @param int $templateUid Optional template uid
846 * @return array|null Returns the template record or null if none was found
847 */
848 public function ext_getFirstTemplate($pid, $templateUid = 0)
849 {
850 if (empty($pid)) {
851 return null;
852 }
853
854 // Query is taken from the runThroughTemplates($theRootLine) function in the parent class.
855 $queryBuilder = $this->getTemplateQueryBuilder($pid)
856 ->setMaxResults(1);
857 if ($templateUid) {
858 $queryBuilder->andWhere(
859 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($templateUid, \PDO::PARAM_INT))
860 );
861 }
862 $row = $queryBuilder->execute()->fetch();
863 BackendUtility::workspaceOL('sys_template', $row);
864
865 return $row;
866 }
867
868 /**
869 * Get an array of all template records on a page.
870 *
871 * @param int $pid Pid to fetch sys_template records for
872 * @return array[] Array of template records
873 */
874 public function ext_getAllTemplates($pid): array
875 {
876 if (empty($pid)) {
877 return [];
878 }
879 $result = $this->getTemplateQueryBuilder($pid)->execute();
880 $outRes = [];
881 while ($row = $result->fetch()) {
882 BackendUtility::workspaceOL('sys_template', $row);
883 if (is_array($row)) {
884 $outRes[] = $row;
885 }
886 }
887 return $outRes;
888 }
889
890 /**
891 * Internal helper method to prepare the query builder for
892 * getting sys_template records from a given pid
893 *
894 * @param int $pid The pid to select sys_template records from
895 * @return QueryBuilder Returns a QueryBuilder
896 */
897 protected function getTemplateQueryBuilder(int $pid): QueryBuilder
898 {
899 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
900 ->getQueryBuilderForTable('sys_template');
901 $queryBuilder->getRestrictions()
902 ->removeAll()
903 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
904 $queryBuilder->select('*')
905 ->from('sys_template')
906 ->where(
907 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT))
908 );
909 if (!empty($GLOBALS['TCA']['sys_template']['ctrl']['sortby'])) {
910 $queryBuilder->orderBy($GLOBALS['TCA']['sys_template']['ctrl']['sortby']);
911 }
912
913 return $queryBuilder;
914 }
915
916 /**
917 * This function compares the flattened constants (default and all).
918 * Returns an array with the constants from the whole template which may be edited by the module.
919 *
920 * @param array $default
921 * @return array
922 */
923 public function ext_compareFlatSetups($default)
924 {
925 $editableComments = [];
926 $counter = 0;
927 foreach ($this->flatSetup as $const => $value) {
928 if (substr($const, -2) === '..' || !isset($this->flatSetup[$const . '..'])) {
929 continue;
930 }
931 $counter++;
932 $comment = trim($this->flatSetup[$const . '..']);
933 $c_arr = explode(LF, $comment);
934 foreach ($c_arr as $k => $v) {
935 $line = trim(preg_replace('/^[#\\/]*/', '', $v));
936 if (!$line) {
937 continue;
938 }
939 $parts = explode(';', $line);
940 foreach ($parts as $par) {
941 if (strstr($par, '=')) {
942 $keyValPair = explode('=', $par, 2);
943 switch (trim(strtolower($keyValPair[0]))) {
944 case 'type':
945 // Type:
946 $editableComments[$const]['type'] = trim($keyValPair[1]);
947 break;
948 case 'cat':
949 // List of categories.
950 $catSplit = explode('/', strtolower($keyValPair[1]));
951 $catSplit[0] = trim($catSplit[0]);
952 if (isset($this->categoryLabels[$catSplit[0]])) {
953 $catSplit[0] = $this->categoryLabels[$catSplit[0]];
954 }
955 $editableComments[$const]['cat'] = $catSplit[0];
956 // This is the subcategory. Must be a key in $this->subCategories[].
957 // catSplit[2] represents the search-order within the subcat.
958 $catSplit[1] = trim($catSplit[1]);
959 if ($catSplit[1] && isset($this->subCategories[$catSplit[1]])) {
960 $editableComments[$const]['subcat_name'] = $catSplit[1];
961 $orderIdentifier = isset($catSplit[2]) ? trim($catSplit[2]) : $counter;
962 $editableComments[$const]['subcat'] = $this->subCategories[$catSplit[1]][1]
963 . '/' . $catSplit[1] . '/' . $orderIdentifier . 'z';
964 } elseif (isset($catSplit[2])) {
965 $editableComments[$const]['subcat'] = 'x' . '/' . trim($catSplit[2]) . 'z';
966 } else {
967 $editableComments[$const]['subcat'] = 'x' . '/' . $counter . 'z';
968 }
969 break;
970 case 'label':
971 // Label
972 $editableComments[$const]['label'] = trim($keyValPair[1]);
973 break;
974 case 'customcategory':
975 // Custom category label
976 $customCategory = explode('=', $keyValPair[1], 2);
977 if (trim($customCategory[0])) {
978 $categoryKey = strtolower($customCategory[0]);
979 $this->categoryLabels[$categoryKey] = $this->getLanguageService()->sL($customCategory[1]);
980 }
981 break;
982 case 'customsubcategory':
983 // Custom subCategory label
984 $customSubcategory = explode('=', $keyValPair[1], 2);
985 if (trim($customSubcategory[0])) {
986 $subCategoryKey = strtolower($customSubcategory[0]);
987 $this->subCategories[$subCategoryKey][0] = $this->getLanguageService()->sL($customSubcategory[1]);
988 }
989 break;
990 }
991 }
992 }
993 }
994 if (isset($editableComments[$const])) {
995 $editableComments[$const]['name'] = $const;
996 $editableComments[$const]['value'] = trim($value);
997 if (isset($default[$const])) {
998 $editableComments[$const]['default_value'] = trim($default[$const]);
999 }
1000 }
1001 }
1002 return $editableComments;
1003 }
1004
1005 /**
1006 * @param array $editConstArray
1007 */
1008 public function ext_categorizeEditableConstants($editConstArray)
1009 {
1010 // Runs through the available constants and fills the $this->categories array with pointers and priority-info
1011 foreach ($editConstArray as $constName => $constData) {
1012 if (!$constData['type']) {
1013 $constData['type'] = 'string';
1014 }
1015 $cats = explode(',', $constData['cat']);
1016 // if = only one category, while allows for many. We have agreed on only one category is the most basic way...
1017 foreach ($cats as $theCat) {
1018 $theCat = trim($theCat);
1019 if ($theCat) {
1020 $this->categories[$theCat][$constName] = $constData['subcat'];
1021 }
1022 }
1023 }
1024 }
1025
1026 /**
1027 * @return array
1028 */
1029 public function ext_getCategoryLabelArray()
1030 {
1031 // Returns array used for labels in the menu.
1032 $retArr = [];
1033 foreach ($this->categories as $k => $v) {
1034 if (!empty($v)) {
1035 $retArr[$k] = strtoupper($k) . ' (' . count($v) . ')';
1036 }
1037 }
1038 return $retArr;
1039 }
1040
1041 /**
1042 * @param string $type
1043 * @return array
1044 */
1045 public function ext_getTypeData($type)
1046 {
1047 $retArr = [];
1048 $type = trim($type);
1049 if (!$type) {
1050 $retArr['type'] = 'string';
1051 } else {
1052 $m = strcspn($type, ' [');
1053 $retArr['type'] = strtolower(substr($type, 0, $m));
1054 $types = ['int' => 1, 'options' => 1, 'file' => 1, 'boolean' => 1, 'offset' => 1, 'user' => 1];
1055 if (isset($types[$retArr['type']])) {
1056 $p = trim(substr($type, $m));
1057 $reg = [];
1058 preg_match('/\\[(.*)\\]/', $p, $reg);
1059 $p = trim($reg[1]);
1060 if ($p) {
1061 $retArr['paramstr'] = $p;
1062 switch ($retArr['type']) {
1063 case 'int':
1064 if ($retArr['paramstr'][0] === '-') {
1065 $retArr['params'] = GeneralUtility::intExplode('-', substr($retArr['paramstr'], 1));
1066 $retArr['params'][0] = (int)('-' . $retArr['params'][0]);
1067 } else {
1068 $retArr['params'] = GeneralUtility::intExplode('-', $retArr['paramstr']);
1069 }
1070 $retArr['min'] = $retArr['params'][0];
1071 $retArr['max'] = $retArr['params'][1];
1072 $retArr['paramstr'] = $retArr['params'][0] . ' - ' . $retArr['params'][1];
1073 break;
1074 case 'options':
1075 $retArr['params'] = explode(',', $retArr['paramstr']);
1076 break;
1077 }
1078 }
1079 }
1080 }
1081 return $retArr;
1082 }
1083
1084 /**
1085 * @param string $category
1086 */
1087 public function ext_getTSCE_config($category)
1088 {
1089 $catConf = $this->setup['constants']['TSConstantEditor.'][$category . '.'];
1090 $out = [];
1091 if (is_array($catConf)) {
1092 foreach ($catConf as $key => $val) {
1093 switch ($key) {
1094 case 'description':
1095 case 'bulletlist':
1096 case 'header':
1097 $out[$key] = $val;
1098 break;
1099 default:
1100 if (MathUtility::canBeInterpretedAsInteger($key)) {
1101 $constRefs = explode(',', $val);
1102 foreach ($constRefs as $const) {
1103 $const = trim($const);
1104 if ($const) {
1105 $out['constants'][$const] .= '<span class="label label-danger">' . $key . '</span>';
1106 }
1107 }
1108 }
1109 }
1110 }
1111 }
1112 $this->helpConfig = $out;
1113 }
1114
1115 /**
1116 * @param array $params
1117 * @return array
1118 */
1119 public function ext_fNandV($params)
1120 {
1121 $fN = 'data[' . $params['name'] . ']';
1122 $idName = str_replace('.', '-', $params['name']);
1123 $fV = $params['value'];
1124 // Values entered from the constantsedit cannot be constants! 230502; removed \{ and set {
1125 if (preg_match('/^{[\\$][a-zA-Z0-9\\.]*}$/', trim($fV), $reg)) {
1126 $fV = '';
1127 }
1128 $fV = htmlspecialchars($fV);
1129 return [$fN, $fV, $params, $idName];
1130 }
1131
1132 /**
1133 * This functions returns the HTML-code that creates the editor-layout of the module.
1134 *
1135 * @param array $theConstants
1136 * @param string $category
1137 * @return string
1138 */
1139 public function ext_printFields($theConstants, $category)
1140 {
1141 reset($theConstants);
1142 $output = '';
1143 $subcat = '';
1144 if (is_array($this->categories[$category])) {
1145 $help = $this->helpConfig;
1146 if (!$this->doNotSortCategoriesBeforeMakingForm) {
1147 asort($this->categories[$category]);
1148 }
1149 /** @var IconFactory $iconFactory */
1150 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
1151 foreach ($this->categories[$category] as $name => $type) {
1152 $params = $theConstants[$name];
1153 if (is_array($params)) {
1154 if ($subcat != $params['subcat_name']) {
1155 $subcat = $params['subcat_name'];
1156 $subcat_name = $params['subcat_name'] ? $this->subCategories[$params['subcat_name']][0] : 'Others';
1157 $output .= '<h3>' . $subcat_name . '</h3>';
1158 }
1159 $label = $this->getLanguageService()->sL($params['label']);
1160 $label_parts = explode(':', $label, 2);
1161 if (count($label_parts) === 2) {
1162 $head = trim($label_parts[0]);
1163 $body = trim($label_parts[1]);
1164 } else {
1165 $head = trim($label_parts[0]);
1166 $body = '';
1167 }
1168 $typeDat = $this->ext_getTypeData($params['type']);
1169 $p_field = '';
1170 $raname = substr(md5($params['name']), 0, 10);
1171 $aname = '\'' . $raname . '\'';
1172 list($fN, $fV, $params, $idName) = $this->ext_fNandV($params);
1173 $idName = htmlspecialchars($idName);
1174 $hint = '';
1175 switch ($typeDat['type']) {
1176 case 'int':
1177 case 'int+':
1178 $additionalAttributes = '';
1179 if ($typeDat['paramstr']) {
1180 $hint = ' Range: ' . $typeDat['paramstr'];
1181 } elseif ($typeDat['type'] === 'int+') {
1182 $hint = ' Range: 0 - ';
1183 $typeDat['min'] = 0;
1184 } else {
1185 $hint = ' (Integer)';
1186 }
1187
1188 if (isset($typeDat['min'])) {
1189 $additionalAttributes .= ' min="' . (int)$typeDat['min'] . '" ';
1190 }
1191 if (isset($typeDat['max'])) {
1192 $additionalAttributes .= ' max="' . (int)$typeDat['max'] . '" ';
1193 }
1194
1195 $p_field =
1196 '<input class="form-control" id="' . $idName . '" type="number"'
1197 . ' name="' . $fN . '" value="' . $fV . '"' . ' onChange="uFormUrl(' . $aname . ')"' . $additionalAttributes . ' />';
1198 break;
1199 case 'color':
1200 $p_field = '
1201 <input class="form-control formengine-colorpickerelement t3js-color-picker" type="text" id="input-' . $idName . '" rel="' . $idName .
1202 '" name="' . $fN . '" value="' . $fV . '"' . $this->getDocumentTemplate()->formWidth(7) . ' onChange="uFormUrl(' . $aname . ')" />';
1203
1204 if (empty($this->inlineJavaScript[$typeDat['type']])) {
1205 $this->inlineJavaScript[$typeDat['type']] = 'require([\'TYPO3/CMS/Backend/ColorPicker\'], function(ColorPicker){ColorPicker.initialize()});';
1206 }
1207 break;
1208 case 'wrap':
1209 $wArr = explode('|', $fV);
1210 $p_field = '<input class="form-control" type="text" id="' . $idName . '" name="' . $fN . '" value="' . $wArr[0] . '"' . $this->getDocumentTemplate()->formWidth(29) . ' onChange="uFormUrl(' . $aname . ')" />';
1211 $p_field .= ' | ';
1212 $p_field .= '<input class="form-control" type="text" name="W' . $fN . '" value="' . $wArr[1] . '"' . $this->getDocumentTemplate()->formWidth(15) . ' onChange="uFormUrl(' . $aname . ')" />';
1213 break;
1214 case 'offset':
1215 $wArr = explode(',', $fV);
1216 $labels = GeneralUtility::trimExplode(',', $typeDat['paramstr']);
1217 $p_field = ($labels[0] ? $labels[0] : 'x') . ':<input type="text" name="' . $fN . '" value="' . $wArr[0] . '"' . $this->getDocumentTemplate()->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
1218 $p_field .= ' , ';
1219 $p_field .= ($labels[1] ? $labels[1] : 'y') . ':<input type="text" name="W' . $fN . '" value="' . $wArr[1] . '"' . $this->getDocumentTemplate()->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
1220 $labelsCount = count($labels);
1221 for ($aa = 2; $aa < $labelsCount; $aa++) {
1222 if ($labels[$aa]) {
1223 $p_field .= ' , ' . $labels[$aa] . ':<input type="text" name="W' . $aa . $fN . '" value="' . $wArr[$aa] . '"' . $this->getDocumentTemplate()->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
1224 } else {
1225 $p_field .= '<input type="hidden" name="W' . $aa . $fN . '" value="' . $wArr[$aa] . '" />';
1226 }
1227 }
1228 break;
1229 case 'options':
1230 if (is_array($typeDat['params'])) {
1231 $p_field = '';
1232 foreach ($typeDat['params'] as $val) {
1233 $vParts = explode('=', $val, 2);
1234 $label = $vParts[0];
1235 $val = isset($vParts[1]) ? $vParts[1] : $vParts[0];
1236 // option tag:
1237 $sel = '';
1238 if ($val === $params['value']) {
1239 $sel = ' selected';
1240 }
1241 $p_field .= '<option value="' . htmlspecialchars($val) . '"' . $sel . '>' . $this->getLanguageService()->sL($label) . '</option>';
1242 }
1243 $p_field = '<select class="form-control" id="' . $idName . '" name="' . $fN . '" onChange="uFormUrl(' . $aname . ')">' . $p_field . '</select>';
1244 }
1245 break;
1246 case 'boolean':
1247 $sel = $fV ? 'checked' : '';
1248 $p_field =
1249 '<label class="btn btn-default btn-checkbox">'
1250 . '<input type="hidden" name="' . $fN . '" value="0" />'
1251 . '<input id="' . $idName . '" type="checkbox" name="' . $fN . '" value="' . ($typeDat['paramstr'] ? $typeDat['paramstr'] : 1) . '" ' . $sel . ' onClick="uFormUrl(' . $aname . ')" />'
1252 . '<span class="t3-icon fa"></span>'
1253 . '</label>';
1254 break;
1255 case 'comment':
1256 $sel = $fV ? 'checked' : '';
1257 $p_field =
1258 '<label class="btn btn-default btn-checkbox">'
1259 . '<input type="hidden" name="' . $fN . '" value="#" />'
1260 . '<input id="' . $idName . '" type="checkbox" name="' . $fN . '" value="" ' . $sel . ' onClick="uFormUrl(' . $aname . ')" />'
1261 . '<span class="t3-icon fa"></span>'
1262 . '</label>';
1263 break;
1264 case 'file':
1265 // extensionlist
1266 $extList = $typeDat['paramstr'];
1267 if ($extList === 'IMAGE_EXT') {
1268 $extList = $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'];
1269 }
1270 $p_field = '<option value="">(' . $extList . ')</option>';
1271 if (trim($params['value'])) {
1272 $val = $params['value'];
1273 $p_field .= '<option value=""></option>';
1274 $p_field .= '<option value="' . htmlspecialchars($val) . '" selected>' . $val . '</option>';
1275 }
1276 $p_field = '<select class="form-select" id="' . $idName . '" name="' . $fN . '" onChange="uFormUrl(' . $aname . ')">' . $p_field . '</select>';
1277 break;
1278 case 'user':
1279 $userFunction = $typeDat['paramstr'];
1280 $userFunctionParams = ['fieldName' => $fN, 'fieldValue' => $fV];
1281 $p_field = GeneralUtility::callUserFunction($userFunction, $userFunctionParams, $this);
1282 break;
1283 default:
1284 $p_field = '<input class="form-control" id="' . $idName . '" type="text" name="' . $fN . '" value="' . $fV . '"'
1285 . ' onChange="uFormUrl(' . $aname . ')" />';
1286 }
1287 // Define default names and IDs
1288 $userTyposcriptID = 'userTS-' . $idName;
1289 $defaultTyposcriptID = 'defaultTS-' . $idName;
1290 $checkboxName = 'check[' . $params['name'] . ']';
1291 $checkboxID = 'check-' . $idName;
1292 $userTyposcriptStyle = '';
1293 $deleteIconHTML = '';
1294 $constantCheckbox = '';
1295 $constantDefaultRow = '';
1296 if (!$this->ext_dontCheckIssetValues) {
1297 // Set the default styling options
1298 if (isset($this->objReg[$params['name']])) {
1299 $checkboxValue = 'checked';
1300 $defaultTyposcriptStyle = 'style="display:none;"';
1301 } else {
1302 $checkboxValue = '';
1303 $userTyposcriptStyle = 'style="display:none;"';
1304 $defaultTyposcriptStyle = '';
1305 }
1306 $deleteTitle = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.deleteTitle'));
1307 $deleteIcon = $iconFactory->getIcon('actions-edit-undo', Icon::SIZE_SMALL)->render();
1308 $deleteIconHTML =
1309 '<button type="button" class="btn btn-default t3js-toggle" data-toggle="undo" rel="' . $idName . '">'
1310 . '<span title="' . $deleteTitle . '" alt="' . $deleteTitle . '">'
1311 . $deleteIcon
1312 . '</span>'
1313 . '</button>';
1314 $editTitle = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.editTitle'));
1315 $editIcon = $iconFactory->getIcon('actions-open', Icon::SIZE_SMALL)->render();
1316 $editIconHTML =
1317 '<button type="button" class="btn btn-default t3js-toggle" data-toggle="edit" rel="' . $idName . '">'
1318 . '<span title="' . $editTitle . '" alt="' . $editTitle . '">'
1319 . $editIcon
1320 . '</span>'
1321 . '</button>';
1322 $constantCheckbox = '<input type="hidden" name="' . $checkboxName . '" id="' . $checkboxID . '" value="' . $checkboxValue . '"/>';
1323 // If there's no default value for the field, use a static label.
1324 if (!$params['default_value']) {
1325 $params['default_value'] = '[Empty]';
1326 }
1327 $constantDefaultRow =
1328 '<div class="input-group defaultTS" id="' . $defaultTyposcriptID . '" ' . $defaultTyposcriptStyle . '>'
1329 . '<span class="input-group-btn">' . $editIconHTML . '</span>'
1330 . '<input class="form-control" type="text" placeholder="' . htmlspecialchars($params['default_value']) . '" readonly>'
1331 . '</div>';
1332 }
1333 $constantEditRow =
1334 '<div class="input-group userTS" id="' . $userTyposcriptID . '" ' . $userTyposcriptStyle . '>'
1335 . '<span class="input-group-btn">' . $deleteIconHTML . '</span>'
1336 . $p_field
1337 . '</div>';
1338 $constantLabel = '<label class="t3js-formengine-label"><span>' . htmlspecialchars($head) . '</span></label>';
1339 $constantName = '<span class="help-block">[' . $params['name'] . ']</span>';
1340 $constantDescription = $body ? '<p class="help-block">' . htmlspecialchars($body) . '</p>' : '';
1341 $constantData = '';
1342 if ($hint !== '') {
1343 $constantData .= '<span class="help-block">' . $hint . '</span>';
1344 }
1345 $constantData .=
1346 $constantCheckbox
1347 . $constantEditRow
1348 . $constantDefaultRow;
1349
1350 $output .=
1351 '<fieldset class="form-section">'
1352 . '<a name="' . $raname . '"></a>' . $help['constants'][$params['name']]
1353 . '<div class="form-group">'
1354 . $constantLabel . $constantName . $constantDescription . $constantData
1355 . '</div>'
1356 . '</fieldset>';
1357 } else {
1358 debug('Error. Constant did not exist. Should not happen.');
1359 }
1360 }
1361 }
1362 return '<div class="tstemplate-constanteditor">' . $output . '</div>';
1363 }
1364
1365 /***************************
1366 *
1367 * Processing input values
1368 *
1369 ***************************/
1370 /**
1371 * @param string $constants
1372 */
1373 public function ext_regObjectPositions($constants)
1374 {
1375 // This runs through the lines of the constants-field of the active template and registers the constants-names
1376 // and line positions in an array, $this->objReg
1377 $this->raw = explode(LF, $constants);
1378 $this->rawP = 0;
1379 // Resetting the objReg if the divider is found!!
1380 $this->objReg = [];
1381 $this->ext_regObjects('');
1382 }
1383
1384 /**
1385 * @param string $pre
1386 */
1387 public function ext_regObjects($pre)
1388 {
1389 // Works with regObjectPositions. "expands" the names of the TypoScript objects
1390 while (isset($this->raw[$this->rawP])) {
1391 $line = ltrim($this->raw[$this->rawP]);
1392 if (strstr($line, $this->edit_divider)) {
1393 // Resetting the objReg if the divider is found!!
1394 $this->objReg = [];
1395 }
1396 $this->rawP++;
1397 if ($line) {
1398 if ($line[0] === '[') {
1399 } elseif (strcspn($line, '}#/') != 0) {
1400 $varL = strcspn($line, ' {=<');
1401 $var = substr($line, 0, $varL);
1402 $line = ltrim(substr($line, $varL));
1403 switch ($line[0]) {
1404 case '=':
1405 $this->objReg[$pre . $var] = $this->rawP - 1;
1406 break;
1407 case '{':
1408 $this->ext_inBrace++;
1409 $this->ext_regObjects($pre . $var . '.');
1410 break;
1411 }
1412 $this->lastComment = '';
1413 } elseif ($line[0] === '}') {
1414 $this->lastComment = '';
1415 $this->ext_inBrace--;
1416 if ($this->ext_inBrace < 0) {
1417 $this->ext_inBrace = 0;
1418 } else {
1419 break;
1420 }
1421 }
1422 }
1423 }
1424 }
1425
1426 /**
1427 * @param string $key
1428 * @param string $var
1429 */
1430 public function ext_putValueInConf($key, $var)
1431 {
1432 // Puts the value $var to the TypoScript value $key in the current lines of the templates.
1433 // If the $key is not found in the template constants field, a new line is inserted in the bottom.
1434 $theValue = ' ' . trim($var);
1435 if (isset($this->objReg[$key])) {
1436 $lineNum = $this->objReg[$key];
1437 $parts = explode('=', $this->raw[$lineNum], 2);
1438 if (count($parts) === 2) {
1439 $parts[1] = $theValue;
1440 }
1441 $this->raw[$lineNum] = implode($parts, '=');
1442 } else {
1443 $this->raw[] = $key . ' =' . $theValue;
1444 }
1445 $this->changed = true;
1446 }
1447
1448 /**
1449 * @param string $key
1450 */
1451 public function ext_removeValueInConf($key)
1452 {
1453 // Removes the value in the configuration
1454 if (isset($this->objReg[$key])) {
1455 $lineNum = $this->objReg[$key];
1456 unset($this->raw[$lineNum]);
1457 }
1458 $this->changed = true;
1459 }
1460
1461 /**
1462 * @param array $arr
1463 * @param array $settings
1464 * @return array
1465 */
1466 public function ext_depthKeys($arr, $settings)
1467 {
1468 $tsbrArray = [];
1469 foreach ($arr as $theK => $theV) {
1470 $theKeyParts = explode('.', $theK);
1471 $depth = '';
1472 $c = count($theKeyParts);
1473 $a = 0;
1474 foreach ($theKeyParts as $p) {
1475 $a++;
1476 $depth .= ($depth ? '.' : '') . $p;
1477 $tsbrArray[$depth] = $c == $a ? $theV : 1;
1478 }
1479 }
1480 // Modify settings
1481 foreach ($tsbrArray as $theK => $theV) {
1482 if ($theV) {
1483 $settings[$theK] = 1;
1484 } else {
1485 unset($settings[$theK]);
1486 }
1487 }
1488 return $settings;
1489 }
1490
1491 /**
1492 * Process input
1493 *
1494 * @param array $http_post_vars
1495 * @param array $http_post_files (not used anymore)
1496 * @param array $theConstants
1497 * @param array $tplRow Not used
1498 */
1499 public function ext_procesInput($http_post_vars, $http_post_files, $theConstants, $tplRow)
1500 {
1501 $data = $http_post_vars['data'];
1502 $check = $http_post_vars['check'];
1503 $Wdata = $http_post_vars['Wdata'];
1504 $W2data = $http_post_vars['W2data'];
1505 $W3data = $http_post_vars['W3data'];
1506 $W4data = $http_post_vars['W4data'];
1507 $W5data = $http_post_vars['W5data'];
1508 if (is_array($data)) {
1509 foreach ($data as $key => $var) {
1510 if (isset($theConstants[$key])) {
1511 // If checkbox is set, update the value
1512 if ($this->ext_dontCheckIssetValues || isset($check[$key])) {
1513 // Exploding with linebreak, just to make sure that no multiline input is given!
1514 list($var) = explode(LF, $var);
1515 $typeDat = $this->ext_getTypeData($theConstants[$key]['type']);
1516 switch ($typeDat['type']) {
1517 case 'int':
1518 if ($typeDat['paramstr']) {
1519 $var = MathUtility::forceIntegerInRange($var, $typeDat['params'][0], $typeDat['params'][1]);
1520 } else {
1521 $var = (int)$var;
1522 }
1523 break;
1524 case 'int+':
1525 $var = max(0, (int)$var);
1526 break;
1527 case 'color':
1528 $col = [];
1529 if ($var) {
1530 $var = preg_replace('/[^A-Fa-f0-9]*/', '', $var);
1531 $useFulHex = strlen($var) > 3;
1532 $col[] = hexdec($var[0]);
1533 $col[] = hexdec($var[1]);
1534 $col[] = hexdec($var[2]);
1535 if ($useFulHex) {
1536 $col[] = hexdec($var[3]);
1537 $col[] = hexdec($var[4]);
1538 $col[] = hexdec($var[5]);
1539 }
1540 $var = substr(('0' . dechex($col[0])), -1) . substr(('0' . dechex($col[1])), -1) . substr(('0' . dechex($col[2])), -1);
1541 if ($useFulHex) {
1542 $var .= substr(('0' . dechex($col[3])), -1) . substr(('0' . dechex($col[4])), -1) . substr(('0' . dechex($col[5])), -1);
1543 }
1544 $var = '#' . strtoupper($var);
1545 }
1546 break;
1547 case 'comment':
1548 if ($var) {
1549 $var = '#';
1550 } else {
1551 $var = '';
1552 }
1553 break;
1554 case 'wrap':
1555 if (isset($Wdata[$key])) {
1556 $var .= '|' . $Wdata[$key];
1557 }
1558 break;
1559 case 'offset':
1560 if (isset($Wdata[$key])) {
1561 $var = (int)$var . ',' . (int)$Wdata[$key];
1562 if (isset($W2data[$key])) {
1563 $var .= ',' . (int)$W2data[$key];
1564 if (isset($W3data[$key])) {
1565 $var .= ',' . (int)$W3data[$key];
1566 if (isset($W4data[$key])) {
1567 $var .= ',' . (int)$W4data[$key];
1568 if (isset($W5data[$key])) {
1569 $var .= ',' . (int)$W5data[$key];
1570 }
1571 }
1572 }
1573 }
1574 }
1575 break;
1576 case 'boolean':
1577 if ($var) {
1578 $var = $typeDat['paramstr'] ? $typeDat['paramstr'] : 1;
1579 }
1580 break;
1581 }
1582 if ($this->ext_printAll || (string)$theConstants[$key]['value'] !== (string)$var) {
1583 // Put value in, if changed.
1584 $this->ext_putValueInConf($key, $var);
1585 }
1586 // Remove the entry because it has been "used"
1587 unset($check[$key]);
1588 } else {
1589 $this->ext_removeValueInConf($key);
1590 }
1591 }
1592 }
1593 }
1594 // Remaining keys in $check indicates fields that are just clicked "on" to be edited.
1595 // Therefore we get the default value and puts that in the template as a start...
1596 if (!$this->ext_dontCheckIssetValues && is_array($check)) {
1597 foreach ($check as $key => $var) {
1598 if (isset($theConstants[$key])) {
1599 $dValue = $theConstants[$key]['default_value'];
1600 $this->ext_putValueInConf($key, $dValue);
1601 }
1602 }
1603 }
1604 }
1605
1606 /**
1607 * @param int $id
1608 * @param string $perms_clause
1609 * @return array
1610 */
1611 public function ext_prevPageWithTemplate($id, $perms_clause)
1612 {
1613 $rootLine = BackendUtility::BEgetRootLine($id, $perms_clause ? ' AND ' . $perms_clause : '');
1614 foreach ($rootLine as $p) {
1615 if ($this->ext_getFirstTemplate($p['uid'])) {
1616 return $p;
1617 }
1618 }
1619 return [];
1620 }
1621
1622 /**
1623 * Is set by runThroughTemplates(), previously set via TemplateAnalyzerModuleFunctionController from the outside
1624 *
1625 * @return array
1626 */
1627 protected function getRootLine()
1628 {
1629 return is_array($this->absoluteRootLine) ? $this->absoluteRootLine : [];
1630 }
1631
1632 /**
1633 * @return LanguageService
1634 */
1635 protected function getLanguageService()
1636 {
1637 return $GLOBALS['LANG'];
1638 }
1639
1640 /**
1641 * @return DocumentTemplate
1642 */
1643 protected function getDocumentTemplate()
1644 {
1645 return $GLOBALS['TBE_TEMPLATE'];
1646 }
1647 }