[BUGFIX] Catch UnknownLinkHandlerException in InputLinkElement
[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\Localization\LanguageService;
22 use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
23 use TYPO3\CMS\Core\Resource\Exception\FolderDoesNotExistException;
24 use TYPO3\CMS\Core\Resource\File;
25 use TYPO3\CMS\Core\Resource\Folder;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\MathUtility;
28 use TYPO3\CMS\Core\Utility\StringUtility;
29 use TYPO3\CMS\Frontend\Service\TypoLinkCodecService;
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 $nullControlNameAttribute = ' name="' . 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 $fieldInformationResult = $this->renderFieldInformation();
189 $fieldInformationHtml = $fieldInformationResult['html'];
190 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
191
192 $fieldWizardResult = $this->renderFieldWizard();
193 $fieldWizardHtml = $fieldWizardResult['html'];
194 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
195
196 $fieldControlResult = $this->renderFieldControl();
197 $fieldControlHtml = $fieldControlResult['html'];
198 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
199
200 $linkExplanation = $this->getLinkExplanation($itemValue ?: '');
201 $explanation = htmlspecialchars($linkExplanation['text']);
202 $toggleButtonTitle = $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:buttons.toggleLinkExplanation');
203
204 $expansionHtml = [];
205 $expansionHtml[] = '<div class="form-control-wrap" style="max-width: ' . $width . 'px">';
206 $expansionHtml[] = '<div class="form-wizards-wrap">';
207 $expansionHtml[] = '<div class="form-wizards-element">';
208 $expansionHtml[] = '<div class="input-group t3js-form-field-inputlink">';
209 $expansionHtml[] = '<span class="input-group-addon">' . $linkExplanation['icon'] . '</span>';
210 $expansionHtml[] = '<input class="form-control form-field-inputlink-explanation t3js-form-field-inputlink-explanation" data-toggle="tooltip" data-title="' . $explanation . '" value="' . $explanation . '" readonly>';
211 $expansionHtml[] = '<input type="text"' . GeneralUtility::implodeAttributes($attributes, true) . ' />';
212 $expansionHtml[] = '<span class="input-group-btn">';
213 $expansionHtml[] = '<button class="btn btn-default t3js-form-field-inputlink-explanation-toggle" type="button" title="' . htmlspecialchars($toggleButtonTitle) . '">';
214 $expansionHtml[] = $this->iconFactory->getIcon('actions-version-workspaces-preview-link', Icon::SIZE_SMALL)->render();
215 $expansionHtml[] = '</button>';
216 $expansionHtml[] = '</span>';
217 $expansionHtml[] = '<input type="hidden" name="' . $parameterArray['itemFormElName'] . '" value="' . htmlspecialchars($itemValue) . '" />';
218 $expansionHtml[] = '</div>';
219 $expansionHtml[] = '</div>';
220 $expansionHtml[] = '<div class="form-wizards-items-aside">';
221 $expansionHtml[] = '<div class="btn-group">';
222 $expansionHtml[] = implode(LF, $valuePickerHtml);
223 $expansionHtml[] = $fieldControlHtml;
224 $expansionHtml[] = '</div>';
225 $expansionHtml[] = '</div>';
226 $expansionHtml[] = '<div class="form-wizards-items-bottom">';
227 $expansionHtml[] = $linkExplanation['additionalAttributes'];
228 $expansionHtml[] = $fieldWizardHtml;
229 $expansionHtml[] = '</div>';
230 $expansionHtml[] = '</div>';
231 $expansionHtml[] = '</div>';
232 $expansionHtml = implode(LF, $expansionHtml);
233
234 $fullElement = $expansionHtml;
235 if ($this->hasNullCheckboxButNoPlaceholder()) {
236 $checked = $itemValue !== null ? ' checked="checked"' : '';
237 $fullElement = [];
238 $fullElement[] = '<div class="t3-form-field-disable"></div>';
239 $fullElement[] = '<div class="checkbox t3-form-field-eval-null-checkbox">';
240 $fullElement[] = '<label>';
241 $fullElement[] = '<input type="hidden"' . $nullControlNameAttribute . ' value="0" />';
242 $fullElement[] = '<input type="checkbox"' . $nullControlNameAttribute . ' value="1"' . $checked . ' />';
243 $fullElement[] = $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.nullCheckbox');
244 $fullElement[] = '</label>';
245 $fullElement[] = '</div>';
246 $fullElement[] = $expansionHtml;
247 $fullElement = implode(LF, $fullElement);
248 } elseif ($this->hasNullCheckboxWithPlaceholder()) {
249 $checked = $itemValue !== null ? ' checked="checked"' : '';
250 $placeholder = $shortenedPlaceholder = $config['placeholder'] ?? '';
251 $disabled = '';
252 $fallbackValue = 0;
253 if (strlen($placeholder) > 0) {
254 $shortenedPlaceholder = GeneralUtility::fixed_lgd_cs($placeholder, 20);
255 if ($placeholder !== $shortenedPlaceholder) {
256 $overrideLabel = sprintf(
257 $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'),
258 '<span title="' . htmlspecialchars($placeholder) . '">' . htmlspecialchars($shortenedPlaceholder) . '</span>'
259 );
260 } else {
261 $overrideLabel = sprintf(
262 $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'),
263 htmlspecialchars($placeholder)
264 );
265 }
266 } else {
267 $fallbackValue = 1;
268 $checked = ' checked="checked"';
269 $disabled = ' disabled="disabled"';
270 $overrideLabel = $languageService->sL(
271 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override_not_available'
272 );
273 }
274 $fullElement = [];
275 $fullElement[] = '<div class="checkbox t3js-form-field-eval-null-placeholder-checkbox">';
276 $fullElement[] = '<label>';
277 $fullElement[] = '<input type="hidden"' . $nullControlNameAttribute . ' value="' . $fallbackValue . '" />';
278 $fullElement[] = '<input type="checkbox"' . $nullControlNameAttribute . ' value="1"' . $checked . $disabled . ' />';
279 $fullElement[] = $overrideLabel;
280 $fullElement[] = '</label>';
281 $fullElement[] = '</div>';
282 $fullElement[] = '<div class="t3js-formengine-placeholder-placeholder">';
283 $fullElement[] = '<div class="form-control-wrap" style="max-width:' . $width . 'px">';
284 $fullElement[] = '<input type="text" class="form-control" disabled="disabled" value="' . $shortenedPlaceholder . '" />';
285 $fullElement[] = '</div>';
286 $fullElement[] = '</div>';
287 $fullElement[] = '<div class="t3js-formengine-placeholder-formfield">';
288 $fullElement[] = $expansionHtml;
289 $fullElement[] = '</div>';
290 $fullElement = implode(LF, $fullElement);
291 }
292
293 $resultArray['html'] = '<div class="formengine-field-item t3js-formengine-field-item">' . $fieldInformationHtml . $fullElement . '</div>';
294 return $resultArray;
295 }
296
297 /**
298 * @param string $itemValue
299 * @return array
300 */
301 protected function getLinkExplanation(string $itemValue): array
302 {
303 if (empty($itemValue)) {
304 return [];
305 }
306 $data = ['text' => '', 'icon' => ''];
307 $typolinkService = GeneralUtility::makeInstance(TypoLinkCodecService::class);
308 $linkParts = $typolinkService->decode($itemValue);
309 $linkService = GeneralUtility::makeInstance(LinkService::class);
310
311 try {
312 $linkData = $linkService->resolve($linkParts['url']);
313 } catch (FileDoesNotExistException $e) {
314 return $data;
315 } catch (FolderDoesNotExistException $e) {
316 return $data;
317 } catch (UnknownLinkHandlerException $e) {
318 return $data;
319 }
320
321 // Resolving the TypoLink parts (class, title, params)
322 $additionalAttributes = [];
323 foreach ($linkParts as $key => $value) {
324 if ($key === 'url') {
325 continue;
326 }
327 if ($value) {
328 switch ($key) {
329 case 'class':
330 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_browse_links.xlf:class');
331 break;
332 case 'title':
333 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_browse_links.xlf:title');
334 break;
335 case 'additionalParams':
336 $label = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_browse_links.xlf:params');
337 break;
338 default:
339 $label = $key;
340 }
341
342 $additionalAttributes[] = '<span><strong>' . htmlspecialchars($label) . ': </strong> ' . htmlspecialchars($value) . '</span>';
343 }
344 }
345
346 // Resolve the actual link
347 switch ($linkData['type']) {
348 case LinkService::TYPE_PAGE:
349 $pageRecord = BackendUtility::readPageAccess($linkData['pageuid'], '1=1');
350 // Is this a real page
351 if ($pageRecord['uid']) {
352 $data = [
353 'text' => $pageRecord['_thePathFull'] . '[' . $pageRecord['uid'] . ']',
354 'icon' => $this->iconFactory->getIconForRecord('pages', $pageRecord, Icon::SIZE_SMALL)->render()
355 ];
356 }
357 break;
358 case LinkService::TYPE_EMAIL:
359 $data = [
360 'text' => $linkData['email'],
361 'icon' => $this->iconFactory->getIcon('content-elements-mailform', Icon::SIZE_SMALL)->render()
362 ];
363 break;
364 case LinkService::TYPE_URL:
365 $data = [
366 'text' => $this->getDomainByUrl($linkData['url']),
367 'icon' => $this->iconFactory->getIcon('apps-pagetree-page-shortcut-external', Icon::SIZE_SMALL)->render()
368
369 ];
370 break;
371 case LinkService::TYPE_FILE:
372 /** @var File $file */
373 $file = $linkData['file'];
374 if ($file) {
375 $data = [
376 'text' => $file->getPublicUrl(),
377 'icon' => $this->iconFactory->getIconForFileExtension($file->getExtension(), Icon::SIZE_SMALL)->render()
378 ];
379 }
380 break;
381 case LinkService::TYPE_FOLDER:
382 /** @var Folder $folder */
383 $folder = $linkData['folder'];
384 if ($folder) {
385 $data = [
386 'text' => $folder->getPublicUrl(),
387 'icon' => $this->iconFactory->getIcon('apps-filetree-folder-default', Icon::SIZE_SMALL)->render()
388 ];
389 }
390 break;
391 case LinkService::TYPE_RECORD:
392 $table = $this->data['pageTsConfig']['TCEMAIN.']['linkHandler.'][$linkData['identifier'] . '.']['configuration.']['table'];
393 $record = BackendUtility::getRecord($table, $linkData['uid']);
394 $recordTitle = BackendUtility::getRecordTitle($table, $record);
395 $tableTitle = $this->getLanguageService()->sL($GLOBALS['TCA'][$table]['ctrl']['title']);
396 $data = [
397 'text' => sprintf('%s [%s:%d]', $recordTitle, $tableTitle, $linkData['uid']),
398 'icon' => $this->iconFactory->getIconForRecord($table, $record, Icon::SIZE_SMALL)->render()
399 ];
400 break;
401 default:
402 // Please note that this hook is preliminary and might change, as this element could become its own
403 // TCA type in the future
404 if (isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['linkHandler'][$linkData['type']])) {
405 $linkBuilder = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['linkHandler'][$linkData['type']]);
406 $data = $linkBuilder->getFormData($linkData, $linkParts, $this->data, $this);
407 } else {
408 $data = [
409 'text' => 'not implemented type ' . $linkData['type'],
410 'icon' => ''
411 ];
412 }
413 }
414
415 $data['additionalAttributes'] = '<div class="help-block">' . implode(' - ', $additionalAttributes) . '</div>';
416 return $data;
417 }
418
419 /**
420 * @param string $uriString
421 *
422 * @return string
423 */
424 protected function getDomainByUrl(string $uriString): string
425 {
426 $data = parse_url($uriString);
427 return $data['host'] ?? '';
428 }
429
430 /**
431 * @return LanguageService
432 */
433 protected function getLanguageService()
434 {
435 return $GLOBALS['LANG'];
436 }
437 }