[BUGFIX] backend formfields: Make boolean fields UI working in Edge/IE
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Element / InputLinkElement.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form\Element;
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\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Imaging\Icon;
19 use TYPO3\CMS\Core\LinkHandling\Exception\UnknownLinkHandlerException;
20 use TYPO3\CMS\Core\LinkHandling\LinkService;
21 use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
22 use TYPO3\CMS\Core\Resource\Exception\FolderDoesNotExistException;
23 use TYPO3\CMS\Core\Resource\File;
24 use TYPO3\CMS\Core\Resource\Folder;
25 use TYPO3\CMS\Core\Utility\GeneralUtility;
26 use TYPO3\CMS\Core\Utility\MathUtility;
27 use TYPO3\CMS\Core\Utility\StringUtility;
28 use TYPO3\CMS\Frontend\Service\TypoLinkCodecService;
29 use TYPO3\CMS\Lang\LanguageService;
30
31 /**
32 * Link input element.
33 *
34 * Shows current link and the link popup.
35 */
36 class InputLinkElement extends AbstractFormElement
37 {
38 /**
39 * Default field controls render the link icon
40 *
41 * @var array
42 */
43 protected $defaultFieldControl = [
44 'linkPopup' => [
45 'renderType' => 'linkPopup',
46 'options' => []
47 ],
48 ];
49
50 /**
51 * Default field wizards enabled for this element.
52 *
53 * @var array
54 */
55 protected $defaultFieldWizard = [
56 'localizationStateSelector' => [
57 'renderType' => 'localizationStateSelector',
58 ],
59 'otherLanguageContent' => [
60 'renderType' => 'otherLanguageContent',
61 'after' => [
62 'localizationStateSelector'
63 ],
64 ],
65 'defaultLanguageDifferences' => [
66 'renderType' => 'defaultLanguageDifferences',
67 'after' => [
68 'otherLanguageContent',
69 ],
70 ],
71 ];
72
73 /**
74 * This will render a single-line input form field, possibly with various control/validation features
75 *
76 * @return array As defined in initializeResultArray() of AbstractNode
77 */
78 public function render()
79 {
80 $languageService = $this->getLanguageService();
81
82 $table = $this->data['tableName'];
83 $fieldName = $this->data['fieldName'];
84 $row = $this->data['databaseRow'];
85 $parameterArray = $this->data['parameterArray'];
86 $resultArray = $this->initializeResultArray();
87 $config = $parameterArray['fieldConf']['config'];
88
89 $itemValue = $parameterArray['itemFormElValue'];
90 $evalList = GeneralUtility::trimExplode(',', $config['eval'], true);
91 $size = MathUtility::forceIntegerInRange($config['size'] ?? $this->defaultInputWidth, $this->minimumInputWidth, $this->maxInputWidth);
92 $width = (int)$this->formMaxWidth($size);
93 $nullControlNameEscaped = htmlspecialchars('control[active][' . $table . '][' . $row['uid'] . '][' . $fieldName . ']');
94
95 if ($config['readOnly']) {
96 // Early return for read only fields
97 $html = [];
98 $html[] = '<div class="formengine-field-item t3js-formengine-field-item">';
99 $html[] = '<div class="form-wizards-wrap">';
100 $html[] = '<div class="form-wizards-element">';
101 $html[] = '<div class="form-control-wrap" style="max-width: ' . $width . 'px">';
102 $html[] = '<input class="form-control" value="' . htmlspecialchars($itemValue) . '" type="text" disabled>';
103 $html[] = '</div>';
104 $html[] = '</div>';
105 $html[] = '</div>';
106 $html[] = '</div>';
107 $resultArray['html'] = implode(LF, $html);
108 return $resultArray;
109 }
110
111 // @todo: The whole eval handling is a mess and needs refactoring
112 foreach ($evalList as $func) {
113 // @todo: This is ugly: The code should find out on it's own whether a eval definition is a
114 // @todo: keyword like "date", or a class reference. The global registration could be dropped then
115 // Pair hook to the one in \TYPO3\CMS\Core\DataHandling\DataHandler::checkValue_input_Eval()
116 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
117 if (class_exists($func)) {
118 $evalObj = GeneralUtility::makeInstance($func);
119 if (method_exists($evalObj, 'deevaluateFieldValue')) {
120 $_params = [
121 'value' => $itemValue
122 ];
123 $itemValue = $evalObj->deevaluateFieldValue($_params);
124 }
125 if (method_exists($evalObj, 'returnFieldJS')) {
126 $resultArray['additionalJavaScriptPost'][] = 'TBE_EDITOR.customEvalFunctions[' . GeneralUtility::quoteJSvalue($func) . ']'
127 . ' = function(value) {' . $evalObj->returnFieldJS() . '};';
128 }
129 }
130 }
131 }
132
133 $attributes = [
134 'value' => '',
135 'id' => StringUtility::getUniqueId('formengine-input-'),
136 'class' => implode(' ', [
137 'form-control',
138 't3js-clearable',
139 't3js-form-field-inputlink-input',
140 'hidden',
141 'hasDefaultValue',
142 ]),
143 'data-formengine-validation-rules' => $this->getValidationDataAsJsonString($config),
144 'data-formengine-input-params' => json_encode([
145 'field' => $parameterArray['itemFormElName'],
146 'evalList' => implode(',', $evalList)
147 ]),
148 'data-formengine-input-name' => $parameterArray['itemFormElName'],
149 ];
150
151 $maxLength = $config['max'] ?? 0;
152 if ((int)$maxLength > 0) {
153 $attributes['maxlength'] = (int)$maxLength;
154 }
155 if (!empty($config['placeholder'])) {
156 $attributes['placeholder'] = trim($config['placeholder']);
157 }
158 if (isset($config['autocomplete'])) {
159 $attributes['autocomplete'] = empty($config['autocomplete']) ? 'new-' . $fieldName : 'on';
160 }
161
162 $valuePickerHtml = [];
163 if (isset($config['valuePicker']['items']) && is_array($config['valuePicker']['items'])) {
164 $mode = $config['valuePicker']['mode'] ?? '';
165 $itemName = $parameterArray['itemFormElName'];
166 $fieldChangeFunc = $parameterArray['fieldChangeFunc'];
167 if ($mode === 'append') {
168 $assignValue = 'document.querySelectorAll(' . GeneralUtility::quoteJSvalue('[data-formengine-input-name="' . $itemName . '"]') . ')[0]'
169 . '.value=\'\'+this.options[this.selectedIndex].value+document.editform[' . GeneralUtility::quoteJSvalue($itemName) . '].value';
170 } elseif ($mode === 'prepend') {
171 $assignValue = 'document.querySelectorAll(' . GeneralUtility::quoteJSvalue('[data-formengine-input-name="' . $itemName . '"]') . ')[0]'
172 . '.value+=\'\'+this.options[this.selectedIndex].value';
173 } else {
174 $assignValue = 'document.querySelectorAll(' . GeneralUtility::quoteJSvalue('[data-formengine-input-name="' . $itemName . '"]') . ')[0]'
175 . '.value=this.options[this.selectedIndex].value';
176 }
177 $valuePickerHtml[] = '<select';
178 $valuePickerHtml[] = ' class="form-control tceforms-select tceforms-wizardselect"';
179 $valuePickerHtml[] = ' onchange="' . htmlspecialchars($assignValue . ';this.blur();this.selectedIndex=0;' . implode('', $fieldChangeFunc)) . '"';
180 $valuePickerHtml[] = '>';
181 $valuePickerHtml[] = '<option></option>';
182 foreach ($config['valuePicker']['items'] as $item) {
183 $valuePickerHtml[] = '<option value="' . htmlspecialchars($item[1]) . '">' . htmlspecialchars($languageService->sL($item[0])) . '</option>';
184 }
185 $valuePickerHtml[] = '</select>';
186 }
187
188 $legacyWizards = $this->renderWizards();
189 $legacyFieldControlHtml = implode(LF, $legacyWizards['fieldControl']);
190 $legacyFieldWizardHtml = implode(LF, $legacyWizards['fieldWizard']);
191
192 $fieldInformationResult = $this->renderFieldInformation();
193 $fieldInformationHtml = $fieldInformationResult['html'];
194 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
195
196 $fieldWizardResult = $this->renderFieldWizard();
197 $fieldWizardHtml = $legacyFieldWizardHtml . $fieldWizardResult['html'];
198 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
199
200 $fieldControlResult = $this->renderFieldControl();
201 $fieldControlHtml = $legacyFieldControlHtml . $fieldControlResult['html'];
202 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
203
204 $linkExplanation = $this->getLinkExplanation($itemValue ?: '');
205 $explanation = htmlspecialchars($linkExplanation['text']);
206 $toggleButtonTitle = $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:buttons.toggleLinkExplanation');
207
208 $expansionHtml = [];
209 $expansionHtml[] = '<div class="form-control-wrap" style="max-width: ' . $width . 'px">';
210 $expansionHtml[] = '<div class="form-wizards-wrap">';
211 $expansionHtml[] = '<div class="form-wizards-element">';
212 $expansionHtml[] = '<div class="input-group t3js-form-field-inputlink">';
213 $expansionHtml[] = '<span class="input-group-addon">' . $linkExplanation['icon'] . '</span>';
214 $expansionHtml[] = '<input class="form-control form-field-inputlink-explanation t3js-form-field-inputlink-explanation" data-toggle="tooltip" data-title="' . $explanation . '" value="' . $explanation . '" readonly>';
215 $expansionHtml[] = '<input type="text"' . GeneralUtility::implodeAttributes($attributes, true) . ' />';
216 $expansionHtml[] = '<span class="input-group-btn">';
217 $expansionHtml[] = '<button class="btn btn-default t3js-form-field-inputlink-explanation-toggle" type="button" title="' . htmlspecialchars($toggleButtonTitle) . '">';
218 $expansionHtml[] = $this->iconFactory->getIcon('actions-version-workspaces-preview-link', Icon::SIZE_SMALL)->render();
219 $expansionHtml[] = '</button>';
220 $expansionHtml[] = '</span>';
221 $expansionHtml[] = '<input type="hidden" name="' . $parameterArray['itemFormElName'] . '" value="' . htmlspecialchars($itemValue) . '" />';
222 $expansionHtml[] = '</div>';
223 $expansionHtml[] = '</div>';
224 $expansionHtml[] = '<div class="form-wizards-items-aside">';
225 $expansionHtml[] = '<div class="btn-group">';
226 $expansionHtml[] = implode(LF, $valuePickerHtml);
227 $expansionHtml[] = $fieldControlHtml;
228 $expansionHtml[] = '</div>';
229 $expansionHtml[] = '</div>';
230 $expansionHtml[] = '<div class="form-wizards-items-bottom">';
231 $expansionHtml[] = $linkExplanation['additionalAttributes'];
232 $expansionHtml[] = $fieldWizardHtml;
233 $expansionHtml[] = '</div>';
234 $expansionHtml[] = '</div>';
235 $expansionHtml[] = '</div>';
236 $expansionHtml = implode(LF, $expansionHtml);
237
238 $fullElement = $expansionHtml;
239 if ($this->hasNullCheckboxButNoPlaceholder()) {
240 $checked = $itemValue !== null ? ' checked="checked"' : '';
241 $fullElement = [];
242 $fullElement[] = '<div class="t3-form-field-disable"></div>';
243 $fullElement[] = '<div class="checkbox t3-form-field-eval-null-checkbox">';
244 $fullElement[] = '<label for="' . $nullControlNameEscaped . '">';
245 $fullElement[] = '<input type="hidden" name="' . $nullControlNameEscaped . '" value="0" />';
246 $fullElement[] = '<input type="checkbox" name="' . $nullControlNameEscaped . '" id="' . $nullControlNameEscaped . '" value="1"' . $checked . ' />';
247 $fullElement[] = $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.nullCheckbox');
248 $fullElement[] = '</label>';
249 $fullElement[] = '</div>';
250 $fullElement[] = $expansionHtml;
251 $fullElement = implode(LF, $fullElement);
252 } elseif ($this->hasNullCheckboxWithPlaceholder()) {
253 $checked = $itemValue !== null ? ' checked="checked"' : '';
254 $placeholder = $shortenedPlaceholder = $config['placeholder'] ?? '';
255 $disabled = '';
256 $fallbackValue = 0;
257 if (strlen($placeholder) > 0) {
258 $shortenedPlaceholder = GeneralUtility::fixed_lgd_cs($placeholder, 20);
259 if ($placeholder !== $shortenedPlaceholder) {
260 $overrideLabel = sprintf(
261 $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'),
262 '<span title="' . htmlspecialchars($placeholder) . '">' . htmlspecialchars($shortenedPlaceholder) . '</span>'
263 );
264 } else {
265 $overrideLabel = sprintf(
266 $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'),
267 htmlspecialchars($placeholder)
268 );
269 }
270 } else {
271 $fallbackValue = 1;
272 $checked = ' checked="checked"';
273 $disabled = ' disabled="disabled"';
274 $overrideLabel = $languageService->sL(
275 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override_not_available'
276 );
277 }
278 $fullElement = [];
279 $fullElement[] = '<div class="checkbox t3js-form-field-eval-null-placeholder-checkbox">';
280 $fullElement[] = '<label for="' . $nullControlNameEscaped . '">';
281 $fullElement[] = '<input type="hidden" name="' . $nullControlNameEscaped . '" value="' . $fallbackValue . '" />';
282 $fullElement[] = '<input type="checkbox" name="' . $nullControlNameEscaped . '" id="' . $nullControlNameEscaped . '" value="1"' . $checked . $disabled . ' />';
283 $fullElement[] = $overrideLabel;
284 $fullElement[] = '</label>';
285 $fullElement[] = '</div>';
286 $fullElement[] = '<div class="t3js-formengine-placeholder-placeholder">';
287 $fullElement[] = '<div class="form-control-wrap" style="max-width:' . $width . 'px">';
288 $fullElement[] = '<input type="text" class="form-control" disabled="disabled" value="' . $shortenedPlaceholder . '" />';
289 $fullElement[] = '</div>';
290 $fullElement[] = '</div>';
291 $fullElement[] = '<div class="t3js-formengine-placeholder-formfield">';
292 $fullElement[] = $expansionHtml;
293 $fullElement[] = '</div>';
294 $fullElement = implode(LF, $fullElement);
295 }
296
297 $resultArray['html'] = '<div class="formengine-field-item t3js-formengine-field-item">' . $fieldInformationHtml . $fullElement . '</div>';
298 return $resultArray;
299 }
300
301 /**
302 * @param string $itemValue
303 * @return array
304 */
305 protected function getLinkExplanation(string $itemValue): array
306 {
307 if (empty($itemValue)) {
308 return [];
309 }
310 $data = ['text' => '', 'icon' => ''];
311 $typolinkService = GeneralUtility::makeInstance(TypoLinkCodecService::class);
312 $linkParts = $typolinkService->decode($itemValue);
313 $linkService = GeneralUtility::makeInstance(LinkService::class);
314
315 try {
316 $linkData = $linkService->resolve($linkParts['url']);
317 } catch (FileDoesNotExistException $e) {
318 return $data;
319 } catch (FolderDoesNotExistException $e) {
320 return $data;
321 } catch (UnknownLinkHandlerException $e) {
322 return $data;
323 }
324
325 // Resolving the TypoLink parts (class, title, params)
326 $additionalAttributes = [];
327 foreach ($linkParts as $key => $value) {
328 if ($key === 'url') {
329 continue;
330 }
331 if ($value) {
332 switch ($key) {
333 case 'class':
334 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_browse_links.xlf:class');
335 break;
336 case 'title':
337 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_browse_links.xlf:title');
338 break;
339 case 'additionalParams':
340 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_browse_links.xlf:params');
341 break;
342 default:
343 $label = $key;
344 }
345
346 $additionalAttributes[] = '<span><strong>' . htmlspecialchars($label) . ': </strong> ' . htmlspecialchars($value) . '</span>';
347 }
348 }
349
350 // Resolve the actual link
351 switch ($linkData['type']) {
352 case LinkService::TYPE_PAGE:
353 $pageRecord = BackendUtility::readPageAccess($linkData['pageuid'], '1=1');
354 // Is this a real page
355 if ($pageRecord['uid']) {
356 $data = [
357 'text' => $pageRecord['_thePathFull'] . '[' . $pageRecord['uid'] . ']',
358 'icon' => $this->iconFactory->getIconForRecord('pages', $pageRecord, Icon::SIZE_SMALL)->render()
359 ];
360 }
361 break;
362 case LinkService::TYPE_EMAIL:
363 $data = [
364 'text' => $linkData['email'],
365 'icon' => $this->iconFactory->getIcon('content-elements-mailform', Icon::SIZE_SMALL)->render()
366 ];
367 break;
368 case LinkService::TYPE_URL:
369 $data = [
370 'text' => $this->getDomainByUrl($linkData['url']),
371 'icon' => $this->iconFactory->getIcon('apps-pagetree-page-shortcut-external', Icon::SIZE_SMALL)->render()
372
373 ];
374 break;
375 case LinkService::TYPE_FILE:
376 /** @var File $file */
377 $file = $linkData['file'];
378 if ($file) {
379 $data = [
380 'text' => $file->getPublicUrl(),
381 'icon' => $this->iconFactory->getIconForFileExtension($file->getExtension(), Icon::SIZE_SMALL)->render()
382 ];
383 }
384 break;
385 case LinkService::TYPE_FOLDER:
386 /** @var Folder $folder */
387 $folder = $linkData['folder'];
388 if ($folder) {
389 $data = [
390 'text' => $folder->getPublicUrl(),
391 'icon' => $this->iconFactory->getIcon('apps-filetree-folder-default', Icon::SIZE_SMALL)->render()
392 ];
393 }
394 break;
395 case LinkService::TYPE_RECORD:
396 $table = $this->data['pageTsConfig']['TCEMAIN.']['linkHandler.'][$linkData['identifier'] . '.']['configuration.']['table'];
397 $record = BackendUtility::getRecord($table, $linkData['uid']);
398 $recordTitle = BackendUtility::getRecordTitle($table, $record);
399 $tableTitle = $this->getLanguageService()->sL($GLOBALS['TCA'][$table]['ctrl']['title']);
400 $data = [
401 'text' => sprintf('%s [%s:%d]', $recordTitle, $tableTitle, $linkData['uid']),
402 'icon' => $this->iconFactory->getIconForRecord($table, $record, Icon::SIZE_SMALL)->render()
403 ];
404 break;
405 default:
406 // Please note that this hook is preliminary and might change, as this element could become its own
407 // TCA type in the future
408 if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['linkHandler'][$linkData['type']])) {
409 $linkBuilder = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['linkHandler'][$linkData['type']]);
410 $data = $linkBuilder->getFormData($linkData, $linkParts, $this->data, $this);
411 } else {
412 $data = [
413 'text' => 'not implemented type ' . $linkData['type'],
414 'icon' => ''
415 ];
416 }
417 }
418
419 $data['additionalAttributes'] = '<div class="help-block">' . implode(' - ', $additionalAttributes) . '</div>';
420 return $data;
421 }
422
423 /**
424 * @param string $uriString
425 *
426 * @return string
427 */
428 protected function getDomainByUrl(string $uriString): string
429 {
430 $data = parse_url($uriString);
431 return $data['host'] ?? '';
432 }
433
434 /**
435 * @return LanguageService
436 */
437 protected function getLanguageService()
438 {
439 return $GLOBALS['LANG'];
440 }
441 }