NewContentElementController.php 23.5 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Backend\Controller\ContentElement;

4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
16

17
18
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
19
20
use TYPO3\CMS\Backend\Module\AbstractModule;
use TYPO3\CMS\Backend\Template\DocumentTemplate;
Nicole Cordes's avatar
Nicole Cordes committed
21
use TYPO3\CMS\Backend\Utility\BackendUtility;
22
23
use TYPO3\CMS\Backend\View\BackendLayoutView;
use TYPO3\CMS\Backend\Wizard\NewContentElementWizardHookInterface;
24
25
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
26
27
use TYPO3\CMS\Core\Imaging\IconProvider\BitmapIconProvider;
use TYPO3\CMS\Core\Imaging\IconRegistry;
28
use TYPO3\CMS\Core\Utility\ArrayUtility;
Nicole Cordes's avatar
Nicole Cordes committed
29
use TYPO3\CMS\Core\Utility\GeneralUtility;
30
use TYPO3\CMS\Core\Utility\StringUtility;
Nicole Cordes's avatar
Nicole Cordes committed
31

32
33
34
/**
 * Script Class for the New Content element wizard
 */
35
class NewContentElementController extends AbstractModule
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
{
    /**
     * Page id
     *
     * @var int
     */
    public $id;

    /**
     * Sys language
     *
     * @var int
     */
    public $sys_language = 0;

    /**
     * Return URL.
     *
     * @var string
     */
    public $R_URI = '';

    /**
     * If set, the content is destined for a specific column.
     *
     * @var int|null
     */
    public $colPos;

    /**
     * @var int
     */
    public $uid_pid;

    /**
     * Module TSconfig.
     *
     * @var array
     */
    public $modTSconfig = array();

    /**
     * Internal backend template object
     *
80
     * @var DocumentTemplate
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
     */
    public $doc;

    /**
     * Used to accumulate the content of the module.
     *
     * @var string
     */
    public $content;

    /**
     * Access boolean.
     *
     * @var bool
     */
    public $access;

    /**
     * config of the wizard
     *
     * @var array
     */
    public $config;

    /**
     * @var array
     */
    protected $pageInfo;

    /**
     * @var array
     */
    protected $elementWrapper;

    /**
     * @var string
     */
    protected $onClickEvent;

    /**
     * @var array
     */
    protected $MCONF;

    /**
     * Constructor
     */
    public function __construct()
    {
130
        parent::__construct();
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
        $GLOBALS['SOBE'] = $this;
        $this->init();
    }

    /**
     * Constructor, initializing internal variables.
     *
     * @return void
     */
    public function init()
    {
        $lang = $this->getLanguageService();
        $lang->includeLLFile('EXT:lang/locallang_misc.xlf');
        $LOCAL_LANG_orig = $GLOBALS['LOCAL_LANG'];
        $lang->includeLLFile('EXT:backend/Resources/Private/Language/locallang_db_new_content_el.xlf');
146
        ArrayUtility::mergeRecursiveWithOverrule($LOCAL_LANG_orig, $GLOBALS['LOCAL_LANG']);
147
148
149
150
151
152
153
154
155
156
157
158
159
        $GLOBALS['LOCAL_LANG'] = $LOCAL_LANG_orig;

        // Setting internal vars:
        $this->id = (int)GeneralUtility::_GP('id');
        $this->sys_language = (int)GeneralUtility::_GP('sys_language_uid');
        $this->R_URI = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
        $this->colPos = GeneralUtility::_GP('colPos') === null ? null : (int)GeneralUtility::_GP('colPos');
        $this->uid_pid = (int)GeneralUtility::_GP('uid_pid');
        $this->MCONF['name'] = 'xMOD_db_new_content_el';
        $this->modTSconfig = BackendUtility::getModTSconfig($this->id, 'mod.wizards.newContentElement');
        $config = BackendUtility::getPagesTSconfig($this->id);
        $this->config = $config['mod.']['wizards.']['newContentElement.'];
        // Starting the document template object:
160
161
        // We keep this here in case somebody relies on it in a hook or alike
        $this->doc = GeneralUtility::makeInstance(DocumentTemplate::class);
162
        // Setting up the context sensitive menu:
163
        $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu');
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
        // Getting the current page and receiving access information (used in main())
        $perms_clause = $this->getBackendUser()->getPagePermsClause(1);
        $this->pageInfo = BackendUtility::readPageAccess($this->id, $perms_clause);
        $this->access = is_array($this->pageInfo) ? 1 : 0;
    }

    /**
     * Injects the request object for the current request or subrequest
     * As this controller goes only through the main() method, it is rather simple for now
     *
     * @param ServerRequestInterface $request the current request
     * @param ResponseInterface $response
     * @return ResponseInterface the response with the content
     */
    public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
    {
        $this->main();
181
182
        $this->moduleTemplate->setContent($this->content);
        $response->getBody()->write($this->moduleTemplate->renderContent());
183
184
185
186
187
188
        return $response;
    }

    /**
     * Creating the module output.
     *
189
     * @throws \UnexpectedValueException
190
191
192
193
194
     * @return void
     */
    public function main()
    {
        $lang = $this->getLanguageService();
195
        $this->content .= '<form action="" name="editForm" id="NewContentElementController"><input type="hidden" name="defValues" value="" />';
196
197
198
199
200
201
202
203
204
205
206
207
        if ($this->id && $this->access) {
            // Init position map object:
            $posMap = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Tree\View\ContentCreationPagePositionMap::class);
            $posMap->cur_sys_language = $this->sys_language;
            // If a column is pre-set:
            if (isset($this->colPos)) {
                if ($this->uid_pid < 0) {
                    $row = array();
                    $row['uid'] = abs($this->uid_pid);
                } else {
                    $row = '';
                }
208
209
210
211
212
213
214
                $this->onClickEvent = $posMap->onClickInsertRecord(
                    $row,
                    $this->colPos,
                    '',
                    $this->uid_pid,
                    $this->sys_language
                );
215
216
217
218
219
220
            } else {
                $this->onClickEvent = '';
            }
            // ***************************
            // Creating content
            // ***************************
221
            $this->content .= '<h1>' . $lang->getLL('newContentElement') . '</h1>';
222
223
224
225
226
227
228
229
            // Wizard
            $wizardItems = $this->wizardArray();
            // Wrapper for wizards
            $this->elementWrapper['section'] = array('', '');
            // Hook for manipulating wizardItems, wrapper, onClickEvent etc.
            if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms']['db_new_content_el']['wizardItemsHook'])) {
                foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms']['db_new_content_el']['wizardItemsHook'] as $classData) {
                    $hookObject = GeneralUtility::getUserObj($classData);
230
231
232
233
234
                    if (!$hookObject instanceof NewContentElementWizardHookInterface) {
                        throw new \UnexpectedValueException(
                            '$hookObject must implement interface ' . NewContentElementWizardHookInterface::class,
                            1227834741
                        );
235
236
237
238
239
                    }
                    $hookObject->manipulateWizardItems($wizardItems, $this);
                }
            }
            // Add document inline javascript
