AbstractFormElement.php 36.5 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Backend\Form\Element;

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

use TYPO3\CMS\Backend\Form\FormEngine;
18
use TYPO3\CMS\Backend\Form\DataPreprocessor;
19
20
use TYPO3\CMS\Backend\Template\DocumentTemplate;
use TYPO3\CMS\Lang\LanguageService;
21
22
23
24
25
26
27
28
29
30
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Backend\Utility\IconUtility;
use TYPO3\CMS\Backend\Form\Wizard\SuggestWizard;
use TYPO3\CMS\Backend\Form\Wizard\ValueSliderWizard;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Backend\Form\DatabaseFileIconsHookInterface;
use TYPO3\CMS\Backend\Clipboard\Clipboard;
Christian Kuhn's avatar
Christian Kuhn committed
31
32
use TYPO3\CMS\Backend\Form\AbstractNode;
use TYPO3\CMS\Backend\Form\InlineStackProcessor;
33
use TYPO3\CMS\Backend\Form\NodeFactory;
34
35

/**
Christian Kuhn's avatar
Christian Kuhn committed
36
 * Base class for form elements of FormEngine. Contains several helper methods used by single elements.
37
 */
Christian Kuhn's avatar
Christian Kuhn committed
38
abstract class AbstractFormElement extends AbstractNode {
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

	/**
	 * Default width value for a couple of elements like text
	 *
	 * @var int
	 */
	protected $defaultInputWidth = 30;

	/**
	 * Minimum width value for a couple of elements like text
	 *
	 * @var int
	 */
	protected $minimumInputWidth = 10;

	/**
	 * Maximum width value for a couple of elements like text
	 *
	 * @var int
58
	 */
59
60
61
62
63
64
	protected $maxInputWidth = 50;

	/**
	 * @var \TYPO3\CMS\Backend\Clipboard\Clipboard|NULL
	 */
	protected $clipboard = NULL;
65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
	/**
	 * @return bool TRUE if field is set to read only
	 */
	protected function isGlobalReadonly() {
		return !empty($this->globalOptions['renderReadonly']);
	}

	/**
	 * @return bool TRUE if wizards are disabled on a global level
	 */
	protected function isWizardsDisabled() {
		return !empty($this->globalOptions['disabledWizards']);
	}

	/**
	 * @return string URL to return to this entry script
	 */
	protected function getReturnUrl() {
		return isset($this->globalOptions['returnUrl']) ? $this->globalOptions['returnUrl'] : '';
	}

	/**
	 * Returns the max width in pixels for a elements like input and text
	 *
	 * @param int $size The abstract size value (1-48)
	 * @return int Maximum width in pixels
	 */
	protected function formMaxWidth($size = 48) {
		$compensationForLargeDocuments = 1.33;
		$compensationForFormFields = 12;

		$size = round($size * $compensationForLargeDocuments);
		return ceil($size * $compensationForFormFields);
	}

