[BUGFIX] Adapt TCA signature for customControls to the documentation
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Container / InlineControlContainer.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form\Container;
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\Form\InlineStackProcessor;
18 use TYPO3\CMS\Backend\Form\NodeFactory;
19 use TYPO3\CMS\Backend\Utility\BackendUtility;
20 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
21 use TYPO3\CMS\Core\Imaging\Icon;
22 use TYPO3\CMS\Core\Imaging\IconFactory;
23 use TYPO3\CMS\Core\Localization\LanguageService;
24 use TYPO3\CMS\Core\Resource\Folder;
25 use TYPO3\CMS\Core\Resource\OnlineMedia\Helpers\OnlineMediaHelperRegistry;
26 use TYPO3\CMS\Core\Utility\GeneralUtility;
27 use TYPO3\CMS\Core\Utility\MathUtility;
28 use TYPO3\CMS\Core\Utility\StringUtility;
29
30 /**
31 * Inline element entry container.
32 *
33 * This container is the entry step to rendering an inline element. It is created by SingleFieldContainer.
34 *
35 * The code creates the main structure for the single inline elements, initializes
36 * the inlineData array, that is manipulated and also returned back in its manipulated state.
37 * The "control" stuff of inline elements is rendered here, for example the "create new" button.
38 *
39 * For each existing inline relation an InlineRecordContainer is called for further processing.
40 */
41 class InlineControlContainer extends AbstractContainer
42 {
43 /**
44 * Inline data array used in JS, returned as JSON object to frontend
45 *
46 * @var array
47 */
48 protected $inlineData = [];
49
50 /**
51 * @var InlineStackProcessor
52 */
53 protected $inlineStackProcessor;
54
55 /**
56 * @var IconFactory
57 */
58 protected $iconFactory;
59
60 /**
61 * @var string[]
62 */
63 protected $requireJsModules = [];
64
65 /**
66 * Default field information enabled for this element.
67 *
68 * @var array
69 */
70 protected $defaultFieldInformation = [
71 'tcaDescription' => [
72 'renderType' => 'tcaDescription',
73 ],
74 ];
75
76 /**
77 * @var array Default wizards
78 */
79 protected $defaultFieldWizard = [
80 'localizationStateSelector' => [
81 'renderType' => 'localizationStateSelector',
82 ],
83 ];
84
85 /**
86 * Container objects give $nodeFactory down to other containers.
87 *
88 * @param NodeFactory $nodeFactory
89 * @param array $data
90 */
91 public function __construct(NodeFactory $nodeFactory, array $data)
92 {
93 parent::__construct($nodeFactory, $data);
94 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
95 }
96
97 /**
98 * Entry method
99 *
100 * @return array As defined in initializeResultArray() of AbstractNode
101 */
102 public function render()
103 {
104 $languageService = $this->getLanguageService();
105
106 $this->inlineData = $this->data['inlineData'];
107
108 /** @var InlineStackProcessor $inlineStackProcessor */
109 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
110 $this->inlineStackProcessor = $inlineStackProcessor;
111 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
112
113 $table = $this->data['tableName'];
114 $row = $this->data['databaseRow'];
115 $field = $this->data['fieldName'];
116 $parameterArray = $this->data['parameterArray'];
117
118 $resultArray = $this->initializeResultArray();
119
120 $config = $parameterArray['fieldConf']['config'];
121 $foreign_table = $config['foreign_table'];
122
123 $language = 0;
124 $languageFieldName = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
125 if (BackendUtility::isTableLocalizable($table)) {
126 $language = isset($row[$languageFieldName][0]) ? (int)$row[$languageFieldName][0] : (int)$row[$languageFieldName];
127 }
128
129 // Add the current inline job to the structure stack
130 $newStructureItem = [
131 'table' => $table,
132 'uid' => $row['uid'],
133 'field' => $field,
134 'config' => $config,
135 ];
136 // Extract FlexForm parts (if any) from element name, e.g. array('vDEF', 'lDEF', 'FlexField', 'vDEF')
137 if (!empty($parameterArray['itemFormElName'])) {
138 $flexFormParts = $this->extractFlexFormParts($parameterArray['itemFormElName']);
139 if ($flexFormParts !== null) {
140 $newStructureItem['flexform'] = $flexFormParts;
141 }
142 }
143 $inlineStackProcessor->pushStableStructureItem($newStructureItem);
144
145 // Transport the flexform DS identifier fields to the FormInlineAjaxController
146 if (!empty($newStructureItem['flexform'])
147 && isset($this->data['processedTca']['columns'][$field]['config']['dataStructureIdentifier'])
148 ) {
149 $config['dataStructureIdentifier'] = $this->data['processedTca']['columns'][$field]['config']['dataStructureIdentifier'];
150 }
151
152 // Hand over original returnUrl to FormInlineAjaxController. Needed if opening for instance a
153 // nested element in a new view to then go back to the original returnUrl and not the url of
154 // the inline ajax controller
155 $config['originalReturnUrl'] = $this->data['returnUrl'];
156
157 // e.g. data[<table>][<uid>][<field>]
158 $nameForm = $inlineStackProcessor->getCurrentStructureFormPrefix();
159 // e.g. data-<pid>-<table1>-<uid1>-<field1>-<table2>-<uid2>-<field2>
160 $nameObject = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
161
162 $config['inline']['first'] = false;
163 $firstChild = reset($this->data['parameterArray']['fieldConf']['children']);
164 if (isset($firstChild['databaseRow']['uid'])) {
165 $config['inline']['first'] = $firstChild['databaseRow']['uid'];
166 }
167 $config['inline']['last'] = false;
168 $lastChild = end($this->data['parameterArray']['fieldConf']['children']);
169 if (isset($lastChild['databaseRow']['uid'])) {
170 $config['inline']['last'] = $lastChild['databaseRow']['uid'];
171 }
172
173 $top = $inlineStackProcessor->getStructureLevel(0);
174
175 $this->inlineData['config'][$nameObject] = [
176 'table' => $foreign_table,
177 'md5' => md5($nameObject)
178 ];
179 $this->inlineData['config'][$nameObject . '-' . $foreign_table] = [
180 'min' => $config['minitems'],
181 'max' => $config['maxitems'],
182 'sortable' => $config['appearance']['useSortable'],
183 'top' => [
184 'table' => $top['table'],
185 'uid' => $top['uid']
186 ],
187 'context' => [
188 'config' => $config,
189 'hmac' => GeneralUtility::hmac(json_encode($config), 'InlineContext'),
190 ],
191 ];
192 $this->inlineData['nested'][$nameObject] = $this->data['tabAndInlineStack'];
193
194 $uniqueMax = 0;
195 $uniqueIds = [];
196
197 if ($config['foreign_unique']) {
198 // Add inlineData['unique'] with JS unique configuration
199 $type = $config['selectorOrUniqueConfiguration']['config']['type'] === 'select' ? 'select' : 'groupdb';
200 foreach ($parameterArray['fieldConf']['children'] as $child) {
201 // Determine used unique ids, skip not localized records
202 if (!$child['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
203 $value = $child['databaseRow'][$config['foreign_unique']];
204 // We're assuming there is only one connected value here for both select and group
205 if ($type === 'select') {
206 // A resolved select field is an array - take first value
207 $value = $value['0'];
208 } else {
209 // A group field is still a list with pipe separated uid|tableName
210 $valueParts = GeneralUtility::trimExplode('|', $value);
211 $itemParts = explode('_', $valueParts[0]);
212 $value = [
213 'uid' => array_pop($itemParts),
214 'table' => implode('_', $itemParts)
215 ];
216 }
217 // @todo: This is weird, $value has different structure for group and select fields?
218 $uniqueIds[$child['databaseRow']['uid']] = $value;
219 }
220 }
221 $possibleRecords = $config['selectorOrUniquePossibleRecords'];
222 $possibleRecordsUidToTitle = [];
223 foreach ($possibleRecords as $possibleRecord) {
224 $possibleRecordsUidToTitle[$possibleRecord[1]] = $possibleRecord[0];
225 }
226 $uniqueMax = $config['appearance']['useCombination'] || empty($possibleRecords) ? -1 : count($possibleRecords);
227 $this->inlineData['unique'][$nameObject . '-' . $foreign_table] = [
228 'max' => $uniqueMax,
229 'used' => $uniqueIds,
230 'type' => $type,
231 'table' => $foreign_table,
232 'elTable' => $config['selectorOrUniqueConfiguration']['foreignTable'],
233 'field' => $config['foreign_unique'],
234 'selector' => $config['selectorOrUniqueConfiguration']['isSelector'] ? $type : false,
235 'possible' => $possibleRecordsUidToTitle,
236 ];
237 }
238
239 $resultArray['inlineData'] = $this->inlineData;
240
241 // @todo: It might be a good idea to have something like "isLocalizedRecord" or similar set by a data provider
242 $uidOfDefaultRecord = $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
243 $isLocalizedParent = $language > 0
244 && ($uidOfDefaultRecord[0] ?? $uidOfDefaultRecord) > 0
245 && MathUtility::canBeInterpretedAsInteger($row['uid']);
246 $numberOfFullLocalizedChildren = 0;
247 $numberOfNotYetLocalizedChildren = 0;
248 foreach ($this->data['parameterArray']['fieldConf']['children'] as $child) {
249 if (!$child['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
250 $numberOfFullLocalizedChildren++;
251 }
252 if ($isLocalizedParent && $child['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
253 $numberOfNotYetLocalizedChildren++;
254 }
255 }
256
257 // Render the localization links if needed
258 $localizationLinks = '';
259 if ($numberOfNotYetLocalizedChildren) {
260 // Add the "Localize all records" link before all child records:
261 if (isset($config['appearance']['showAllLocalizationLink']) && $config['appearance']['showAllLocalizationLink']) {
262 $localizationLinks = ' ' . $this->getLevelInteractionLink('localize', $nameObject . '-' . $foreign_table, $config);
263 }
264 // Add the "Synchronize with default language" link before all child records:
265 if (isset($config['appearance']['showSynchronizationLink']) && $config['appearance']['showSynchronizationLink']) {
266 $localizationLinks .= ' ' . $this->getLevelInteractionLink('synchronize', $nameObject . '-' . $foreign_table, $config);
267 }
268 }
269
270 // Define how to show the "Create new record" link - if there are more than maxitems, hide it
271 if ($numberOfFullLocalizedChildren >= $config['maxitems'] || $uniqueMax > 0 && $numberOfFullLocalizedChildren >= $uniqueMax) {
272 $config['inline']['inlineNewButtonStyle'] = 'display: none;';
273 $config['inline']['inlineNewRelationButtonStyle'] = 'display: none;';
274 $config['inline']['inlineOnlineMediaAddButtonStyle'] = 'display: none;';
275 }
276
277 // Render the level links (create new record):
278 $levelLinks = '';
279 if (!empty($config['appearance']['enabledControls']['new'])) {
280 $levelLinks = $this->getLevelInteractionLink('newRecord', $nameObject . '-' . $foreign_table, $config);
281 }
282 // Wrap all inline fields of a record with a <div> (like a container)
283 $html = '<div class="form-group" id="' . $nameObject . '">';
284
285 $fieldInformationResult = $this->renderFieldInformation();
286 $html .= $fieldInformationResult['html'];
287 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
288
289 // Add the level links before all child records:
290 if ($config['appearance']['levelLinksPosition'] === 'both' || $config['appearance']['levelLinksPosition'] === 'top') {
291 $html .= '<div class="form-group t3js-formengine-validation-marker">' . $levelLinks . $localizationLinks . '</div>';
292 }
293
294 // If it's required to select from possible child records (reusable children), add a selector box
295 if ($config['foreign_selector'] && $config['appearance']['showPossibleRecordsSelector'] !== false) {
296 if ($config['selectorOrUniqueConfiguration']['config']['type'] === 'select') {
297 $selectorBox = $this->renderPossibleRecordsSelectorTypeSelect($config, $uniqueIds);
298 } else {
299 $selectorBox = $this->renderPossibleRecordsSelectorTypeGroupDB($config);
300 }
301 $html .= $selectorBox . $localizationLinks;
302 }
303
304 $title = $languageService->sL(trim($parameterArray['fieldConf']['label']));
305 $html .= '<div class="panel-group panel-hover" data-title="' . htmlspecialchars($title) . '" id="' . $nameObject . '_records">';
306
307 $sortableRecordUids = [];
308 foreach ($this->data['parameterArray']['fieldConf']['children'] as $options) {
309 $options['inlineParentUid'] = $row['uid'];
310 $options['inlineFirstPid'] = $this->data['inlineFirstPid'];
311 // @todo: this can be removed if this container no longer sets additional info to $config
312 $options['inlineParentConfig'] = $config;
313 $options['inlineData'] = $this->inlineData;
314 $options['inlineStructure'] = $inlineStackProcessor->getStructure();
315 $options['inlineExpandCollapseStateArray'] = $this->data['inlineExpandCollapseStateArray'];
316 $options['renderType'] = 'inlineRecordContainer';
317 $childResult = $this->nodeFactory->create($options)->render();
318 $html .= $childResult['html'];
319 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childResult, false);
320 if (!$options['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
321 // Don't add record to list of "valid" uids if it is only the default
322 // language record of a not yet localized child
323 $sortableRecordUids[] = $options['databaseRow']['uid'];
324 }
325 }
326
327 $html .= '</div>';
328
329 $fieldWizardResult = $this->renderFieldWizard();
330 $fieldWizardHtml = $fieldWizardResult['html'];
331 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
332 $html .= $fieldWizardHtml;
333
334 // Add the level links after all child records:
335 if ($config['appearance']['levelLinksPosition'] === 'both' || $config['appearance']['levelLinksPosition'] === 'bottom') {
336 $html .= $levelLinks . $localizationLinks;
337 }
338 if (is_array($config['customControls'])) {
339 $html .= '<div id="' . $nameObject . '_customControls">';
340 foreach ($config['customControls'] as $customControlConfig) {
341 if (!isset($customControlConfig['userFunc'])) {
342 trigger_error('Support for customControl without a userFunc key will be removed in TYPO3 v10.', E_USER_DEPRECATED);
343 $customControlConfig = [
344 'userFunc' => $customControlConfig
345 ];
346 }
347 $parameters = [
348 'table' => $table,
349 'field' => $field,
350 'row' => $row,
351 'nameObject' => $nameObject,
352 'nameForm' => $nameForm,
353 'config' => $config,
354 'customControlConfig' => $customControlConfig,
355 ];
356 $html .= GeneralUtility::callUserFunction($customControlConfig['userFunc'], $parameters, $this);
357 }
358 $html .= '</div>';
359 }
360 // Add Drag&Drop functions for sorting to FormEngine::$additionalJS_post
361 if (count($sortableRecordUids) > 1 && $config['appearance']['useSortable']) {
362 $resultArray['additionalJavaScriptPost'][] = 'inline.createDragAndDropSorting("' . $nameObject . '_records' . '");';
363 }
364 $resultArray['requireJsModules'] = array_merge($resultArray['requireJsModules'], $this->requireJsModules);
365
366 // Publish the uids of the child records in the given order to the browser
367 $html .= '<input type="hidden" name="' . $nameForm . '" value="' . implode(',', $sortableRecordUids) . '" '
368 . ' data-formengine-validation-rules="' . htmlspecialchars($this->getValidationDataAsJsonString(['type' => 'inline', 'minitems' => $config['minitems'], 'maxitems' => $config['maxitems']])) . '"'
369 . ' class="inlineRecord" />';
370 // Close the wrap for all inline fields (container)
371 $html .= '</div>';
372
373 $resultArray['html'] = $html;
374 return $resultArray;
375 }
376
377 /**
378 * Creates the HTML code of a general link to be used on a level of inline children.
379 * The possible keys for the parameter $type are 'newRecord', 'localize' and 'synchronize'.
380 *
381 * @param string $type The link type, values are 'newRecord', 'localize' and 'synchronize'.
382 * @param string $objectPrefix The "path" to the child record to create (e.g. 'data-parentPageId-partenTable-parentUid-parentField-childTable]')
383 * @param array $conf TCA configuration of the parent(!) field
384 * @return string The HTML code of the new link, wrapped in a div
385 */
386 protected function getLevelInteractionLink($type, $objectPrefix, $conf = [])
387 {
388 $languageService = $this->getLanguageService();
389 $nameObject = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
390 $attributes = [];
391 switch ($type) {
392 case 'newRecord':
393 $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.createnew'));
394 $icon = 'actions-add';
395 $className = 'typo3-newRecordLink';
396 $attributes['class'] = 'btn btn-default inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
397 $attributes['onclick'] = 'return inline.createNewRecord(' . GeneralUtility::quoteJSvalue($objectPrefix) . ')';
398 if (!empty($conf['inline']['inlineNewButtonStyle'])) {
399 $attributes['style'] = $conf['inline']['inlineNewButtonStyle'];
400 }
401 if (!empty($conf['appearance']['newRecordLinkAddTitle'])) {
402 $title = htmlspecialchars(sprintf(
403 $languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.createnew.link'),
404 $languageService->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'])
405 ));
406 } elseif (isset($conf['appearance']['newRecordLinkTitle']) && $conf['appearance']['newRecordLinkTitle'] !== '') {
407 $title = htmlspecialchars($languageService->sL($conf['appearance']['newRecordLinkTitle']));
408 }
409 break;
410 case 'localize':
411 $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:localizeAllRecords'));
412 $icon = 'actions-document-localize';
413 $className = 'typo3-localizationLink';
414 $attributes['class'] = 'btn btn-default';
415 $attributes['onclick'] = 'return inline.synchronizeLocalizeRecords(' . GeneralUtility::quoteJSvalue($objectPrefix) . ', \'localize\')';
416 break;
417 case 'synchronize':
418 $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:synchronizeWithOriginalLanguage'));
419 $icon = 'actions-document-synchronize';
420 $className = 'typo3-synchronizationLink';
421 $attributes['class'] = 'btn btn-default inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
422 $attributes['onclick'] = 'return inline.synchronizeLocalizeRecords(' . GeneralUtility::quoteJSvalue($objectPrefix) . ', \'synchronize\')';
423 break;
424 default:
425 $title = '';
426 $icon = '';
427 $className = '';
428 }
429 // Create the link:
430 $icon = $icon ? $this->iconFactory->getIcon($icon, Icon::SIZE_SMALL)->render() : '';
431 $link = $this->wrapWithAnchor($icon . ' ' . $title, '#', $attributes);
432 return '<div' . ($className ? ' class="' . $className . '"' : '') . 'title="' . $title . '">' . $link . '</div>';
433 }
434
435 /**
436 * Wraps a text with an anchor and returns the HTML representation.
437 *
438 * @param string $text The text to be wrapped by an anchor
439 * @param string $link The link to be used in the anchor
440 * @param array $attributes Array of attributes to be used in the anchor
441 * @return string The wrapped text as HTML representation
442 */
443 protected function wrapWithAnchor($text, $link, $attributes = [])
444 {
445 $attributes['href'] = trim($link ?: '#');
446 return '<a ' . GeneralUtility::implodeAttributes($attributes, true, true) . '>' . $text . '</a>';
447 }
448
449 /**
450 * Generate a link that opens an element browser in a new window.
451 * For group/db there is no way to use a "selector" like a <select>|</select>-box.
452 *
453 * @param array $inlineConfiguration TCA inline configuration of the parent(!) field
454 * @return string A HTML link that opens an element browser in a new window
455 */
456 protected function renderPossibleRecordsSelectorTypeGroupDB(array $inlineConfiguration)
457 {
458 $backendUser = $this->getBackendUserAuthentication();
459 $languageService = $this->getLanguageService();
460
461 $groupFieldConfiguration = $inlineConfiguration['selectorOrUniqueConfiguration']['config'];
462
463 $foreign_table = $inlineConfiguration['foreign_table'];
464 $allowed = $groupFieldConfiguration['allowed'];
465 $currentStructureDomObjectIdPrefix = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
466 $objectPrefix = $currentStructureDomObjectIdPrefix . '-' . $foreign_table;
467 $nameObject = $currentStructureDomObjectIdPrefix;
468 $mode = 'db';
469 $showUpload = false;
470 $elementBrowserEnabled = true;
471 if (!empty($inlineConfiguration['appearance']['createNewRelationLinkTitle'])) {
472 $createNewRelationText = htmlspecialchars($languageService->sL($inlineConfiguration['appearance']['createNewRelationLinkTitle']));
473 } else {
474 $createNewRelationText = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.createNewRelation'));
475 }
476 if (is_array($groupFieldConfiguration['appearance'])) {
477 if (isset($groupFieldConfiguration['appearance']['elementBrowserType'])) {
478 $mode = $groupFieldConfiguration['appearance']['elementBrowserType'];
479 }
480 if ($mode === 'file') {
481 $showUpload = true;
482 }
483 if (isset($inlineConfiguration['appearance']['fileUploadAllowed'])) {
484 $showUpload = (bool)$inlineConfiguration['appearance']['fileUploadAllowed'];
485 }
486 if (isset($groupFieldConfiguration['appearance']['elementBrowserAllowed'])) {
487 $allowed = $groupFieldConfiguration['appearance']['elementBrowserAllowed'];
488 }
489 if (isset($inlineConfiguration['appearance']['elementBrowserEnabled'])) {
490 $elementBrowserEnabled = (bool)$inlineConfiguration['appearance']['elementBrowserEnabled'];
491 }
492 }
493 $browserParams = '|||' . $allowed . '|' . $objectPrefix . '|inline.checkUniqueElement||inline.importElement';
494 $onClick = 'setFormValueOpenBrowser(' . GeneralUtility::quoteJSvalue($mode) . ', ' . GeneralUtility::quoteJSvalue($browserParams) . '); return false;';
495
496 $buttonStyle = '';
497 if (isset($inlineConfiguration['inline']['inlineNewRelationButtonStyle'])) {
498 $buttonStyle = ' style="' . $inlineConfiguration['inline']['inlineNewRelationButtonStyle'] . '"';
499 }
500 $item = '';
501 if ($elementBrowserEnabled) {
502 $item .= '
503 <a href="#" class="btn btn-default inlineNewRelationButton ' . $this->inlineData['config'][$nameObject]['md5'] . '"
504 ' . $buttonStyle . ' onclick="' . htmlspecialchars($onClick) . '" title="' . $createNewRelationText . '">
505 ' . $this->iconFactory->getIcon('actions-insert-record', Icon::SIZE_SMALL)->render() . '
506 ' . $createNewRelationText . '
507 </a>';
508 }
509
510 $isDirectFileUploadEnabled = (bool)$backendUser->uc['edit_docModuleUpload'];
511 $allowedArray = GeneralUtility::trimExplode(',', $allowed, true);
512 $onlineMediaAllowed = OnlineMediaHelperRegistry::getInstance()->getSupportedFileExtensions();
513 if (!empty($allowedArray)) {
514 $onlineMediaAllowed = array_intersect($allowedArray, $onlineMediaAllowed);
515 }
516 if ($showUpload && $isDirectFileUploadEnabled) {
517 $folder = $backendUser->getDefaultUploadFolder(
518 $this->data['parentPageRow']['uid'],
519 $this->data['tableName'],
520 $this->data['fieldName']
521 );
522 if (
523 $folder instanceof Folder
524 && $folder->getStorage()->checkUserActionPermission('add', 'File')
525 ) {
526 $maxFileSize = GeneralUtility::getMaxUploadFileSize() * 1024;
527 $item .= ' <a href="#" class="btn btn-default t3js-drag-uploader inlineNewFileUploadButton ' . $this->inlineData['config'][$nameObject]['md5'] . '"
528 ' . $buttonStyle . '
529 data-dropzone-target="#' . htmlspecialchars(StringUtility::escapeCssSelector($currentStructureDomObjectIdPrefix)) . '"
530 data-insert-dropzone-before="1"
531 data-file-irre-object="' . htmlspecialchars($objectPrefix) . '"
532 data-file-allowed="' . htmlspecialchars($allowed) . '"
533 data-target-folder="' . htmlspecialchars($folder->getCombinedIdentifier()) . '"
534 data-max-file-size="' . htmlspecialchars($maxFileSize) . '"
535 >';
536 $item .= $this->iconFactory->getIcon('actions-upload', Icon::SIZE_SMALL)->render() . ' ';
537 $item .= htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:file_upload.select-and-submit'));
538 $item .= '</a>';
539
540 $this->requireJsModules[] = ['TYPO3/CMS/Backend/DragUploader' => 'function(dragUploader){dragUploader.initialize()}'];
541 if (!empty($onlineMediaAllowed)) {
542 $buttonStyle = '';
543 if (isset($inlineConfiguration['inline']['inlineOnlineMediaAddButtonStyle'])) {
544 $buttonStyle = ' style="' . $inlineConfiguration['inline']['inlineOnlineMediaAddButtonStyle'] . '"';
545 }
546 $this->requireJsModules[] = 'TYPO3/CMS/Backend/OnlineMedia';
547 $buttonText = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:online_media.new_media.button'));
548 $placeholder = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:online_media.new_media.placeholder'));
549 $buttonSubmit = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:online_media.new_media.submit'));
550 $allowedMediaUrl = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.allowEmbedSources'));
551 $item .= '
552 <span class="btn btn-default t3js-online-media-add-btn ' . $this->inlineData['config'][$nameObject]['md5'] . '"
553 ' . $buttonStyle . '
554 data-file-irre-object="' . htmlspecialchars($objectPrefix) . '"
555 data-online-media-allowed="' . htmlspecialchars(implode(',', $onlineMediaAllowed)) . '"
556 data-online-media-allowed-help-text="' . $allowedMediaUrl . '"
557 data-target-folder="' . htmlspecialchars($folder->getCombinedIdentifier()) . '"
558 title="' . $buttonText . '"
559 data-btn-submit="' . $buttonSubmit . '"
560 data-placeholder="' . $placeholder . '"
561 >
562 ' . $this->iconFactory->getIcon('actions-online-media-add', Icon::SIZE_SMALL)->render() . '
563 ' . $buttonText . '</span>';
564 }
565 }
566 }
567
568 $item = '<div class="form-control-wrap">' . $item . '</div>';
569 $allowedList = '';
570 $allowedLabel = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.allowedFileExtensions'));
571 foreach ($allowedArray as $allowedItem) {
572 $allowedList .= '<span class="label label-success">' . strtoupper($allowedItem) . '</span> ';
573 }
574 if (!empty($allowedList)) {
575 $item .= '<div class="help-block">' . $allowedLabel . '<br>' . $allowedList . '</div>';
576 }
577 $item = '<div class="form-group t3js-formengine-validation-marker">' . $item . '</div>';
578 return $item;
579 }
580
581 /**
582 * Get a selector as used for the select type, to select from all available
583 * records and to create a relation to the embedding record (e.g. like MM).
584 *
585 * @param array $config TCA inline configuration of the parent(!) field
586 * @param array $uniqueIds The uids that have already been used and should be unique
587 * @return string A HTML <select> box with all possible records
588 */
589 protected function renderPossibleRecordsSelectorTypeSelect(array $config, array $uniqueIds)
590 {
591 $possibleRecords = $config['selectorOrUniquePossibleRecords'];
592 $nameObject = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
593 // Create option tags:
594 $opt = [];
595 foreach ($possibleRecords as $p) {
596 if (!in_array($p[1], $uniqueIds)) {
597 $opt[] = '<option value="' . htmlspecialchars($p[1]) . '">' . htmlspecialchars($p[0]) . '</option>';
598 }
599 }
600 // Put together the selector box:
601 $size = (int)$config['size'];
602 $size = $config['autoSizeMax'] ? MathUtility::forceIntegerInRange(count($possibleRecords) + 1, MathUtility::forceIntegerInRange($size, 1), $config['autoSizeMax']) : $size;
603 $onChange = 'return inline.importNewRecord(' . GeneralUtility::quoteJSvalue($nameObject . '-' . $config['foreign_table']) . ')';
604 $item = '
605 <select id="' . $nameObject . '-' . $config['foreign_table'] . '_selector" class="form-control"' . ($size ? ' size="' . $size . '"' : '')
606 . ' onchange="' . htmlspecialchars($onChange) . '"' . ($config['foreign_unique'] ? ' isunique="isunique"' : '') . '>
607 ' . implode('', $opt) . '
608 </select>';
609
610 if ($size <= 1) {
611 // Add a "Create new relation" link for adding new relations
612 // This is necessary, if the size of the selector is "1" or if
613 // there is only one record item in the select-box, that is selected by default
614 // The selector-box creates a new relation on using an onChange event (see some line above)
615 if (!empty($config['appearance']['createNewRelationLinkTitle'])) {
616 $createNewRelationText = htmlspecialchars($this->getLanguageService()->sL($config['appearance']['createNewRelationLinkTitle']));
617 } else {
618 $createNewRelationText = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.createNewRelation'));
619 }
620 $item .= '
621 <span class="input-group-btn">
622 <a href="#" class="btn btn-default" onclick="' . htmlspecialchars($onChange) . '" title="' . $createNewRelationText . '">
623 ' . $this->iconFactory->getIcon('actions-add', Icon::SIZE_SMALL)->render() . $createNewRelationText . '
624 </a>
625 </span>';
626 } else {
627 $item .= '
628 <span class="input-group-btn btn"></span>';
629 }
630
631 // Wrap the selector and add a spacer to the bottom
632 $item = '<div class="input-group form-group t3js-formengine-validation-marker ' . $this->inlineData['config'][$nameObject]['md5'] . '">' . $item . '</div>';
633 return $item;
634 }
635
636 /**
637 * Extracts FlexForm parts of a form element name like
638 * data[table][uid][field][sDEF][lDEF][FlexForm][vDEF]
639 * Helper method used in inline
640 *
641 * @param string $formElementName The form element name
642 * @return array|null
643 */
644 protected function extractFlexFormParts($formElementName)
645 {
646 $flexFormParts = null;
647 $matches = [];
648 if (preg_match('#^data(?:\[[^]]+\]){3}(\[data\](?:\[[^]]+\]){4,})$#', $formElementName, $matches)) {
649 $flexFormParts = GeneralUtility::trimExplode(
650 '][',
651 trim($matches[1], '[]')
652 );
653 }
654 return $flexFormParts;
655 }
656
657 /**
658 * @return BackendUserAuthentication
659 */
660 protected function getBackendUserAuthentication()
661 {
662 return $GLOBALS['BE_USER'];
663 }
664
665 /**
666 * @return LanguageService
667 */
668 protected function getLanguageService()
669 {
670 return $GLOBALS['LANG'];
671 }
672 }