240
241
242
            $this->moduleTemplate->addJavaScriptCode(
                'NewContentElementWizardInlineJavascript',
                '
243
				function goToalt_doc() {	//
244
					' . $this->onClickEvent . '
245
246
247
248
249
250
				}

				if(top.refreshMenu) {
					top.refreshMenu();
				} else {
					top.TYPO3ModuleMenu.refreshMenu();
251
252
				}'
            );
253

254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
            $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);

            // Traverse items for the wizard.
            // An item is either a header or an item rendered with a radio button and title/description and icon:
            $cc = ($key = 0);
            $menuItems = array();
            foreach ($wizardItems as $k => $wInfo) {
                if ($wInfo['header']) {
                    $menuItems[] = array(
                        'label' => htmlspecialchars($wInfo['header']),
                        'content' => $this->elementWrapper['section'][0]
                    );
                    $key = count($menuItems) - 1;
                } else {
                    $content = '';

                    if (!$this->onClickEvent) {
                        // Radio button:
                        $oC = 'document.editForm.defValues.value=unescape(' . GeneralUtility::quoteJSvalue(rawurlencode($wInfo['params'])) . ');goToalt_doc();' . (!$this->onClickEvent ? 'window.location.hash=\'#sel2\';' : '');
                        $content .= '<div class="media-left"><input type="radio" name="tempB" value="' . htmlspecialchars($k) . '" onclick="' . htmlspecialchars($oC) . '" /></div>';
                        // Onclick action for icon/title:
                        $aOnClick = 'document.getElementsByName(\'tempB\')[' . $cc . '].checked=1;' . $oC . 'return false;';
                    } else {
                        $aOnClick = "document.editForm.defValues.value=unescape('" . rawurlencode($wInfo['params']) . "');goToalt_doc();" . (!$this->onClickEvent?"window.location.hash='#sel2';":'');
                    }

                    if (isset($wInfo['icon'])) {
                        GeneralUtility::deprecationLog('The PageTS-Config: mod.wizards.newContentElement.wizardItems.*.elements.*.icon'
                            . ' is deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8.'
                            . ' Register your icon in IconRegistry::registerIcon and use the new setting:'
284
                            . ' mod.wizards.newContentElement.wizardItems.*.elements.*.iconIdentifier');
285
286
287
288
289
290
291
292
293
294
295
296
                        $wInfo['iconIdentifier'] = 'content-' . $k;
                        $icon = $wInfo['icon'];
                        if (StringUtility::beginsWith($icon, '../typo3conf/ext/')) {
                            $icon = str_replace('../typo3conf/ext/', 'EXT:', $icon);
                        }
                        if (!StringUtility::beginsWith($icon, 'EXT:') && strpos($icon, '/') !== false) {
                            $icon = TYPO3_mainDir . GeneralUtility::resolveBackPath($wInfo['icon']);
                        }
                        $iconRegistry->registerIcon($wInfo['iconIdentifier'], BitmapIconProvider::class, array(
                            'source' => $icon
                        ));
                    }
297
                    $icon = $this->moduleTemplate->getIconFactory()->getIcon($wInfo['iconIdentifier'])->render();
298
                    $menuItems[$key]['content'] .= '
299
						<div class="media">
300
301
302
							<a href="#" onclick="' . htmlspecialchars($aOnClick) . '">
								' . $content . '
								<div class="media-left">
303
									' . $icon . '
304
305
306
								</div>
								<div class="media-body">
									<strong>' . htmlspecialchars($wInfo['title']) . '</strong>' .
307
308
309
                                    '<br />' .
                                    nl2br(htmlspecialchars(trim($wInfo['description']))) .
                                '</div>
310
							</a>
311
						</div>';
312
313
314
315
316
317
318
319
                    $cc++;
                }
            }
            // Add closing section-tag
            foreach ($menuItems as $key => $val) {
                $menuItems[$key]['content'] .= $this->elementWrapper['section'][1];
            }
            // Add the wizard table to the content, wrapped in tabs