	/**
	 * Rendering wizards for form fields.
	 *
	 * @param array $itemKinds Array with the real item in the first value, and an alternative item in the second value.
	 * @param array $wizConf The "wizard" key from the config array for the field (from TCA)
	 * @param string $table Table name
	 * @param array $row The record array
	 * @param string $field The field name
	 * @param array $PA Additional configuration array.
	 * @param string $itemName The field name
	 * @param array $specConf Special configuration if available.
	 * @param bool $RTE Whether the RTE could have been loaded.
	 * @return string The new item value.
	 */
	protected function renderWizards($itemKinds, $wizConf, $table, $row, $field, $PA, $itemName, $specConf, $RTE = FALSE) {
		// Return not changed main item directly if wizards are disabled
		if (!is_array($wizConf) || $this->isWizardsDisabled()) {
			return $itemKinds[0];
		}

		$languageService = $this->getLanguageService();

		$fieldChangeFunc = $PA['fieldChangeFunc'];
		$item = $itemKinds[0];
		$fName = '[' . $table . '][' . $row['uid'] . '][' . $field . ']';
		$md5ID = 'ID' . GeneralUtility::shortmd5($itemName);
		$fieldConfig = $PA['fieldConf']['config'];
		$prefixOfFormElName = 'data[' . $table . '][' . $row['uid'] . '][' . $field . ']';
		$flexFormPath = '';
		if (GeneralUtility::isFirstPartOfStr($PA['itemFormElName'], $prefixOfFormElName)) {
			$flexFormPath = str_replace('][', '/', substr($PA['itemFormElName'], strlen($prefixOfFormElName) + 1, -1));
		}

		// Manipulate the field name (to be the TRUE form field name) and remove
		// a suffix-value if the item is a selector box with renderMode "singlebox":
		$listFlag = '_list';
Christian Kuhn's avatar
Christian Kuhn committed
137
		if ($PA['fieldConf']['config']['type'] == 'select') {
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
			// Single select situation:
			if ($PA['fieldConf']['config']['maxitems'] <= 1) {
				$listFlag = '';
			} elseif ($PA['fieldConf']['config']['renderMode'] == 'singlebox') {
				$itemName .= '[]';
				$listFlag = '';
			}
		}

		// Contains wizard identifiers enabled for this record type, see "special configuration" docs
		$wizardsEnabledByType = $specConf['wizards']['parameters'];

		$buttonWizards = array();
		$otherWizards = array();
		foreach ($wizConf as $wizardIdentifier => $wizardConfiguration) {
			// If an identifier starts with "_", this is a configuration option like _POSITION and not a wizard
			if ($wizardIdentifier[0] === '_') {
				continue;
			}

			// Sanitize wizard type
			$wizardConfiguration['type'] = (string)$wizardConfiguration['type'];

			// Wizards can be shown based on selected "type" of record. If this is the case, the wizard configuration
			// is set to enableByTypeConfig = 1, and the wizardIdentifier is found in $wizardsEnabledByType
			$wizardIsEnabled = TRUE;
			if (
				isset($wizardConfiguration['enableByTypeConfig'])
				&& (bool)$wizardConfiguration['enableByTypeConfig']
				&& (!is_array($wizardsEnabledByType) || !in_array($wizardIdentifier, $wizardsEnabledByType))
			) {
				$wizardIsEnabled = FALSE;
			}
			// Disable if wizard is for RTE fields only and the handled field is no RTE field or RTE can not be loaded
			if (isset($wizardConfiguration['RTEonly']) && (bool)$wizardConfiguration['RTEonly'] && !$RTE) {
				$wizardIsEnabled = FALSE;
			}
			// Disable if wizard is for not-new records only and we're handling a new record
			if (isset($wizardConfiguration['notNewRecords']) && $wizardConfiguration['notNewRecords'] && !MathUtility::canBeInterpretedAsInteger($row['uid'])) {
				$wizardIsEnabled = FALSE;
			}
			// Wizard types script, colorbox and popup must contain a module name configuration
			if (!isset($wizardConfiguration['module']['name']) && in_array($wizardConfiguration['type'], array('script', 'colorbox', 'popup'), TRUE)) {
				$wizardIsEnabled = FALSE;
			}

			if (!$wizardIsEnabled) {
				continue;
			}

			// Title / icon:
			$iTitle = htmlspecialchars($languageService->sL($wizardConfiguration['title']));
			if (isset($wizardConfiguration['icon'])) {
				$icon = FormEngineUtility::getIconHtml($wizardConfiguration['icon'], $iTitle, $iTitle);
			} else {
				$icon = $iTitle;
			}

			switch ($wizardConfiguration['type']) {
				case 'userFunc':
					$params = array();
					$params['fieldConfig'] = $fieldConfig;
					$params['params'] = $wizardConfiguration['params'];
					$params['exampleImg'] = $wizardConfiguration['exampleImg'];
					$params['table'] = $table;
					$params['uid'] = $row['uid'];
					$params['pid'] = $row['pid'];
					$params['field'] = $field;
					$params['flexFormPath'] = $flexFormPath;
					$params['md5ID'] = $md5ID;
					$params['returnUrl'] = $this->getReturnUrl();

					$params['formName'] = 'editform';
					$params['itemName'] = $itemName;
					$params['hmac'] = GeneralUtility::hmac($params['formName'] . $params['itemName'], 'wizard_js');
					$params['fieldChangeFunc'] = $fieldChangeFunc;
					$params['fieldChangeFuncHash'] = GeneralUtility::hmac(serialize($fieldChangeFunc));

					$params['item'] = &$item;
					$params['icon'] = $icon;
					$params['iTitle'] = $iTitle;
					$params['wConf'] = $wizardConfiguration;
					$params['row'] = $row;
					$formEngineDummy = new FormEngine;
					$otherWizards[] = GeneralUtility::callUserFunction($wizardConfiguration['userFunc'], $params, $formEngineDummy);
					break;

				case 'script':
					$params = array();
					// Including the full fieldConfig from TCA may produce too long an URL
					if ($wizardIdentifier != 'RTE') {
						$params['fieldConfig'] = $fieldConfig;
					}
					$params['params'] = $wizardConfiguration['params'];
					$params['exampleImg'] = $wizardConfiguration['exampleImg'];
					$params['table'] = $table;
					$params['uid'] = $row['uid'];
					$params['pid'] = $row['pid'];
					$params['field'] = $field;
					$params['flexFormPath'] = $flexFormPath;
					$params['md5ID'] = $md5ID;
					$params['returnUrl'] = $this->getReturnUrl();

					// Resolving script filename and setting URL.
					$urlParameters = array();
					if (isset($wizardConfiguration['module']['urlParameters']) && is_array($wizardConfiguration['module']['urlParameters'])) {
						$urlParameters = $wizardConfiguration['module']['urlParameters'];
					}
					$wScript = BackendUtility::getModuleUrl($wizardConfiguration['module']['name'], $urlParameters, '');
					$url = $wScript . (strstr($wScript, '?') ? '' : '?') . GeneralUtility::implodeArrayForUrl('', array('P' => $params));
					$buttonWizards[] =
						'<a class="btn btn-default" href="' . htmlspecialchars($url) . '" onclick="this.blur(); return !TBE_EDITOR.isFormChanged();">'
							. $icon .
						'</a>';
					break;

				case 'popup':
					$params = array();
					$params['fieldConfig'] = $fieldConfig;
					$params['params'] = $wizardConfiguration['params'];
					$params['exampleImg'] = $wizardConfiguration['exampleImg'];
					$params['table'] = $table;
					$params['uid'] = $row['uid'];
					$params['pid'] = $row['pid'];
					$params['field'] = $field;
					$params['flexFormPath'] = $flexFormPath;
					$params['md5ID'] = $md5ID;
					$params['returnUrl'] = $this->getReturnUrl();

					$params['formName'] = 'editform';
					$params['itemName'] = $itemName;
					$params['hmac'] = GeneralUtility::hmac($params['formName'] . $params['itemName'], 'wizard_js');
					$params['fieldChangeFunc'] = $fieldChangeFunc;
					$params['fieldChangeFuncHash'] = GeneralUtility::hmac(serialize($fieldChangeFunc));

					// Resolving script filename and setting URL.
					$urlParameters = array();
					if (isset($wizardConfiguration['module']['urlParameters']) && is_array($wizardConfiguration['module']['urlParameters'])) {
						$urlParameters = $wizardConfiguration['module']['urlParameters'];
					}
					$wScript = BackendUtility::getModuleUrl($wizardConfiguration['module']['name'], $urlParameters, '');
					$url = $wScript . (strstr($wScript, '?') ? '' : '?') . GeneralUtility::implodeArrayForUrl('', array('P' => $params));

					$onlyIfSelectedJS = '';
					if (isset($wizardConfiguration['popup_onlyOpenIfSelected']) && $wizardConfiguration['popup_onlyOpenIfSelected']) {
						$notSelectedText = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:mess.noSelItemForEdit');
						$onlyIfSelectedJS =
285
							'if (!TBE_EDITOR.curSelected(' . GeneralUtility::quoteJSvalue($itemName . $listFlag) . ')){' .
286
								'alert(' . GeneralUtility::quoteJSvalue($notSelectedText) . ');' .
287
288
								'return false;' .
							'}';
289
290
291
292
					}
					$aOnClick =
						'this.blur();' .
						$onlyIfSelectedJS .
293
294
						'vHWin=window.open(' . GeneralUtility::quoteJSvalue($url) . '+\'&P[currentValue]=\'+TBE_EDITOR.rawurlencode(' .
								'document.editform[' . GeneralUtility::quoteJSvalue($itemName) . '].value,200' .
295
							')' .
296
297
298
							'+\'&P[currentSelectedValues]=\'+TBE_EDITOR.curSelected(' . GeneralUtility::quoteJSvalue($itemName . $listFlag) . '),' .
							GeneralUtility::quoteJSvalue('popUp' . $md5ID) . ',' .
							GeneralUtility::quoteJSvalue($wizardConfiguration['JSopenParams']) .
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
						');' .
						'vHWin.focus();' .
						'return false;';

					$buttonWizards[] =
						'<a class="btn btn-default" href="#" onclick="' . htmlspecialchars($aOnClick) . '">' .
							$icon .
						'</a>';
					break;

				case 'colorbox':
					$params = array();
					$params['fieldConfig'] = $fieldConfig;
					$params['params'] = $wizardConfiguration['params'];
					$params['exampleImg'] = $wizardConfiguration['exampleImg'];
					$params['table'] = $table;
					$params['uid'] = $row['uid'];
					$params['pid'] = $row['pid'];
					$params['field'] = $field;
					$params['flexFormPath'] = $flexFormPath;
					$params['md5ID'] = $md5ID;
					$params['returnUrl'] = $this->getReturnUrl();

					$params['formName'] = 'editform';
					$params['itemName'] = $itemName;
					$params['hmac'] = GeneralUtility::hmac($params['formName'] . $params['itemName'], 'wizard_js');
					$params['fieldChangeFunc'] = $fieldChangeFunc;
					$params['fieldChangeFuncHash'] = GeneralUtility::hmac(serialize($fieldChangeFunc));

					// Resolving script filename and setting URL.
					$urlParameters = array();
					if (isset($wizardConfiguration['module']['urlParameters']) && is_array($wizardConfiguration['module']['urlParameters'])) {
						$urlParameters = $wizardConfiguration['module']['urlParameters'];
					}
					$wScript = BackendUtility::getModuleUrl($wizardConfiguration['module']['name'], $urlParameters, '');
					$url = $wScript . (strstr($wScript, '?') ? '' : '?') . GeneralUtility::implodeArrayForUrl('', array('P' => $params));

					$aOnClick =
						'this.blur();' .
338
						'vHWin=window.open('. GeneralUtility::quoteJSvalue($url) . '+\'&P[currentValue]=\'+TBE_EDITOR.rawurlencode(' .
339
340
							'document.editform[\'' . $itemName . '\'].value,200' .
							')' .
341
342
343
							'+\'&P[currentSelectedValues]=\'+TBE_EDITOR.curSelected(' . GeneralUtility::quoteJSvalue($itemName . $listFlag) . '),' .
							GeneralUtility::quoteJSvalue('popUp' . $md5ID) . ',' .
							GeneralUtility::quoteJSvalue($wizardConfiguration['JSopenParams']) .
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
						');' .
						'vHWin.focus();' .
						'return false;';

					$dim = GeneralUtility::intExplode('x', $wizardConfiguration['dim']);
					$dX = MathUtility::forceIntegerInRange($dim[0], 1, 200, 20);
					$dY = MathUtility::forceIntegerInRange($dim[1], 1, 200, 20);
					$color = $PA['itemFormElValue'] ? ' bgcolor="' . htmlspecialchars($PA['itemFormElValue']) . '"' : '';
					$skinImg = IconUtility::skinImg(
						'',
						$PA['itemFormElValue'] === '' ? 'gfx/colorpicker_empty.png' : 'gfx/colorpicker.png',
						'width="' . $dX . '" height="' . $dY . '"' . BackendUtility::titleAltAttrib(trim($iTitle . ' ' . $PA['itemFormElValue'])) . ' border="0"'
					);
					$otherWizards[] =
						'<table border="0" id="' . $md5ID . '"' . $color . ' style="' . htmlspecialchars($wizardConfiguration['tableStyle']) . '">' .
							'<tr>' .
								'<td>' .
									'<a class="btn btn-default" href="#" onclick="' . htmlspecialchars($aOnClick) . '">' . '<img ' . $skinImg . '>' . '</a>' .
								'</td>' .
							'</tr>' .
						'</table>';
					break;

				case 'slider':
					$params = array();
					$params['fieldConfig'] = $fieldConfig;
					$params['field'] = $field;
					$params['flexFormPath'] = $flexFormPath;
					$params['md5ID'] = $md5ID;
					$params['itemName'] = $itemName;
					$params['fieldChangeFunc'] = $fieldChangeFunc;
					$params['wConf'] = $wizardConfiguration;
					$params['row'] = $row;

					/** @var ValueSliderWizard $wizard */
					$wizard = GeneralUtility::makeInstance(ValueSliderWizard::class);
					$otherWizards[] = $wizard->renderWizard($params);
					break;

				case 'select':
					$fieldValue = array('config' => $wizardConfiguration);
					$TSconfig = FormEngineUtility::getTSconfigForTableRow($table, $row);
					$TSconfig[$field] = $TSconfig[$field]['wizards.'][$wizardIdentifier . '.'];
					$selItems = FormEngineUtility::addSelectOptionsToItemArray(FormEngineUtility::initItemArray($fieldValue), $fieldValue, $TSconfig, $field);
					// Process items by a user function:
					if (!empty($wizardConfiguration['itemsProcFunc'])) {
						$funcConfig = !empty($wizardConfiguration['itemsProcFunc.']) ? $wizardConfiguration['itemsProcFunc.'] : array();
						$dataPreprocessor = GeneralUtility::makeInstance(DataPreprocessor::class);
						$selItems = $dataPreprocessor->procItems($selItems, $funcConfig, $wizardConfiguration, $table, $row, $field);
					}
					$options = array();
					$options[] = '<option>' . $iTitle . '</option>';
					foreach ($selItems as $p) {
						$options[] = '<option value="' . htmlspecialchars($p[1]) . '">' . htmlspecialchars($p[0]) . '</option>';
					}
					if ($wizardConfiguration['mode'] == 'append') {
400
						$assignValue = 'document.editform[' . GeneralUtility::quoteJSvalue($itemName) . '].value=\'\'+this.options[this.selectedIndex].value+document.editform[' . GeneralUtility::quoteJSvalue($itemName) . '].value';
401
					} elseif ($wizardConfiguration['mode'] == 'prepend') {
402
						$assignValue = 'document.editform[' . GeneralUtility::quoteJSvalue($itemName) . '].value+=\'\'+this.options[this.selectedIndex].value';
403
					} else {
404
						$assignValue = 'document.editform[' . GeneralUtility::quoteJSvalue($itemName) . '].value=this.options[this.selectedIndex].value';
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
					}
					$otherWizards[] =
						'<select' .
							' id="' . str_replace('.', '', uniqid('tceforms-select-', TRUE)) . '"' .
							' class="form-control tceforms-select tceforms-wizardselect"' .
							' name="_WIZARD' . $fName . '"' .
							' onchange="' . htmlspecialchars($assignValue . ';this.blur();this.selectedIndex=0;' . implode('', $fieldChangeFunc)) . '"'.
						'>' .
							implode('', $options) .
						'</select>';
					break;
				case 'suggest':
					if (!empty($PA['fieldTSConfig']['suggest.']['default.']['hide'])) {
						break;
					}
					/** @var SuggestWizard $suggestWizard */
					$suggestWizard = GeneralUtility::makeInstance(SuggestWizard::class);
					$otherWizards[] = $suggestWizard->renderSuggestSelector($PA['itemFormElName'], $table, $field, $row, $PA);
					break;
			}

			// Hide the real form element?
			if (is_array($wizardConfiguration['hideParent']) || $wizardConfiguration['hideParent']) {
				// Setting the item to a hidden-field.
				$item = $itemKinds[1];
				if (is_array($wizardConfiguration['hideParent'])) {
431
432
					$options = $this->globalOptions;
					$options['parameterArray'] = array(
433
434
435
436
437
						'fieldConf' => array(
							'config' => $wizardConfiguration['hideParent'],
						),
						'itemFormElValue' => $PA['itemFormElValue'],
					);
438
					$options['renderType'] = 'none';
439
440
441
					/** @var NodeFactory $nodeFactory */
					$nodeFactory = $this->globalOptions['nodeFactory'];
					$noneElementResult = $nodeFactory->create($options)->render();
Christian Kuhn's avatar
Christian Kuhn committed
442
					$item .= $noneElementResult['html'];
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
				}
			}
		}

		// For each rendered wizard, put them together around the item.
		if (!empty($buttonWizards) || !empty($otherWizards)) {
			if ($wizConf['_HIDDENFIELD']) {
				$item = $itemKinds[1];
			}

			$innerContent = '';
			if (!empty($buttonWizards)) {
				$innerContent .= '<div class="btn-group' . ($wizConf['_VERTICAL'] ? ' btn-group-vertical' : '') . '">' . implode('', $buttonWizards) . '</div>';
			}
			$innerContent .= implode(' ', $otherWizards);

			// Position
			$classes = array('form-wizards-wrap');
			if ($wizConf['_POSITION'] === 'left') {
				$classes[] = 'form-wizards-aside';
				$innerContent = '<div class="form-wizards-items">' . $innerContent . '</div><div class="form-wizards-element">' . $item . '</div>';
			} elseif ($wizConf['_POSITION'] === 'top') {
				$classes[] = 'form-wizards-top';
				$innerContent = '<div class="form-wizards-items">' . $innerContent . '</div><div class="form-wizards-element">' . $item . '</div>';
			} elseif ($wizConf['_POSITION'] === 'bottom') {
				$classes[] = 'form-wizards-bottom';
				$innerContent = '<div class="form-wizards-element">' . $item . '</div><div class="form-wizards-items">' . $innerContent . '</div>';
			} else {
				$classes[] = 'form-wizards-aside';
				$innerContent = '<div class="form-wizards-element">' . $item . '</div><div class="form-wizards-items">' . $innerContent . '</div>';
			}
			$item = '
				<div class="' . implode(' ', $classes) . '">
					' . $innerContent . '
				</div>';
		}

		return $item;
	}

