[TASK] Update php-cs-fixer to 2.5.0
[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\Localization\LanguageService;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\MathUtility;
28 use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
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 }
380 return [$theSetup[$parts[0] . '.'], $theSetup[$parts[0]]];
381 }
382 if (trim($theKey) !== '') {
383 return [[], $theSetup[$theKey]];
384 }
385 return [$theSetup, ''];
386 }
387
388 /**
389 * Get object tree
390 *
391 * @param array $arr
392 * @param string $depth_in
393 * @param string $depthData
394 * @param string $parentType (unused)
395 * @param string $parentValue (unused)
396 * @param string $alphaSort sorts the array keys / tree by alphabet when set to 1
397 * @return array
398 */
399 public function ext_getObjTree($arr, $depth_in, $depthData, $parentType = '', $parentValue = '', $alphaSort = '0')
400 {
401 $HTML = '';
402 if ($alphaSort == '1') {
403 ksort($arr);
404 }
405 $keyArr_num = [];
406 $keyArr_alpha = [];
407 foreach ($arr as $key => $value) {
408 // Don't do anything with comments / linenumber registrations...
409 if (substr($key, -2) !== '..') {
410 $key = preg_replace('/\\.$/', '', $key);
411 if (substr($key, -1) !== '.') {
412 if (MathUtility::canBeInterpretedAsInteger($key)) {
413 $keyArr_num[$key] = $arr[$key];
414 } else {
415 $keyArr_alpha[$key] = $arr[$key];
416 }
417 }
418 }
419 }
420 ksort($keyArr_num);
421 $keyArr = $keyArr_num + $keyArr_alpha;
422 if ($depth_in) {
423 $depth_in = $depth_in . '.';
424 }
425 foreach ($keyArr as $key => $value) {
426 $depth = $depth_in . $key;
427 // This excludes all constants starting with '_' from being shown.
428 if ($this->bType !== 'const' || $depth[0] !== '_') {
429 $goto = substr(md5($depth), 0, 6);
430 $deeper = is_array($arr[$key . '.']) && ($this->tsbrowser_depthKeys[$depth] || $this->ext_expandAllNotes) ? 1 : 0;
431 $PM = is_array($arr[$key . '.']) && !$this->ext_noPMicons ? ($deeper ? 'minus' : 'plus') : 'join';
432 $HTML .= $depthData . '<li>';
433 if ($PM !== 'join') {
434 $urlParameters = [
435 'id' => $GLOBALS['SOBE']->id,
436 'tsbr[' . $depth . ']' => $deeper ? 0 : 1
437 ];
438 if (GeneralUtility::_GP('breakPointLN')) {
439 $urlParameters['breakPointLN'] = GeneralUtility::_GP('breakPointLN');
440 }
441 $aHref = BackendUtility::getModuleUrl('web_ts', $urlParameters) . '#' . $goto;
442 $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>';
443 }
444 $label = $key;
445 // Read only...
446 if (($depth === 'types' || $depth === 'resources' || $depth === 'sitetitle') && $this->bType === 'setup') {
447 $label = '<span style="color: #666666;">' . $label . '</span>';
448 } else {
449 if ($this->linkObjects) {
450 $urlParameters = [
451 'id' => $GLOBALS['SOBE']->id,
452 'sObj' => $depth
453 ];
454 if (GeneralUtility::_GP('breakPointLN')) {
455 $urlParameters['breakPointLN'] = GeneralUtility::_GP('breakPointLN');
456 }
457 $aHref = BackendUtility::getModuleUrl('web_ts', $urlParameters);
458 if ($this->bType !== 'const') {
459 $ln = is_array($arr[$key . '.ln..']) ? 'Defined in: ' . $this->lineNumberToScript($arr[$key . '.ln..']) : 'N/A';
460 } else {
461 $ln = '';
462 }
463 if ($this->tsbrowser_searchKeys[$depth] & 4) {
464 $label = '<strong class="text-danger">' . $label . '</strong>';
465 }
466 // The key has matched the search string
467 $label = '<a href="' . htmlspecialchars($aHref) . '" title="' . htmlspecialchars($ln) . '">' . $label . '</a>';
468 }
469 }
470 $HTML .= '
471 <span class="list-tree-group">
472 <span class="list-tree-label">[' . $label . ']</span>';
473 if (isset($arr[$key])) {
474 $theValue = $arr[$key];
475 if ($this->fixedLgd) {
476 $imgBlocks = ceil(1 + strlen($depthData) / 77);
477 $lgdChars = 68 - ceil(strlen(('[' . $key . ']')) * 0.8) - $imgBlocks * 3;
478 $theValue = $this->ext_fixed_lgd($theValue, $lgdChars);
479 }
480 // The value has matched the search string
481 if ($this->tsbrowser_searchKeys[$depth] & 2) {
482 $HTML .= ' = <span class="list-tree-value text-danger">' . htmlspecialchars($theValue) . '</span>';
483 } else {
484 $HTML .= ' = <span class="list-tree-value">' . htmlspecialchars($theValue) . '</span>';
485 }
486 if ($this->ext_regComments && isset($arr[$key . '..'])) {
487 $comment = $arr[$key . '..'];
488 // Skip INCLUDE_TYPOSCRIPT comments, they are almost useless
489 if (!preg_match('/### <INCLUDE_TYPOSCRIPT:.*/', $comment)) {
490 // Remove linebreaks, replace with ' '
491 $comment = preg_replace('/[\\r\\n]/', ' ', $comment);
492 // Remove # and * if more than twice in a row
493 $comment = preg_replace('/[#\\*]{2,}/', '', $comment);
494 // Replace leading # (just if it exists) and add it again. Result: Every comment should be prefixed by a '#'.
495 $comment = preg_replace('/^[#\\*\\s]+/', '# ', $comment);
496 // Masking HTML Tags: Replace < with &lt; and > with &gt;
497 $comment = htmlspecialchars($comment);
498 $HTML .= ' <i class="text-muted">' . trim($comment) . '</i>';
499 }
500 }
501 }
502 $HTML .= '</span>';
503 if ($deeper) {
504 $HTML .= $this->ext_getObjTree($arr[$key . '.'], $depth, $depthData, '', $arr[$key], $alphaSort);
505 }
506 }
507 }
508 if ($HTML !== '') {
509 $HTML = '<ul class="list-tree text-monospace">' . $HTML . '</ul>';
510 }
511
512 return $HTML;
513 }
514
515 /**
516 * Find the originating template name for an array of line numbers (TypoScript setup only!)
517 * Given an array of linenumbers the method will try to find the corresponding template where this line originated
518 * The linenumber indicates the *last* lineNumber that is part of the template
519 *
520 * lineNumbers are in sync with the calculated lineNumbers '.ln..' in TypoScriptParser
521 *
522 * @param array $lnArr Array with linenumbers (might have some extra symbols, for example for unsetting) to be processed
523 * @return array The same array where each entry has been prepended by the template title if available
524 */
525 public function lineNumberToScript(array $lnArr)
526 {
527 // On the first call, construct the lnToScript array.
528 if (!is_array($this->lnToScript)) {
529 $this->lnToScript = [];
530
531 // aggregatedTotalLineCount
532 $c = 0;
533 foreach ($this->hierarchyInfo as $templateNumber => $info) {
534 // hierarchyInfo has the number of lines in configLines, but unfortunately this value
535 // was calculated *before* processing of any INCLUDE instructions
536 // for some yet unknown reason we have to add an extra +2 offset
537 $linecountAfterIncludeProcessing = substr_count($this->config[$templateNumber], LF) + 2;
538 $c += $linecountAfterIncludeProcessing;
539 $this->lnToScript[$c] = $info['title'];
540 }
541 }
542
543 foreach ($lnArr as $k => $ln) {
544 foreach ($this->lnToScript as $endLn => $title) {
545 if ($endLn >= (int)$ln) {
546 $lnArr[$k] = '"' . $title . '", ' . $ln;
547 break;
548 }
549 }
550 }
551
552 return implode('; ', $lnArr);
553 }
554
555 /**
556 * @param array $arr
557 * @param string $depth_in
558 * @param string $searchString
559 * @param array $keyArray
560 * @return array
561 * @throws Exception
562 */
563 public function ext_getSearchKeys($arr, $depth_in, $searchString, $keyArray)
564 {
565 $keyArr = [];
566 foreach ($arr as $key => $value) {
567 $key = preg_replace('/\\.$/', '', $key);
568 if (substr($key, -1) !== '.') {
569 $keyArr[$key] = 1;
570 }
571 }
572 if ($depth_in) {
573 $depth_in = $depth_in . '.';
574 }
575 $searchPattern = '';
576 if ($this->regexMode) {
577 $searchPattern = '/' . addcslashes($searchString, '/') . '/';
578 $matchResult = @preg_match($searchPattern, '');
579 if ($matchResult === false) {
580 throw new Exception(sprintf('Error evaluating regular expression "%s".', $searchPattern), 1446559458);
581 }
582 }
583 foreach ($keyArr as $key => $value) {
584 $depth = $depth_in . $key;
585 $deeper = is_array($arr[$key . '.']);
586 if ($this->regexMode) {
587 // The value has matched
588 if (preg_match($searchPattern, $arr[$key])) {
589 $this->tsbrowser_searchKeys[$depth] += 2;
590 }
591 // The key has matched
592 if (preg_match($searchPattern, $key)) {
593 $this->tsbrowser_searchKeys[$depth] += 4;
594 }
595 // Just open this subtree if the parent key has matched the search
596 if (preg_match($searchPattern, $depth_in)) {
597 $this->tsbrowser_searchKeys[$depth] = 1;
598 }
599 } else {
600 // The value has matched
601 if (stristr($arr[$key], $searchString)) {
602 $this->tsbrowser_searchKeys[$depth] += 2;
603 }
604 // The key has matches
605 if (stristr($key, $searchString)) {
606 $this->tsbrowser_searchKeys[$depth] += 4;
607 }
608 // Just open this subtree if the parent key has matched the search
609 if (stristr($depth_in, $searchString)) {
610 $this->tsbrowser_searchKeys[$depth] = 1;
611 }
612 }
613 if ($deeper) {
614 $cS = count($this->tsbrowser_searchKeys);
615 $keyArray = $this->ext_getSearchKeys($arr[$key . '.'], $depth, $searchString, $keyArray);
616 if ($cS != count($this->tsbrowser_searchKeys)) {
617 $keyArray[$depth] = 1;
618 }
619 }
620 }
621 return $keyArray;
622 }
623
624 /**
625 * @param int $pid
626 * @return int
627 */
628 public function ext_getRootlineNumber($pid)
629 {
630 if ($pid) {
631 foreach ($this->getRootLine() as $key => $val) {
632 if ((int)$val['uid'] === (int)$pid) {
633 return (int)$key;
634 }
635 }
636 }
637 return -1;
638 }
639
640 /**
641 * @param array $arr
642 * @param string $depthData
643 * @param array $keyArray
644 * @param int $first
645 * @return array
646 */
647 public function ext_getTemplateHierarchyArr($arr, $depthData, $keyArray, $first = 0)
648 {
649 $keyArr = [];
650 foreach ($arr as $key => $value) {
651 $key = preg_replace('/\\.$/', '', $key);
652 if (substr($key, -1) !== '.') {
653 $keyArr[$key] = 1;
654 }
655 }
656 $a = 0;
657 $c = count($keyArr);
658 /** @var IconFactory $iconFactory */
659 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
660 foreach ($keyArr as $key => $value) {
661 $HTML = '';
662 $a++;
663 $deeper = is_array($arr[$key . '.']);
664 $row = $arr[$key];
665 $LN = $a == $c ? 'blank' : 'line';
666 $BTM = $a == $c ? 'top' : '';
667 $HTML .= $depthData;
668 $alttext = '[' . $row['templateID'] . ']';
669 $alttext .= $row['pid'] ? ' - ' . BackendUtility::getRecordPath($row['pid'], $GLOBALS['SOBE']->perms_clause, 20) : '';
670 $icon = substr($row['templateID'], 0, 3) === 'sys'
671 ? '<span title="' . htmlspecialchars($alttext) . '">' . $iconFactory->getIconForRecord('sys_template', $row, Icon::SIZE_SMALL)->render() . '</span>'
672 : '<span title="' . htmlspecialchars($alttext) . '">' . $iconFactory->getIcon('mimetypes-x-content-template-static', Icon::SIZE_SMALL)->render() . '</span>';
673 if (in_array($row['templateID'], $this->clearList_const) || in_array($row['templateID'], $this->clearList_setup)) {
674 $urlParameters = [
675 'id' => $GLOBALS['SOBE']->id,
676 'template' => $row['templateID']
677 ];
678 $aHref = BackendUtility::getModuleUrl('web_ts', $urlParameters);
679 $A_B = '<a href="' . htmlspecialchars($aHref) . '">';
680 $A_E = '</a>';
681 if (GeneralUtility::_GP('template') == $row['templateID']) {
682 $A_B = '<strong>' . $A_B;
683 $A_E .= '</strong>';
684 }
685 } else {
686 $A_B = '';
687 $A_E = '';
688 }
689 $HTML .= ($first ? '' : '<span class="treeline-icon treeline-icon-join' . $BTM . '"></span>') . $icon . ' ' . $A_B
690 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['title'], $GLOBALS['BE_USER']->uc['titleLen']))
691 . $A_E . '&nbsp;&nbsp;';
692 $RL = $this->ext_getRootlineNumber($row['pid']);
693 $statusCheckedIcon = $iconFactory->getIcon('status-status-checked', Icon::SIZE_SMALL)->render();
694 $keyArray[] = '<tr>
695 <td class="nowrap">' . $HTML . '</td>
696 <td align="center">' . ($row['root'] ? $statusCheckedIcon : '') . '</td>
697 <td align="center">' . ($row['clConf'] ? $statusCheckedIcon : '') . '</td>
698 <td align="center">' . ($row['clConst'] ? $statusCheckedIcon : '') . '</td>
699 <td align="center">' . ($row['pid'] ?: '') . '</td>
700 <td align="center">' . ($RL >= 0 ? $RL : '') . '</td>
701 <td>' . ($row['next'] ? $row['next'] : '') . '</td>
702 </tr>';
703 if ($deeper) {
704 $keyArray = $this->ext_getTemplateHierarchyArr($arr[$key . '.'], $depthData . ($first ? '' : '<span class="treeline-icon treeline-icon-' . $LN . '"></span>'), $keyArray);
705 }
706 }
707 return $keyArray;
708 }
709
710 /**
711 * Processes the flat array from TemplateService->hierarchyInfo
712 * and turns it into a hierarchical array to show dependencies (used by TemplateAnalyzer)
713 *
714 * @param array $depthDataArr (empty array on external call)
715 * @param int &$pointer Element number (1! to count()) of $this->hierarchyInfo that should be processed.
716 * @return array Processed hierachyInfo.
717 */
718 public function ext_process_hierarchyInfo(array $depthDataArr, &$pointer)
719 {
720 $parent = $this->hierarchyInfo[$pointer - 1]['templateParent'];
721 while ($pointer > 0 && $this->hierarchyInfo[$pointer - 1]['templateParent'] == $parent) {
722 $pointer--;
723 $row = $this->hierarchyInfo[$pointer];
724 $depthDataArr[$row['templateID']] = $row;
725 unset($this->clearList_setup_temp[$row['templateID']]);
726 unset($this->clearList_const_temp[$row['templateID']]);
727 $this->templateTitles[$row['templateID']] = $row['title'];
728 if ($row['templateID'] == $this->hierarchyInfo[$pointer - 1]['templateParent']) {
729 $depthDataArr[$row['templateID'] . '.'] = $this->ext_process_hierarchyInfo([], $pointer);
730 }
731 }
732 return $depthDataArr;
733 }
734
735 /**
736 * Get formatted HTML output for TypoScript either with Syntaxhiglighting or in plain mode
737 *
738 * @param array $config Array with simple strings of typoscript code.
739 * @param bool $lineNumbers Prepend linNumbers to each line.
740 * @param bool $comments Enable including comments in output.
741 * @param bool $crop Enable cropping of long lines.
742 * @param bool $syntaxHL Enrich output with syntaxhighlighting.
743 * @param int $syntaxHLBlockmode
744 * @return string
745 */
746 public function ext_outputTS(
747 array $config,
748 $lineNumbers = false,
749 $comments = false,
750 $crop = false,
751 $syntaxHL = false,
752 $syntaxHLBlockmode = 0
753 ) {
754 $all = '';
755 foreach ($config as $str) {
756 $all .= '[GLOBAL]' . LF . $str;
757 }
758 if ($syntaxHL) {
759 $tsparser = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
760 $tsparser->lineNumberOffset = $this->ext_lineNumberOffset + 1;
761 $tsparser->parentObject = $this;
762 return $tsparser->doSyntaxHighlight($all, $lineNumbers ? [$this->ext_lineNumberOffset + 1] : '', $syntaxHLBlockmode);
763 }
764 return $this->ext_formatTS($all, $lineNumbers, $comments, $crop);
765 }
766
767 /**
768 * Returns a new string of max. $chars length
769 * If the string is longer, it will be truncated and prepended with '...'
770 * $chars must be an integer of at least 4
771 *
772 * @param string $string
773 * @param int $chars
774 * @return string
775 */
776 public function ext_fixed_lgd($string, $chars)
777 {
778 if ($chars >= 4) {
779 if (strlen($string) > $chars) {
780 if (strlen($string) > 24 && preg_match('/^##[a-z0-9]{6}_B##$/', substr($string, 0, 12))) {
781 $string = GeneralUtility::fixed_lgd_cs(substr($string, 12, -12), ($chars - 3));
782 $marker = substr(md5($string), 0, 6);
783 return '##' . $marker . '_B##' . $string . '##' . $marker . '_E##';
784 }
785 return GeneralUtility::fixed_lgd_cs($string, $chars - 3);
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 . '" 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 = '<div class="input-group">
1211 <input class="form-control form-control-adapt" type="text" id="' . $idName . '" name="' . $fN . '" value="' . $wArr[0] . '" onChange="uFormUrl(' . $aname . ')" />
1212 <span class="input-group-addon input-group-icon">|</span>
1213 <input class="form-control form-control-adapt" type="text" name="W' . $fN . '" value="' . $wArr[1] . '" onChange="uFormUrl(' . $aname . ')" />
1214 </div>';
1215 break;
1216 case 'offset':
1217 $wArr = explode(',', $fV);
1218 $labels = GeneralUtility::trimExplode(',', $typeDat['paramstr']);
1219 $p_field = '<span class="input-group-addon input-group-icon">' . ($labels[0] ?: 'x') . '</span><input type="text" class="form-control form-control-adapt" name="' . $fN . '" value="' . $wArr[0] . '" onChange="uFormUrl(' . $aname . ')" />';
1220 $p_field .= '<span class="input-group-addon input-group-icon">' . ($labels[1] ?: 'y') . '</span><input type="text" name="W' . $fN . '" value="' . $wArr[1] . '" class="form-control form-control-adapt" onChange="uFormUrl(' . $aname . ')" />';
1221 $labelsCount = count($labels);
1222 for ($aa = 2; $aa < $labelsCount; $aa++) {
1223 if ($labels[$aa]) {
1224 $p_field .= '<span class="input-group-addon input-group-icon">' . $labels[$aa] . '</span><input type="text" name="W' . $aa . $fN . '" value="' . $wArr[$aa] . '" class="form-control form-control-adapt" onChange="uFormUrl(' . $aname . ')" />';
1225 } else {
1226 $p_field .= '<input type="hidden" name="W' . $aa . $fN . '" value="' . $wArr[$aa] . '" />';
1227 }
1228 }
1229 $p_field = '<div class="input-group">' . $p_field . '</div>';
1230 break;
1231 case 'options':
1232 if (is_array($typeDat['params'])) {
1233 $p_field = '';
1234 foreach ($typeDat['params'] as $val) {
1235 $vParts = explode('=', $val, 2);
1236 $label = $vParts[0];
1237 $val = isset($vParts[1]) ? $vParts[1] : $vParts[0];
1238 // option tag:
1239 $sel = '';
1240 if ($val === $params['value']) {
1241 $sel = ' selected';
1242 }
1243 $p_field .= '<option value="' . htmlspecialchars($val) . '"' . $sel . '>' . $this->getLanguageService()->sL($label) . '</option>';
1244 }
1245 $p_field = '<select class="form-control" id="' . $idName . '" name="' . $fN . '" onChange="uFormUrl(' . $aname . ')">' . $p_field . '</select>';
1246 }
1247 break;
1248 case 'boolean':
1249 $sel = $fV ? 'checked' : '';
1250 $p_field =
1251 '<label class="btn btn-default btn-checkbox">'
1252 . '<input type="hidden" name="' . $fN . '" value="0" />'
1253 . '<input id="' . $idName . '" type="checkbox" name="' . $fN . '" value="' . ($typeDat['paramstr'] ? $typeDat['paramstr'] : 1) . '" ' . $sel . ' onClick="uFormUrl(' . $aname . ')" />'
1254 . '<span class="t3-icon fa"></span>'
1255 . '</label>';
1256 break;
1257 case 'comment':
1258 $sel = $fV ? 'checked' : '';
1259 $p_field =
1260 '<label class="btn btn-default btn-checkbox">'
1261 . '<input type="hidden" name="' . $fN . '" value="#" />'
1262 . '<input id="' . $idName . '" type="checkbox" name="' . $fN . '" value="" ' . $sel . ' onClick="uFormUrl(' . $aname . ')" />'
1263 . '<span class="t3-icon fa"></span>'
1264 . '</label>';
1265 break;
1266 case 'file':
1267 // extensionlist
1268 $extList = $typeDat['paramstr'];
1269 if ($extList === 'IMAGE_EXT') {
1270 $extList = $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'];
1271 }
1272 $p_field = '<option value="">(' . $extList . ')</option>';
1273 if (trim($params['value'])) {
1274 $val = $params['value'];
1275 $p_field .= '<option value=""></option>';
1276 $p_field .= '<option value="' . htmlspecialchars($val) . '" selected>' . $val . '</option>';
1277 }
1278 $p_field = '<select class="form-select" id="' . $idName . '" name="' . $fN . '" onChange="uFormUrl(' . $aname . ')">' . $p_field . '</select>';
1279 break;
1280 case 'user':
1281 $userFunction = $typeDat['paramstr'];
1282 $userFunctionParams = ['fieldName' => $fN, 'fieldValue' => $fV];
1283 $p_field = GeneralUtility::callUserFunction($userFunction, $userFunctionParams, $this);
1284 break;
1285 default:
1286 $p_field = '<input class="form-control" id="' . $idName . '" type="text" name="' . $fN . '" value="' . $fV . '"'
1287 . ' onChange="uFormUrl(' . $aname . ')" />';
1288 }
1289 // Define default names and IDs
1290 $userTyposcriptID = 'userTS-' . $idName;
1291 $defaultTyposcriptID = 'defaultTS-' . $idName;
1292 $checkboxName = 'check[' . $params['name'] . ']';
1293 $checkboxID = 'check-' . $idName;
1294 $userTyposcriptStyle = '';
1295 $deleteIconHTML = '';
1296 $constantCheckbox = '';
1297 $constantDefaultRow = '';
1298 if (!$this->ext_dontCheckIssetValues) {
1299 // Set the default styling options
1300 if (isset($this->objReg[$params['name']])) {
1301 $checkboxValue = 'checked';
1302 $defaultTyposcriptStyle = 'style="display:none;"';
1303 } else {
1304 $checkboxValue = '';
1305 $userTyposcriptStyle = 'style="display:none;"';
1306 $defaultTyposcriptStyle = '';
1307 }
1308 $deleteTitle = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.deleteTitle'));
1309 $deleteIcon = $iconFactory->getIcon('actions-edit-undo', Icon::SIZE_SMALL)->render();
1310 $deleteIconHTML =
1311 '<button type="button" class="btn btn-default t3js-toggle" data-toggle="undo" rel="' . $idName . '">'
1312 . '<span title="' . $deleteTitle . '" alt="' . $deleteTitle . '">'
1313 . $deleteIcon
1314 . '</span>'
1315 . '</button>';
1316 $editTitle = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.editTitle'));
1317 $editIcon = $iconFactory->getIcon('actions-open', Icon::SIZE_SMALL)->render();
1318 $editIconHTML =
1319 '<button type="button" class="btn btn-default t3js-toggle" data-toggle="edit" rel="' . $idName . '">'
1320 . '<span title="' . $editTitle . '" alt="' . $editTitle . '">'
1321 . $editIcon
1322 . '</span>'
1323 . '</button>';
1324 $constantCheckbox = '<input type="hidden" name="' . $checkboxName . '" id="' . $checkboxID . '" value="' . $checkboxValue . '"/>';
1325 // If there's no default value for the field, use a static label.
1326 if (!$params['default_value']) {
1327 $params['default_value'] = '[Empty]';
1328 }
1329 $constantDefaultRow =
1330 '<div class="input-group defaultTS" id="' . $defaultTyposcriptID . '" ' . $defaultTyposcriptStyle . '>'
1331 . '<span class="input-group-btn">' . $editIconHTML . '</span>'
1332 . '<input class="form-control" type="text" placeholder="' . htmlspecialchars($params['default_value']) . '" readonly>'
1333 . '</div>';
1334 }
1335 $constantEditRow =
1336 '<div class="input-group userTS" id="' . $userTyposcriptID . '" ' . $userTyposcriptStyle . '>'
1337 . '<span class="input-group-btn">' . $deleteIconHTML . '</span>'
1338 . $p_field
1339 . '</div>';
1340 $constantLabel = '<label class="t3js-formengine-label"><span>' . htmlspecialchars($head) . '</span></label>';
1341 $constantName = '<span class="help-block">[' . $params['name'] . ']</span>';
1342 $constantDescription = $body ? '<p class="help-block">' . htmlspecialchars($body) . '</p>' : '';
1343 $constantData = '';
1344 if ($hint !== '') {
1345 $constantData .= '<span class="help-block">' . $hint . '</span>';
1346 }
1347 $constantData .=
1348 $constantCheckbox
1349 . $constantEditRow
1350 . $constantDefaultRow;
1351
1352 $output .=
1353 '<fieldset class="form-section">'
1354 . '<a name="' . $raname . '"></a>' . $help['constants'][$params['name']]
1355 . '<div class="form-group">'
1356 . $constantLabel . $constantName . $constantDescription . $constantData
1357 . '</div>'
1358 . '</fieldset>';
1359 } else {
1360 debug('Error. Constant did not exist. Should not happen.');
1361 }
1362 }
1363 }
1364 return '<div class="tstemplate-constanteditor">' . $output . '</div>';
1365 }
1366
1367 /***************************
1368 *
1369 * Processing input values
1370 *
1371 ***************************/
1372 /**
1373 * @param string $constants
1374 */
1375 public function ext_regObjectPositions($constants)
1376 {
1377 // This runs through the lines of the constants-field of the active template and registers the constants-names
1378 // and line positions in an array, $this->objReg
1379 $this->raw = explode(LF, $constants);
1380 $this->rawP = 0;
1381 // Resetting the objReg if the divider is found!!
1382 $this->objReg = [];
1383 $this->ext_regObjects('');
1384 }
1385
1386 /**
1387 * @param string $pre
1388 */
1389 public function ext_regObjects($pre)
1390 {
1391 // Works with regObjectPositions. "expands" the names of the TypoScript objects
1392 while (isset($this->raw[$this->rawP])) {
1393 $line = ltrim($this->raw[$this->rawP]);
1394 if (strstr($line, $this->edit_divider)) {
1395 // Resetting the objReg if the divider is found!!
1396 $this->objReg = [];
1397 }
1398 $this->rawP++;
1399 if ($line) {
1400 if ($line[0] === '[') {
1401 } elseif (strcspn($line, '}#/') != 0) {
1402 $varL = strcspn($line, ' {=<');
1403 $var = substr($line, 0, $varL);
1404 $line = ltrim(substr($line, $varL));
1405 switch ($line[0]) {
1406 case '=':
1407 $this->objReg[$pre . $var] = $this->rawP - 1;
1408 break;
1409 case '{':
1410 $this->ext_inBrace++;
1411 $this->ext_regObjects($pre . $var . '.');
1412 break;
1413 }
1414 $this->lastComment = '';
1415 } elseif ($line[0] === '}') {
1416 $this->lastComment = '';
1417 $this->ext_inBrace--;
1418 if ($this->ext_inBrace < 0) {
1419 $this->ext_inBrace = 0;
1420 } else {
1421 break;
1422 }
1423 }
1424 }
1425 }
1426 }
1427
1428 /**
1429 * @param string $key
1430 * @param string $var
1431 */
1432 public function ext_putValueInConf($key, $var)
1433 {
1434 // Puts the value $var to the TypoScript value $key in the current lines of the templates.
1435 // If the $key is not found in the template constants field, a new line is inserted in the bottom.
1436 $theValue = ' ' . trim($var);
1437 if (isset($this->objReg[$key])) {
1438 $lineNum = $this->objReg[$key];
1439 $parts = explode('=', $this->raw[$lineNum], 2);
1440 if (count($parts) === 2) {
1441 $parts[1] = $theValue;
1442 }
1443 $this->raw[$lineNum] = implode($parts, '=');
1444 } else {
1445 $this->raw[] = $key . ' =' . $theValue;
1446 }
1447 $this->changed = true;
1448 }
1449
1450 /**
1451 * @param string $key
1452 */
1453 public function ext_removeValueInConf($key)
1454 {
1455 // Removes the value in the configuration
1456 if (isset($this->objReg[$key])) {
1457 $lineNum = $this->objReg[$key];
1458 unset($this->raw[$lineNum]);
1459 }
1460 $this->changed = true;
1461 }
1462
1463 /**
1464 * @param array $arr
1465 * @param array $settings
1466 * @return array
1467 */
1468 public function ext_depthKeys($arr, $settings)
1469 {
1470 $tsbrArray = [];
1471 foreach ($arr as $theK => $theV) {
1472 $theKeyParts = explode('.', $theK);
1473 $depth = '';
1474 $c = count($theKeyParts);
1475 $a = 0;
1476 foreach ($theKeyParts as $p) {
1477 $a++;
1478 $depth .= ($depth ? '.' : '') . $p;
1479 $tsbrArray[$depth] = $c == $a ? $theV : 1;
1480 }
1481 }
1482 // Modify settings
1483 foreach ($tsbrArray as $theK => $theV) {
1484 if ($theV) {
1485 $settings[$theK] = 1;
1486 } else {
1487 unset($settings[$theK]);
1488 }
1489 }
1490 return $settings;
1491 }
1492
1493 /**
1494 * Process input
1495 *
1496 * @param array $http_post_vars
1497 * @param array $http_post_files (not used anymore)
1498 * @param array $theConstants
1499 * @param array $tplRow Not used
1500 */
1501 public function ext_procesInput($http_post_vars, $http_post_files, $theConstants, $tplRow)
1502 {
1503 $data = $http_post_vars['data'];
1504 $check = $http_post_vars['check'];
1505 $Wdata = $http_post_vars['Wdata'];
1506 $W2data = $http_post_vars['W2data'];
1507 $W3data = $http_post_vars['W3data'];
1508 $W4data = $http_post_vars['W4data'];
1509 $W5data = $http_post_vars['W5data'];
1510 if (is_array($data)) {
1511 foreach ($data as $key => $var) {
1512 if (isset($theConstants[$key])) {
1513 // If checkbox is set, update the value
1514 if ($this->ext_dontCheckIssetValues || isset($check[$key])) {
1515 // Exploding with linebreak, just to make sure that no multiline input is given!
1516 list($var) = explode(LF, $var);
1517 $typeDat = $this->ext_getTypeData($theConstants[$key]['type']);
1518 switch ($typeDat['type']) {
1519 case 'int':
1520 if ($typeDat['paramstr']) {
1521 $var = MathUtility::forceIntegerInRange($var, $typeDat['params'][0], $typeDat['params'][1]);
1522 } else {
1523 $var = (int)$var;
1524 }
1525 break;
1526 case 'int+':
1527 $var = max(0, (int)$var);
1528 break;
1529 case 'color':
1530 $col = [];
1531 if ($var) {
1532 $var = preg_replace('/[^A-Fa-f0-9]*/', '', $var);
1533 $useFulHex = strlen($var) > 3;
1534 $col[] = hexdec($var[0]);
1535 $col[] = hexdec($var[1]);
1536 $col[] = hexdec($var[2]);
1537 if ($useFulHex) {
1538 $col[] = hexdec($var[3]);
1539 $col[] = hexdec($var[4]);
1540 $col[] = hexdec($var[5]);
1541 }
1542 $var = substr(('0' . dechex($col[0])), -1) . substr(('0' . dechex($col[1])), -1) . substr(('0' . dechex($col[2])), -1);
1543 if ($useFulHex) {
1544 $var .= substr(('0' . dechex($col[3])), -1) . substr(('0' . dechex($col[4])), -1) . substr(('0' . dechex($col[5])), -1);
1545 }
1546 $var = '#' . strtoupper($var);
1547 }
1548 break;
1549 case 'comment':
1550 if ($var) {
1551 $var = '#';
1552 } else {
1553 $var = '';
1554 }
1555 break;
1556 case 'wrap':
1557 if (isset($Wdata[$key])) {
1558 $var .= '|' . $Wdata[$key];
1559 }
1560 break;
1561 case 'offset':
1562 if (isset($Wdata[$key])) {
1563 $var = (int)$var . ',' . (int)$Wdata[$key];
1564 if (isset($W2data[$key])) {
1565 $var .= ',' . (int)$W2data[$key];
1566 if (isset($W3data[$key])) {
1567 $var .= ',' . (int)$W3data[$key];
1568 if (isset($W4data[$key])) {
1569 $var .= ',' . (int)$W4data[$key];
1570 if (isset($W5data[$key])) {
1571 $var .= ',' . (int)$W5data[$key];
1572 }
1573 }
1574 }
1575 }
1576 }
1577 break;
1578 case 'boolean':
1579 if ($var) {
1580 $var = $typeDat['paramstr'] ? $typeDat['paramstr'] : 1;
1581 }
1582 break;
1583 }
1584 if ($this->ext_printAll || (string)$theConstants[$key]['value'] !== (string)$var) {
1585 // Put value in, if changed.
1586 $this->ext_putValueInConf($key, $var);
1587 }
1588 // Remove the entry because it has been "used"
1589 unset($check[$key]);
1590 } else {
1591 $this->ext_removeValueInConf($key);
1592 }
1593 }
1594 }
1595 }
1596 // Remaining keys in $check indicates fields that are just clicked "on" to be edited.
1597 // Therefore we get the default value and puts that in the template as a start...
1598 if (!$this->ext_dontCheckIssetValues && is_array($check)) {
1599 foreach ($check as $key => $var) {
1600 if (isset($theConstants[$key])) {
1601 $dValue = $theConstants[$key]['default_value'];
1602 $this->ext_putValueInConf($key, $dValue);
1603 }
1604 }
1605 }
1606 }
1607
1608 /**
1609 * @param int $id
1610 * @param string $perms_clause
1611 * @return array
1612 */
1613 public function ext_prevPageWithTemplate($id, $perms_clause)
1614 {
1615 $rootLine = BackendUtility::BEgetRootLine($id, $perms_clause ? ' AND ' . $perms_clause : '');
1616 foreach ($rootLine as $p) {
1617 if ($this->ext_getFirstTemplate($p['uid'])) {
1618 return $p;
1619 }
1620 }
1621 return [];
1622 }
1623
1624 /**
1625 * Is set by runThroughTemplates(), previously set via TemplateAnalyzerModuleFunctionController from the outside
1626 *
1627 * @return array
1628 */
1629 protected function getRootLine()
1630 {
1631 return is_array($this->absoluteRootLine) ? $this->absoluteRootLine : [];
1632 }
1633
1634 /**
1635 * @return LanguageService
1636 */
1637 protected function getLanguageService()
1638 {
1639 return $GLOBALS['LANG'];
1640 }
1641
1642 /**
1643 * @return DocumentTemplate
1644 */
1645 protected function getDocumentTemplate()
1646 {
1647 return $GLOBALS['TBE_TEMPLATE'];
1648 }
1649 }