320
321
322
323
324
325
326
327
328
329
330
            $code = '<p>' . $lang->getLL('sel1', 1) . '</p>' . $this->moduleTemplate->getDynamicTabMenu(
                $menuItems,
                'new-content-element-wizard'
            );

            $this->content .= $this->moduleTemplate->section(
                !$this->onClickEvent ? $lang->getLL('1_selectType') : '',
                $code,
                0,
                1
            );
331
332
333
            // If the user must also select a column:
            if (!$this->onClickEvent) {
                // Add anchor "sel2"
334
                $this->content .= $this->moduleTemplate->section('', '<a name="sel2"></a>');
335
336
337
338
                // Select position
                $code = '<p>' . $lang->getLL('sel2', 1) . '</p>';

                // Load SHARED page-TSconfig settings and retrieve column list from there, if applicable:
339
340
341
342
343
                $colPosArray = GeneralUtility::callUserFunction(
                    BackendLayoutView::class . '->getColPosListItemsParsed',
                    $this->id,
                    $this
                );
344
345
346
347
348
                $colPosIds = array_column($colPosArray, 1);
                // Removing duplicates, if any
                $colPosList = implode(',', array_unique(array_map('intval', $colPosIds)));
                // Finally, add the content of the column selector to the content:
                $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
352
353
            }
        } else {
            // In case of no access:
            $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
363
364
365
    }

    /**
     * Create the panel of buttons for submitting the form or otherwise perform operations.
     */
    protected function getButtons()
    {
366
367
368
369
370
371
372
373
374
375
        $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
        if ($this->R_URI) {
            $backButton = $buttonBar->makeLinkButton()
                ->setHref($this->R_URI)
                ->setTitle($this->getLanguageService()->getLL('goBack', true))
                ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
                    'actions-view-go-back',
                    Icon::SIZE_SMALL
                ));
            $buttonBar->addButton($backButton);