	/**
	 * Prints the selector box form-field for the db/file/select elements (multiple)
	 *
	 * @param string $fName Form element name
	 * @param string $mode Mode "db", "file" (internal_type for the "group" type) OR blank (then for the "select" type)
	 * @param string $allowed Commalist of "allowed
	 * @param array $itemArray The array of items. For "select" and "group"/"file" this is just a set of value. For "db" its an array of arrays with table/uid pairs.
	 * @param string $selector Alternative selector box.
	 * @param array $params An array of additional parameters, eg: "size", "info", "headers" (array with "selector" and "items"), "noBrowser", "thumbnails
	 * @param string $onFocus On focus attribute string
	 * @param string $table (optional) Table name processing for
	 * @param string $field (optional) Field of table name processing for
	 * @param string $uid (optional) uid of table record processing for
	 * @param array $config (optional) The TCA field config
	 * @return string The form fields for the selection.
	 * @throws \UnexpectedValueException
	 */
	protected function dbFileIcons($fName, $mode, $allowed, $itemArray, $selector = '', $params = array(), $onFocus = '', $table = '', $field = '', $uid = '', $config = array()) {
		$languageService = $this->getLanguageService();
		$disabled = '';
		if ($this->isGlobalReadonly() || $params['readOnly']) {
			$disabled = ' disabled="disabled"';
		}
		// INIT
		$uidList = array();
		$opt = array();
		$itemArrayC = 0;
		// Creating <option> elements:
		if (is_array($itemArray)) {
			$itemArrayC = count($itemArray);
			switch ($mode) {
				case 'db':
					foreach ($itemArray as $pp) {
						$pRec = BackendUtility::getRecordWSOL($pp['table'], $pp['id']);
						if (is_array($pRec)) {
							$pTitle = BackendUtility::getRecordTitle($pp['table'], $pRec, FALSE, TRUE);
							$pUid = $pp['table'] . '_' . $pp['id'];
							$uidList[] = $pUid;
							$title = htmlspecialchars($pTitle);
							$opt[] = '<option value="' . htmlspecialchars($pUid) . '" title="' . $title . '">' . $title . '</option>';
						}
					}
					break;
				case 'file_reference':

				case 'file':
					foreach ($itemArray as $item) {
						$itemParts = explode('|', $item);
						$uidList[] = ($pUid = ($pTitle = $itemParts[0]));
						$title = htmlspecialchars(rawurldecode($itemParts[1]));
						$opt[] = '<option value="' . htmlspecialchars(rawurldecode($itemParts[0])) . '" title="' . $title . '">' . $title . '</option>';
					}
					break;
				case 'folder':
					foreach ($itemArray as $pp) {
						$pParts = explode('|', $pp);
						$uidList[] = ($pUid = ($pTitle = $pParts[0]));
						$title = htmlspecialchars(rawurldecode($pParts[0]));
						$opt[] = '<option value="' . htmlspecialchars(rawurldecode($pParts[0])) . '" title="' . $title . '">' . $title . '</option>';
					}
					break;
				default:
					foreach ($itemArray as $pp) {
						$pParts = explode('|', $pp, 2);
						$uidList[] = ($pUid = $pParts[0]);
						$pTitle = $pParts[1];
						$title = htmlspecialchars(rawurldecode($pTitle));
						$opt[] = '<option value="' . htmlspecialchars(rawurldecode($pUid)) . '" title="' . $title . '">' . $title . '</option>';
					}
			}
		}
		// Create selector box of the options
		$sSize = $params['autoSizeMax']
			? MathUtility::forceIntegerInRange($itemArrayC + 1, MathUtility::forceIntegerInRange($params['size'], 1), $params['autoSizeMax'])
			: $params['size'];
		if (!$selector) {
			$isMultiple = $params['maxitems'] != 1 && $params['size'] != 1;
			$selector = '<select id="' . str_replace('.', '', uniqid('tceforms-multiselect-', TRUE)) . '" '
				. ($params['noList'] ? 'style="display: none"' : 'size="' . $sSize . '" class="form-control tceforms-multiselect"')
				. ($isMultiple ? ' multiple="multiple"' : '')
				. ' name="' . $fName . '_list" ' . $onFocus . $params['style'] . $disabled . '>' . implode('', $opt)
				. '</select>';
		}
		$icons = array(
			'L' => array(),
			'R' => array()
		);
		$rOnClickInline = '';
		if (!$params['readOnly'] && !$params['noList']) {
			if (!$params['noBrowser']) {
				// Check against inline uniqueness
Christian Kuhn's avatar
Christian Kuhn committed
574
575
576
577
				/** @var InlineStackProcessor $inlineStackProcessor */
				$inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
				$inlineStackProcessor->initializeByGivenStructure($this->globalOptions['inlineStructure']);
				$inlineParent = $inlineStackProcessor->getStructureLevel(-1);
578
579
580
				$aOnClickInline = '';
				if (is_array($inlineParent) && $inlineParent['uid']) {
					if ($inlineParent['config']['foreign_table'] == $table && $inlineParent['config']['foreign_unique'] == $field) {
Christian Kuhn's avatar
Christian Kuhn committed
581
						$objectPrefix = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->globalOptions['inlineFirstPid']) . '-' . $table;
582
						$aOnClickInline = $objectPrefix . '|inline.checkUniqueElement|inline.setUniqueElement';
583
						$rOnClickInline = 'inline.revertUnique(' . GeneralUtility::quoteJSvalue($objectPrefix) . ',null,' . GeneralUtility::quoteJSvalue($uid) . ');';
584
585
586
587
588
589
590
591
592
593
594
595
					}
				}
				if (is_array($config['appearance']) && isset($config['appearance']['elementBrowserType'])) {
					$elementBrowserType = $config['appearance']['elementBrowserType'];
				} else {
					$elementBrowserType = $mode;
				}
				if (is_array($config['appearance']) && isset($config['appearance']['elementBrowserAllowed'])) {
					$elementBrowserAllowed = $config['appearance']['elementBrowserAllowed'];
				} else {
					$elementBrowserAllowed = $allowed;
				}
596
597
				$aOnClick = 'setFormValueOpenBrowser(' . GeneralUtility::quoteJSvalue($elementBrowserType) . ','
					. GeneralUtility::quoteJSvalue(($fName . '|||' . $elementBrowserAllowed . '|' . $aOnClickInline)) . '); return false;';
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
				$icons['R'][] = '
					<a href="#"
						onclick="' . htmlspecialchars($aOnClick) . '"
						class="btn btn-default"
						title="' . htmlspecialchars($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.browse_' . ($mode == 'db' ? 'db' : 'file'))) . '">
						' . IconUtility::getSpriteIcon('actions-insert-record') . '
					</a>';
			}
			if (!$params['dontShowMoveIcons']) {
				if ($sSize >= 5) {
					$icons['L'][] = '
						<a href="#"
							class="btn btn-default t3-btn-moveoption-top"
							data-fieldname="' . $fName . '"
							title="' . htmlspecialchars($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.move_to_top')) . '">
							' . IconUtility::getSpriteIcon('actions-move-to-top') . '
						</a>';

				}
				$icons['L'][] = '
					<a href="#"
						class="btn btn-default t3-btn-moveoption-up"
						data-fieldname="' . $fName . '"
						title="' . htmlspecialchars($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.move_up')) . '">
						' . IconUtility::getSpriteIcon('actions-move-up') . '
					</a>';
				$icons['L'][] = '
					<a href="#"
						class="btn btn-default t3-btn-moveoption-down"
						data-fieldname="' . $fName . '"
						title="' . htmlspecialchars($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.move_down')) . '">
						' . IconUtility::getSpriteIcon('actions-move-down') . '
					</a>';
				if ($sSize >= 5) {
					$icons['L'][] = '
						<a href="#"
							class="btn btn-default t3-btn-moveoption-bottom"
							data-fieldname="' . $fName . '"
							title="' . htmlspecialchars($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.move_to_bottom')) . '">
							' . IconUtility::getSpriteIcon('actions-move-to-bottom') . '
						</a>';
				}
			}
			$clipElements = $this->getClipboardElements($allowed, $mode);
			if (count($clipElements)) {
				$aOnClick = '';
				foreach ($clipElements as $elValue) {
					if ($mode == 'db') {
						list($itemTable, $itemUid) = explode('|', $elValue);
						$recordTitle = BackendUtility::getRecordTitle($itemTable, BackendUtility::getRecordWSOL($itemTable, $itemUid));
						$itemTitle = GeneralUtility::quoteJSvalue($recordTitle);
						$elValue = $itemTable . '_' . $itemUid;
					} else {
						// 'file', 'file_reference' and 'folder' mode
652
						$itemTitle = 'unescape(' . GeneralUtility::quoteJSvalue(rawurlencode(basename($elValue))) . ')';
653
					}
654
655
					$aOnClick .= 'setFormValueFromBrowseWin(' . GeneralUtility::quoteJSvalue($fName) . ',unescape('
						. GeneralUtility::quoteJSvalue(rawurlencode(str_replace('%20', ' ', $elValue))) . '),' . $itemTitle . ',' . $itemTitle . ');';
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
				}
				$aOnClick .= 'return false;';
				$icons['R'][] = '
					<a href="#"
						onclick="' . htmlspecialchars($aOnClick) . '"
						title="' . htmlspecialchars(sprintf($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.clipInsert_' . ($mode == 'db' ? 'db' : 'file')), count($clipElements))) . '">
						' . IconUtility::getSpriteIcon('actions-document-paste-into') . '
					</a>';
			}
		}
		if (!$params['readOnly'] && !$params['noDelete']) {
			$icons['L'][] = '
				<a href="#"
					class="btn btn-default t3-btn-removeoption"
					onClick="' . $rOnClickInline . '"
					data-fieldname="' . $fName . '"
					title="' . htmlspecialchars($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.remove_selected')) . '">
					' . IconUtility::getSpriteIcon('actions-selection-delete') . '
				</a>';
		}

