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