376
        }
377
378
        $cshButton = $buttonBar->makeHelpButton()->setModuleName('xMOD_csh_corebe')->setFieldName('new_ce');
        $buttonBar->addButton($cshButton);
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    }

    /***************************
     *
     * OTHER FUNCTIONS:
     *
     ***************************/
    /**
     * Returns the content of wizardArray() function...
     *
     * @return array Returns the content of wizardArray() function...
     * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8, use "wizardArray()" directly
     */
    public function getWizardItems()
    {
        GeneralUtility::logDeprecatedFunction();
        return $this->wizardArray();
    }

    /**
     * Returns the array of elements in the wizard display.
     * For the plugin section there is support for adding elements there from a global variable.
     *
     * @return array
     */
    public function wizardArray()
    {
        $wizardItems = array();
        if (is_array($this->config)) {
            $wizards = $this->config['wizardItems.'];
            $appendWizards = $this->wizard_appendWizards($wizards['elements.']);
            if (is_array($wizards)) {
                foreach ($wizards as $groupKey => $wizardGroup) {
                    $groupKey = rtrim($groupKey, '.');
                    $showItems = GeneralUtility::trimExplode(',', $wizardGroup['show'], true);
                    $showAll = $wizardGroup['show'] === '*';
                    $groupItems = array();
                    if (is_array($appendWizards[$groupKey . '.']['elements.'])) {
                        $wizardElements = array_merge((array)$wizardGroup['elements.'], $appendWizards[$groupKey . '.']['elements.']);
                    } else {
                        $wizardElements = $wizardGroup['elements.'];
                    }
                    if (is_array($wizardElements)) {
                        foreach ($wizardElements as $itemKey => $itemConf) {
                            $itemKey = rtrim($itemKey, '.');
                            if ($showAll || in_array($itemKey, $showItems)) {
                                $tmpItem = $this->wizard_getItem($groupKey, $itemKey, $itemConf);
                                if ($tmpItem) {
                                    $groupItems[$groupKey . '_' . $itemKey] = $tmpItem;
                                }
                            }
                        }
                    }
                    if (!empty($groupItems)) {
                        $wizardItems[$groupKey] = $this->wizard_getGroupHeader($groupKey, $wizardGroup);
                        $wizardItems = array_merge($wizardItems, $groupItems);
                    }
                }
            }
        }
        // Remove elements where preset values are not allowed:
        $this->removeInvalidElements($wizardItems);
        return $wizardItems;
    }

    /**
     * @param mixed $wizardElements
     * @return array
     */
    public function wizard_appendWizards($wizardElements)
    {
        if (!is_array($wizardElements)) {
            $wizardElements = array();
        }
        if (is_array($GLOBALS['TBE_MODULES_EXT']['xMOD_db_new_content_el']['addElClasses'])) {
            foreach ($GLOBALS['TBE_MODULES_EXT']['xMOD_db_new_content_el']['addElClasses'] as $class => $path) {
                require_once $path;
                $modObj = GeneralUtility::makeInstance($class);
                $wizardElements = $modObj->proc($wizardElements);
            }
        }
        $returnElements = array();
        foreach ($wizardElements as $key => $wizardItem) {
            preg_match('/^[a-zA-Z0-9]+_/', $key, $group);
            $wizardGroup = $group[0] ? substr($group[0], 0, -1) . '.' : $key;
            $returnElements[$wizardGroup]['elements.'][substr($key, strlen($wizardGroup)) . '.'] = $wizardItem;
        }
        return $returnElements;
    }

    /**
     * @param string $groupKey Not used
     * @param string $itemKey Not used
     * @param array $itemConf
     * @return array
     */
    public function wizard_getItem($groupKey, $itemKey, $itemConf)
    {
        $itemConf['title'] = $this->getLanguageService()->sL($itemConf['title']);
        $itemConf['description'] = $this->getLanguageService()->sL($itemConf['description']);
        $itemConf['tt_content_defValues'] = $itemConf['tt_content_defValues.'];
        unset($itemConf['tt_content_defValues.']);
        return $itemConf;
    }

    /**
     * @param string $groupKey Not used
     * @param array $wizardGroup
     * @return array
     */
    public function wizard_getGroupHeader($groupKey, $wizardGroup)
    {
        return array(
            'header' => $this->getLanguageService()->sL($wizardGroup['header'])
        );
    }

    /**
     * Checks the array for elements which might contain unallowed default values and will unset them!
498
499
     * Looks for the "tt_content_defValues" key in each element and if found it will traverse that array as fieldname /
     * value pairs and check.
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
     * The values will be added to the "params" key of the array (which should probably be unset or empty by default).
     *
     * @param array $wizardItems Wizard items, passed by reference
     * @return void
     */
    public function removeInvalidElements(&$wizardItems)
    {
        // Get TCEFORM from TSconfig of current page
        $row = array('pid' => $this->id);
        $TCEFORM_TSconfig = BackendUtility::getTCEFORM_TSconfig('tt_content', $row);
        $headersUsed = array();
        // Traverse wizard items:
        foreach ($wizardItems as $key => $cfg) {
            // Exploding parameter string, if any (old style)
            if ($wizardItems[$key]['params']) {
                // Explode GET vars recursively
                $tempGetVars = GeneralUtility::explodeUrl2Array($wizardItems[$key]['params'], true);
                // If tt_content values are set, merge them into the tt_content_defValues array,
                // unset them from $tempGetVars and re-implode $tempGetVars into the param string
                // (in case remaining parameters are around).
                if (is_array($tempGetVars['defVals']['tt_content'])) {
                    $wizardItems[$key]['tt_content_defValues'] = array_merge(
522
                        is_array($wizardItems[$key]['tt_content_defValues']) ? $wizardItems[$key]['tt_content_defValues'] : array(),
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
                        $tempGetVars['defVals']['tt_content']
                    );
                    unset($tempGetVars['defVals']['tt_content']);
                    $wizardItems[$key]['params'] = GeneralUtility::implodeArrayForUrl('', $tempGetVars);
                }
            }
            // If tt_content_defValues are defined...:
            if (is_array($wizardItems[$key]['tt_content_defValues'])) {
                $backendUser = $this->getBackendUser();
                // Traverse field values:
                foreach ($wizardItems[$key]['tt_content_defValues'] as $fN => $fV) {
                    if (is_array($GLOBALS['TCA']['tt_content']['columns'][$fN])) {
                        // Get information about if the field value is OK:
                        $config = &$GLOBALS['TCA']['tt_content']['columns'][$fN]['config'];
                        $authModeDeny = $config['type'] == 'select' && $config['authMode']
                            && !$backendUser->checkAuthMode('tt_content', $fN, $fV, $config['authMode']);
                        // explode TSconfig keys only as needed
                        if (!isset($removeItems[$fN])) {
541
542
543
544
545
                            $removeItems[$fN] = GeneralUtility::trimExplode(
                                ',',
                                $TCEFORM_TSconfig[$fN]['removeItems'],
                                true
                            );
546
547
                        }
                        if (!isset($keepItems[$fN])) {
548
549
550
551
552
                            $keepItems[$fN] = GeneralUtility::trimExplode(
                                ',',
                                $TCEFORM_TSconfig[$fN]['keepItems'],
                                true
                            );
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
                        }
                        $isNotInKeepItems = !empty($keepItems[$fN]) && !in_array($fV, $keepItems[$fN]);
                        if ($authModeDeny || $fN === 'CType' && in_array($fV, $removeItems[$fN]) || $isNotInKeepItems) {
                            // Remove element all together:
                            unset($wizardItems[$key]);
                            break;
                        } else {
                            // Add the parameter:
                            $wizardItems[$key]['params'] .= '&defVals[tt_content][' . $fN . ']=' . rawurlencode($fV);
                            $tmp = explode('_', $key);
                            $headersUsed[$tmp[0]] = $tmp[0];
                        }
                    }
                }
            }
        }
        // remove headers without elements
        foreach ($wizardItems as $key => $cfg) {
            $tmp = explode('_', $key);
            if ($tmp[0] && !$tmp[1] && !in_array($tmp[0], $headersUsed)) {
                unset($wizardItems[$key]);
            }
        }
    }

    /**
     * Returns LanguageService
     *
     * @return \TYPO3\CMS\Lang\LanguageService
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }

    /**
     * Returns the current BE user.
     *
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
     */
    protected function getBackendUser()
    {
        return $GLOBALS['BE_USER'];
    }
597
}