		// Thumbnails
		$imagesOnly = FALSE;
		if ($params['thumbnails'] && $params['allowed']) {
			// In case we have thumbnails, check if only images are allowed.
			// In this case, render them below the field, instead of to the right
			$allowedExtensionList = $params['allowed'];
			$imageExtensionList = GeneralUtility::trimExplode(',', strtolower($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']), TRUE);
			$imagesOnly = TRUE;
			foreach ($allowedExtensionList as $allowedExtension) {
				if (!ArrayUtility::inArray($imageExtensionList, $allowedExtension)) {
					$imagesOnly = FALSE;
					break;
				}
			}
		}
		$thumbnails = '';
		if (is_array($params['thumbnails']) && !empty($params['thumbnails'])) {
			if ($imagesOnly) {
				$thumbnails .= '<ul class="list-inline">';
				foreach ($params['thumbnails'] as $thumbnail) {
					$thumbnails .= '<li><span class="thumbnail">' . $thumbnail['image'] . '</span></li>';
				}
				$thumbnails .= '</ul>';
			} else {
				$thumbnails .= '<div class="table-fit"><table class="table table-white"><tbody>';
				foreach ($params['thumbnails'] as $thumbnail) {
					$thumbnails .= '
						<tr>
							<td class="col-icon">
								' . ($config['internal_type'] === 'db'
							? $this->getControllerDocumentTemplate()->wrapClickMenuOnIcon($thumbnail['image'], $thumbnail['table'], $thumbnail['uid'], 1, '', '+copy,info,edit,view')
							: $thumbnail['image']) . '
							</td>
							<td class="col-title">
								' . ($config['internal_type'] === 'db'
							? $this->getControllerDocumentTemplate()->wrapClickMenuOnIcon($thumbnail['name'], $thumbnail['table'], $thumbnail['uid'], 1, '', '+copy,info,edit,view')
							: $thumbnail['name']) . '
714
								' . ($config['internal_type'] === 'db' ? ' <span class="text-muted">[' . $thumbnail['uid'] . ']</span>' : '') . '
715
716
717
718
719
720
721
722
723
724
725
726
727
728
							</td>
						</tr>
						';
				}
				$thumbnails .= '</tbody></table></div>';
			}
		}

