[TASK] Remove usage of setForm from NewContentElementController
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / ContentElement / NewContentElementController.php
1 <?php
2 namespace TYPO3\CMS\Backend\Controller\ContentElement;
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 Psr\Http\Message\ServerRequestInterface;
18 use Psr\Http\Message\ResponseInterface;
19 use TYPO3\CMS\Backend\Module\AbstractModule;
20 use TYPO3\CMS\Backend\Template\DocumentTemplate;
21 use TYPO3\CMS\Backend\Utility\BackendUtility;
22 use TYPO3\CMS\Backend\View\BackendLayoutView;
23 use TYPO3\CMS\Backend\Wizard\NewContentElementWizardHookInterface;
24 use TYPO3\CMS\Core\Imaging\Icon;
25 use TYPO3\CMS\Core\Imaging\IconFactory;
26 use TYPO3\CMS\Core\Imaging\IconProvider\BitmapIconProvider;
27 use TYPO3\CMS\Core\Imaging\IconRegistry;
28 use TYPO3\CMS\Core\Utility\ArrayUtility;
29 use TYPO3\CMS\Core\Utility\GeneralUtility;
30 use TYPO3\CMS\Core\Utility\StringUtility;
31
32 /**
33 * Script Class for the New Content element wizard
34 */
35 class NewContentElementController extends AbstractModule
36 {
37 /**
38 * Page id
39 *
40 * @var int
41 */
42 public $id;
43
44 /**
45 * Sys language
46 *
47 * @var int
48 */
49 public $sys_language = 0;
50
51 /**
52 * Return URL.
53 *
54 * @var string
55 */
56 public $R_URI = '';
57
58 /**
59 * If set, the content is destined for a specific column.
60 *
61 * @var int|null
62 */
63 public $colPos;
64
65 /**
66 * @var int
67 */
68 public $uid_pid;
69
70 /**
71 * Module TSconfig.
72 *
73 * @var array
74 */
75 public $modTSconfig = array();
76
77 /**
78 * Internal backend template object
79 *
80 * @var DocumentTemplate
81 */
82 public $doc;
83
84 /**
85 * Used to accumulate the content of the module.
86 *
87 * @var string
88 */
89 public $content;
90
91 /**
92 * Access boolean.
93 *
94 * @var bool
95 */
96 public $access;
97
98 /**
99 * config of the wizard
100 *
101 * @var array
102 */
103 public $config;
104
105 /**
106 * @var array
107 */
108 protected $pageInfo;
109
110 /**
111 * @var array
112 */
113 protected $elementWrapper;
114
115 /**
116 * @var string
117 */
118 protected $onClickEvent;
119
120 /**
121 * @var array
122 */
123 protected $MCONF;
124
125 /**
126 * Constructor
127 */
128 public function __construct()
129 {
130 parent::__construct();
131 $GLOBALS['SOBE'] = $this;
132 $this->init();
133 }
134
135 /**
136 * Constructor, initializing internal variables.
137 *
138 * @return void
139 */
140 public function init()
141 {
142 $lang = $this->getLanguageService();
143 $lang->includeLLFile('EXT:lang/locallang_misc.xlf');
144 $LOCAL_LANG_orig = $GLOBALS['LOCAL_LANG'];
145 $lang->includeLLFile('EXT:backend/Resources/Private/Language/locallang_db_new_content_el.xlf');
146 ArrayUtility::mergeRecursiveWithOverrule($LOCAL_LANG_orig, $GLOBALS['LOCAL_LANG']);
147 $GLOBALS['LOCAL_LANG'] = $LOCAL_LANG_orig;
148
149 // Setting internal vars:
150 $this->id = (int)GeneralUtility::_GP('id');
151 $this->sys_language = (int)GeneralUtility::_GP('sys_language_uid');
152 $this->R_URI = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
153 $this->colPos = GeneralUtility::_GP('colPos') === null ? null : (int)GeneralUtility::_GP('colPos');
154 $this->uid_pid = (int)GeneralUtility::_GP('uid_pid');
155 $this->MCONF['name'] = 'xMOD_db_new_content_el';
156 $this->modTSconfig = BackendUtility::getModTSconfig($this->id, 'mod.wizards.newContentElement');
157 $config = BackendUtility::getPagesTSconfig($this->id);
158 $this->config = $config['mod.']['wizards.']['newContentElement.'];
159 // Starting the document template object:
160 // We keep this here in case somebody relies on it in a hook or alike
161 $this->doc = GeneralUtility::makeInstance(DocumentTemplate::class);
162 // Setting up the context sensitive menu:
163 $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu');
164 // Getting the current page and receiving access information (used in main())
165 $perms_clause = $this->getBackendUser()->getPagePermsClause(1);
166 $this->pageInfo = BackendUtility::readPageAccess($this->id, $perms_clause);
167 $this->access = is_array($this->pageInfo) ? 1 : 0;
168 }
169
170 /**
171 * Injects the request object for the current request or subrequest
172 * As this controller goes only through the main() method, it is rather simple for now
173 *
174 * @param ServerRequestInterface $request the current request
175 * @param ResponseInterface $response
176 * @return ResponseInterface the response with the content
177 */
178 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
179 {
180 $this->main();
181 $this->moduleTemplate->setContent($this->content);
182 $response->getBody()->write($this->moduleTemplate->renderContent());
183 return $response;
184 }
185
186 /**
187 * Creating the module output.
188 *
189 * @throws \UnexpectedValueException
190 * @return void
191 */
192 public function main()
193 {
194 $lang = $this->getLanguageService();
195 $this->content .= '<form action="" name="editForm" id="NewContentElementController"><input type="hidden" name="defValues" value="" />';
196 if ($this->id && $this->access) {
197 // Init position map object:
198 $posMap = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Tree\View\ContentCreationPagePositionMap::class);
199 $posMap->cur_sys_language = $this->sys_language;
200 // If a column is pre-set:
201 if (isset($this->colPos)) {
202 if ($this->uid_pid < 0) {
203 $row = array();
204 $row['uid'] = abs($this->uid_pid);
205 } else {
206 $row = '';
207 }
208 $this->onClickEvent = $posMap->onClickInsertRecord(
209 $row,
210 $this->colPos,
211 '',
212 $this->uid_pid,
213 $this->sys_language
214 );
215 } else {
216 $this->onClickEvent = '';
217 }
218 // ***************************
219 // Creating content
220 // ***************************
221 $this->content .= '<h1>' . $lang->getLL('newContentElement') . '</h1>';
222 // Wizard
223 $wizardItems = $this->wizardArray();
224 // Wrapper for wizards
225 $this->elementWrapper['section'] = array('', '');
226 // Hook for manipulating wizardItems, wrapper, onClickEvent etc.
227 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms']['db_new_content_el']['wizardItemsHook'])) {
228 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms']['db_new_content_el']['wizardItemsHook'] as $classData) {
229 $hookObject = GeneralUtility::getUserObj($classData);
230 if (!$hookObject instanceof NewContentElementWizardHookInterface) {
231 throw new \UnexpectedValueException(
232 '$hookObject must implement interface ' . NewContentElementWizardHookInterface::class,
233 1227834741
234 );
235 }
236 $hookObject->manipulateWizardItems($wizardItems, $this);
237 }
238 }
239 // Add document inline javascript
240 $this->moduleTemplate->addJavaScriptCode(
241 'NewContentElementWizardInlineJavascript',
242 '
243 function goToalt_doc() { //
244 ' . $this->onClickEvent . '
245 }
246
247 if(top.refreshMenu) {
248 top.refreshMenu();
249 } else {
250 top.TYPO3ModuleMenu.refreshMenu();
251 }'
252 );
253
254 $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
255
256 // Traverse items for the wizard.
257 // An item is either a header or an item rendered with a radio button and title/description and icon:
258 $cc = ($key = 0);
259 $menuItems = array();
260 foreach ($wizardItems as $k => $wInfo) {
261 if ($wInfo['header']) {
262 $menuItems[] = array(
263 'label' => htmlspecialchars($wInfo['header']),
264 'content' => $this->elementWrapper['section'][0]
265 );
266 $key = count($menuItems) - 1;
267 } else {
268 $content = '';
269
270 if (!$this->onClickEvent) {
271 // Radio button:
272 $oC = 'document.editForm.defValues.value=unescape(' . GeneralUtility::quoteJSvalue(rawurlencode($wInfo['params'])) . ');goToalt_doc();' . (!$this->onClickEvent ? 'window.location.hash=\'#sel2\';' : '');
273 $content .= '<div class="media-left"><input type="radio" name="tempB" value="' . htmlspecialchars($k) . '" onclick="' . htmlspecialchars($oC) . '" /></div>';
274 // Onclick action for icon/title:
275 $aOnClick = 'document.getElementsByName(\'tempB\')[' . $cc . '].checked=1;' . $oC . 'return false;';
276 } else {
277 $aOnClick = "document.editForm.defValues.value=unescape('" . rawurlencode($wInfo['params']) . "');goToalt_doc();" . (!$this->onClickEvent?"window.location.hash='#sel2';":'');
278 }
279
280 if (isset($wInfo['icon'])) {
281 GeneralUtility::deprecationLog('The PageTS-Config: mod.wizards.newContentElement.wizardItems.*.elements.*.icon'
282 . ' is deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8.'
283 . ' Register your icon in IconRegistry::registerIcon and use the new setting:'
284 . ' mod.wizards.newContentElement.wizardItems.*.elements.*.iconIdentifier');
285 $wInfo['iconIdentifier'] = 'content-' . $k;
286 $icon = $wInfo['icon'];
287 if (StringUtility::beginsWith($icon, '../typo3conf/ext/')) {
288 $icon = str_replace('../typo3conf/ext/', 'EXT:', $icon);
289 }
290 if (!StringUtility::beginsWith($icon, 'EXT:') && strpos($icon, '/') !== false) {
291 $icon = TYPO3_mainDir . GeneralUtility::resolveBackPath($wInfo['icon']);
292 }
293 $iconRegistry->registerIcon($wInfo['iconIdentifier'], BitmapIconProvider::class, array(
294 'source' => $icon
295 ));
296 }
297 $icon = $this->moduleTemplate->getIconFactory()->getIcon($wInfo['iconIdentifier'])->render();
298 $menuItems[$key]['content'] .= '
299 <div class="media">
300 <a href="#" onclick="' . htmlspecialchars($aOnClick) . '">
301 ' . $content . '
302 <div class="media-left">
303 ' . $icon . '
304 </div>
305 <div class="media-body">
306 <strong>' . htmlspecialchars($wInfo['title']) . '</strong>' .
307 '<br />' .
308 nl2br(htmlspecialchars(trim($wInfo['description']))) .
309 '</div>
310 </a>
311 </div>';
312 $cc++;
313 }
314 }
315 // Add closing section-tag
316 foreach ($menuItems as $key => $val) {
317 $menuItems[$key]['content'] .= $this->elementWrapper['section'][1];
318 }
319 // Add the wizard table to the content, wrapped in tabs
320 $code = '<p>' . $lang->getLL('sel1', 1) . '</p>' . $this->moduleTemplate->getDynamicTabMenu(
321 $menuItems,
322 'new-content-element-wizard'
323 );
324
325 $this->content .= $this->moduleTemplate->section(
326 !$this->onClickEvent ? $lang->getLL('1_selectType') : '',
327 $code,
328 0,
329 1
330 );
331 // If the user must also select a column:
332 if (!$this->onClickEvent) {
333 // Add anchor "sel2"
334 $this->content .= $this->moduleTemplate->section('', '<a name="sel2"></a>');
335 // Select position
336 $code = '<p>' . $lang->getLL('sel2', 1) . '</p>';
337
338 // Load SHARED page-TSconfig settings and retrieve column list from there, if applicable:
339 $colPosArray = GeneralUtility::callUserFunction(
340 BackendLayoutView::class . '->getColPosListItemsParsed',
341 $this->id,
342 $this
343 );
344 $colPosIds = array_column($colPosArray, 1);
345 // Removing duplicates, if any
346 $colPosList = implode(',', array_unique(array_map('intval', $colPosIds)));
347 // Finally, add the content of the column selector to the content:
348 $code .= $posMap->printContentElementColumns($this->id, 0, $colPosList, 1, $this->R_URI);
349 $this->content .= $this->moduleTemplate->section($lang->getLL('2_selectPosition'), $code, 0, 1);
350 }
351 } else {
352 // In case of no access:
353 $this->content = '';
354 $this->content .= '<h1>' . $lang->getLL('newContentElement') . '</h1>';
355 }
356 $this->content .= '</form>';
357 // Setting up the buttons and markers for docheader
358 $this->getButtons();
359 }
360
361 /**
362 * Create the panel of buttons for submitting the form or otherwise perform operations.
363 */
364 protected function getButtons()
365 {
366 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
367 if ($this->R_URI) {
368 $backButton = $buttonBar->makeLinkButton()
369 ->setHref($this->R_URI)
370 ->setTitle($this->getLanguageService()->getLL('goBack', true))
371 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
372 'actions-view-go-back',
373 Icon::SIZE_SMALL
374 ));
375 $buttonBar->addButton($backButton);
376 }
377 $cshButton = $buttonBar->makeHelpButton()->setModuleName('xMOD_csh_corebe')->setFieldName('new_ce');
378 $buttonBar->addButton($cshButton);
379 }
380
381 /***************************
382 *
383 * OTHER FUNCTIONS:
384 *
385 ***************************/
386 /**
387 * Returns the content of wizardArray() function...
388 *
389 * @return array Returns the content of wizardArray() function...
390 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8, use "wizardArray()" directly
391 */
392 public function getWizardItems()
393 {
394 GeneralUtility::logDeprecatedFunction();
395 return $this->wizardArray();
396 }
397
398 /**
399 * Returns the array of elements in the wizard display.
400 * For the plugin section there is support for adding elements there from a global variable.
401 *
402 * @return array
403 */
404 public function wizardArray()
405 {
406 $wizardItems = array();
407 if (is_array($this->config)) {
408 $wizards = $this->config['wizardItems.'];
409 $appendWizards = $this->wizard_appendWizards($wizards['elements.']);
410 if (is_array($wizards)) {
411 foreach ($wizards as $groupKey => $wizardGroup) {
412 $groupKey = rtrim($groupKey, '.');
413 $showItems = GeneralUtility::trimExplode(',', $wizardGroup['show'], true);
414 $showAll = $wizardGroup['show'] === '*';
415 $groupItems = array();
416 if (is_array($appendWizards[$groupKey . '.']['elements.'])) {
417 $wizardElements = array_merge((array)$wizardGroup['elements.'], $appendWizards[$groupKey . '.']['elements.']);
418 } else {
419 $wizardElements = $wizardGroup['elements.'];
420 }
421 if (is_array($wizardElements)) {
422 foreach ($wizardElements as $itemKey => $itemConf) {
423 $itemKey = rtrim($itemKey, '.');
424 if ($showAll || in_array($itemKey, $showItems)) {
425 $tmpItem = $this->wizard_getItem($groupKey, $itemKey, $itemConf);
426 if ($tmpItem) {
427 $groupItems[$groupKey . '_' . $itemKey] = $tmpItem;
428 }
429 }
430 }
431 }
432 if (!empty($groupItems)) {
433 $wizardItems[$groupKey] = $this->wizard_getGroupHeader($groupKey, $wizardGroup);
434 $wizardItems = array_merge($wizardItems, $groupItems);
435 }
436 }
437 }
438 }
439 // Remove elements where preset values are not allowed:
440 $this->removeInvalidElements($wizardItems);
441 return $wizardItems;
442 }
443
444 /**
445 * @param mixed $wizardElements
446 * @return array
447 */
448 public function wizard_appendWizards($wizardElements)
449 {
450 if (!is_array($wizardElements)) {
451 $wizardElements = array();
452 }
453 if (is_array($GLOBALS['TBE_MODULES_EXT']['xMOD_db_new_content_el']['addElClasses'])) {
454 foreach ($GLOBALS['TBE_MODULES_EXT']['xMOD_db_new_content_el']['addElClasses'] as $class => $path) {
455 require_once $path;
456 $modObj = GeneralUtility::makeInstance($class);
457 $wizardElements = $modObj->proc($wizardElements);
458 }
459 }
460 $returnElements = array();
461 foreach ($wizardElements as $key => $wizardItem) {
462 preg_match('/^[a-zA-Z0-9]+_/', $key, $group);
463 $wizardGroup = $group[0] ? substr($group[0], 0, -1) . '.' : $key;
464 $returnElements[$wizardGroup]['elements.'][substr($key, strlen($wizardGroup)) . '.'] = $wizardItem;
465 }
466 return $returnElements;
467 }
468
469 /**
470 * @param string $groupKey Not used
471 * @param string $itemKey Not used
472 * @param array $itemConf
473 * @return array
474 */
475 public function wizard_getItem($groupKey, $itemKey, $itemConf)
476 {
477 $itemConf['title'] = $this->getLanguageService()->sL($itemConf['title']);
478 $itemConf['description'] = $this->getLanguageService()->sL($itemConf['description']);
479 $itemConf['tt_content_defValues'] = $itemConf['tt_content_defValues.'];
480 unset($itemConf['tt_content_defValues.']);
481 return $itemConf;
482 }
483
484 /**
485 * @param string $groupKey Not used
486 * @param array $wizardGroup
487 * @return array
488 */
489 public function wizard_getGroupHeader($groupKey, $wizardGroup)
490 {
491 return array(
492 'header' => $this->getLanguageService()->sL($wizardGroup['header'])
493 );
494 }
495
496 /**
497 * Checks the array for elements which might contain unallowed default values and will unset them!
498 * Looks for the "tt_content_defValues" key in each element and if found it will traverse that array as fieldname /
499 * value pairs and check.
500 * The values will be added to the "params" key of the array (which should probably be unset or empty by default).
501 *
502 * @param array $wizardItems Wizard items, passed by reference
503 * @return void
504 */
505 public function removeInvalidElements(&$wizardItems)
506 {
507 // Get TCEFORM from TSconfig of current page
508 $row = array('pid' => $this->id);
509 $TCEFORM_TSconfig = BackendUtility::getTCEFORM_TSconfig('tt_content', $row);
510 $headersUsed = array();
511 // Traverse wizard items:
512 foreach ($wizardItems as $key => $cfg) {
513 // Exploding parameter string, if any (old style)
514 if ($wizardItems[$key]['params']) {
515 // Explode GET vars recursively
516 $tempGetVars = GeneralUtility::explodeUrl2Array($wizardItems[$key]['params'], true);
517 // If tt_content values are set, merge them into the tt_content_defValues array,
518 // unset them from $tempGetVars and re-implode $tempGetVars into the param string
519 // (in case remaining parameters are around).
520 if (is_array($tempGetVars['defVals']['tt_content'])) {
521 $wizardItems[$key]['tt_content_defValues'] = array_merge(
522 is_array($wizardItems[$key]['tt_content_defValues']) ? $wizardItems[$key]['tt_content_defValues'] : array(),
523 $tempGetVars['defVals']['tt_content']
524 );
525 unset($tempGetVars['defVals']['tt_content']);
526 $wizardItems[$key]['params'] = GeneralUtility::implodeArrayForUrl('', $tempGetVars);
527 }
528 }
529 // If tt_content_defValues are defined...:
530 if (is_array($wizardItems[$key]['tt_content_defValues'])) {
531 $backendUser = $this->getBackendUser();
532 // Traverse field values:
533 foreach ($wizardItems[$key]['tt_content_defValues'] as $fN => $fV) {
534 if (is_array($GLOBALS['TCA']['tt_content']['columns'][$fN])) {
535 // Get information about if the field value is OK:
536 $config = &$GLOBALS['TCA']['tt_content']['columns'][$fN]['config'];
537 $authModeDeny = $config['type'] == 'select' && $config['authMode']
538 && !$backendUser->checkAuthMode('tt_content', $fN, $fV, $config['authMode']);
539 // explode TSconfig keys only as needed
540 if (!isset($removeItems[$fN])) {
541 $removeItems[$fN] = GeneralUtility::trimExplode(
542 ',',
543 $TCEFORM_TSconfig[$fN]['removeItems'],
544 true
545 );
546 }
547 if (!isset($keepItems[$fN])) {
548 $keepItems[$fN] = GeneralUtility::trimExplode(
549 ',',
550 $TCEFORM_TSconfig[$fN]['keepItems'],
551 true
552 );
553 }
554 $isNotInKeepItems = !empty($keepItems[$fN]) && !in_array($fV, $keepItems[$fN]);
555 if ($authModeDeny || $fN === 'CType' && in_array($fV, $removeItems[$fN]) || $isNotInKeepItems) {
556 // Remove element all together:
557 unset($wizardItems[$key]);
558 break;
559 } else {
560 // Add the parameter:
561 $wizardItems[$key]['params'] .= '&defVals[tt_content][' . $fN . ']=' . rawurlencode($fV);
562 $tmp = explode('_', $key);
563 $headersUsed[$tmp[0]] = $tmp[0];
564 }
565 }
566 }
567 }
568 }
569 // remove headers without elements
570 foreach ($wizardItems as $key => $cfg) {
571 $tmp = explode('_', $key);
572 if ($tmp[0] && !$tmp[1] && !in_array($tmp[0], $headersUsed)) {
573 unset($wizardItems[$key]);
574 }
575 }
576 }
577
578 /**
579 * Returns LanguageService
580 *
581 * @return \TYPO3\CMS\Lang\LanguageService
582 */
583 protected function getLanguageService()
584 {
585 return $GLOBALS['LANG'];
586 }
587
588 /**
589 * Returns the current BE user.
590 *
591 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
592 */
593 protected function getBackendUser()
594 {
595 return $GLOBALS['BE_USER'];
596 }
597 }