		// Allowed Tables
		$allowedTables = '';
		if (is_array($params['allowedTables']) && !empty($params['allowedTables'])) {
			$allowedTables .= '<div class="help-block">';
			foreach ($params['allowedTables'] as $key => $item) {
				if (is_array($item)) {
729
730
731
732
733
					if (empty($params['readOnly'])) {
						$allowedTables .= '<a href="#" onClick="' . htmlspecialchars($item['onClick']) . '" class="btn btn-default">' . $item['icon'] . ' ' . htmlspecialchars($item['name']) . '</a> ';
					} else {
						$allowedTables .= '<span>' . htmlspecialchars($item['name']) . '</span> ';
					}
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
				} elseif($key === 'name') {
					$allowedTables .= '<span>' . htmlspecialchars($item) . '</span> ';
				}
			}
			$allowedTables .= '</div>';
		}
		// Allowed
		$allowedList = '';
		if (is_array($params['allowed']) && !empty($params['allowed'])) {
			foreach ($params['allowed'] as $item) {
				$allowedList .= '<span class="label label-success">' . strtoupper($item) . '</span> ';
			}
		}
		// Disallowed
		$disallowedList = '';
		if (is_array($params['disallowed']) && !empty($params['disallowed'])) {
			foreach ($params['disallowed'] as $item) {
				$disallowedList .= '<span class="label label-danger">' . strtoupper($item) . '</span> ';
			}
		}
		// Rightbox
		$rightbox = ($params['rightbox'] ?: '');

		// Hook: dbFileIcons_postProcess (requested by FAL-team for use with the "fal" extension)
		if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['dbFileIcons'])) {
			foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['dbFileIcons'] as $classRef) {
				$hookObject = GeneralUtility::getUserObj($classRef);
				if (!$hookObject instanceof DatabaseFileIconsHookInterface) {
					throw new \UnexpectedValueException('$hookObject must implement interface ' . DatabaseFileIconsHookInterface::class, 1290167704);
				}
				$additionalParams = array(
					'mode' => $mode,
					'allowed' => $allowed,
					'itemArray' => $itemArray,
					'onFocus' => $onFocus,
					'table' => $table,
					'field' => $field,
					'uid' => $uid,
					'config' => $GLOBALS['TCA'][$table]['columns'][$field]
				);
				$hookObject->dbFileIcons_postProcess($params, $selector, $thumbnails, $icons, $rightbox, $fName, $uidList, $additionalParams, $this);
			}
		}

		// Output
		$str = '
			' . ($params['headers']['selector'] ? '<label>' . $params['headers']['selector'] . '</label>' : '') . '
			<div class="form-wizards-wrap form-wizards-aside">
				<div class="form-wizards-element">
					' . $selector . '
					' . (!$params['noList'] && !empty($allowedTables) ? $allowedTables : '') . '
					' . (!$params['noList'] && (!empty($allowedList) || !empty($disallowedList))
				? '<div class="help-block">' . $allowedList . $disallowedList . ' </div>'
				: '') . '
				</div>
				' . (!empty($icons['L']) ? '<div class="form-wizards-items"><div class="btn-group-vertical">' . implode('', $icons['L']) . '</div></div>' : '' ) . '
				' . (!empty($icons['R']) ? '<div class="form-wizards-items"><div class="btn-group-vertical">' . implode('', $icons['R']) . '</div></div>' : '' ) . '
			</div>
			';
		if ($rightbox) {
			$str = '
				<div class="form-multigroup-wrap t3js-formengine-field-group">
					<div class="form-multigroup-item form-multigroup-element">' . $str . '</div>
					<div class="form-multigroup-item form-multigroup-element">
						' . ($params['headers']['items'] ? '<label>' . $params['headers']['items'] . '</label>' : '') . '
						' . ($params['headers']['selectorbox'] ? '<div class="form-multigroup-item-wizard">' . $params['headers']['selectorbox'] . '</div>' : '') . '
						' . $rightbox . '
					</div>
				</div>
				';
		}
		$str .= $thumbnails;

		// Creating the hidden field which contains the actual value as a comma list.
		$str .= '<input type="hidden" name="' . $fName . '" value="' . htmlspecialchars(implode(',', $uidList)) . '" />';
		return $str;
	}

	/**
	 * Returns array of elements from clipboard to insert into GROUP element box.
	 *
	 * @param string $allowed Allowed elements, Eg "pages,tt_content", "gif,jpg,jpeg,png
	 * @param string $mode Mode of relations: "db" or "file
	 * @return array Array of elements in values (keys are insignificant), if none found, empty array.
	 */
	protected function getClipboardElements($allowed, $mode) {
		if (!is_object($this->clipboard)) {
			$this->clipboard = GeneralUtility::makeInstance(Clipboard::class);
			$this->clipboard->initializeClipboard();
		}

		$output = array();
		switch ($mode) {
			case 'file_reference':

			case 'file':
				$elFromTable = $this->clipboard->elFromTable('_FILE');
				$allowedExts = GeneralUtility::trimExplode(',', $allowed, TRUE);
				// If there are a set of allowed extensions, filter the content:
				if ($allowedExts) {
					foreach ($elFromTable as $elValue) {
						$pI = pathinfo($elValue);
						$ext = strtolower($pI['extension']);
						if (in_array($ext, $allowedExts)) {
							$output[] = $elValue;
						}
					}
				} else {
					// If all is allowed, insert all: (This does NOT respect any disallowed extensions,
					// but those will be filtered away by the backend TCEmain)
					$output = $elFromTable;
				}
				break;
			case 'db':
				$allowedTables = GeneralUtility::trimExplode(',', $allowed, TRUE);
				// All tables allowed for relation:
				if (trim($allowedTables[0]) === '*') {
					$output = $this->clipboard->elFromTable('');
				} else {
					// Only some tables, filter them:
					foreach ($allowedTables as $tablename) {
						$elFromTable = $this->clipboard->elFromTable($tablename);
						$output = array_merge($output, $elFromTable);
					}
				}
				$output = array_keys($output);
				break;
		}

		return $output;
	}

866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
	/**
	 * @return LanguageService
	 */
	protected function getLanguageService() {
		return $GLOBALS['LANG'];
	}

	/**
	 * @return DocumentTemplate
	 */
	protected function getControllerDocumentTemplate() {
		// $GLOBALS['SOBE'] might be any kind of PHP class (controller most of the times)
		// These classes do not inherit from any common class, but they all seem to have a "doc" member
		return $GLOBALS['SOBE']->doc;
	}
881

882
}