FormManagerController.php 20.7 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
 * This file is part of the TYPO3 CMS project.
 *
 * 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.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

18
19
namespace TYPO3\CMS\Form\Controller;

20
use Symfony\Component\Yaml\Yaml;
21
use TYPO3\CMS\Backend\Routing\UriBuilder;
22
23
24
25
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Backend\View\BackendTemplateView;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
26
use TYPO3\CMS\Core\Charset\CharsetConverter;
27
28
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
29
use TYPO3\CMS\Core\Localization\LanguageService;
30
31
use TYPO3\CMS\Core\Messaging\AbstractMessage;
use TYPO3\CMS\Core\Page\PageRenderer;
32
use TYPO3\CMS\Core\Utility\ArrayUtility;
33
34
35
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\View\JsonView;
use TYPO3\CMS\Form\Exception as FormException;
36
use TYPO3\CMS\Form\Mvc\Persistence\Exception\PersistenceManagerException;
37
use TYPO3\CMS\Form\Service\DatabaseService;
38
39
40
41
42
43
use TYPO3\CMS\Form\Service\TranslationService;

/**
 * The form manager controller
 *
 * Scope: backend
44
 * @internal
45
46
47
48
 */
class FormManagerController extends AbstractBackendController
{

49
50
51
52
53
54
55
56
57
    /**
     * @var DatabaseService
     */
    protected $databaseService;

    /**
     * @param \TYPO3\CMS\Form\Service\DatabaseService $databaseService
     * @internal
     */
58
    public function injectDatabaseService(DatabaseService $databaseService)
59
60
61
62
    {
        $this->databaseService = $databaseService;
    }

63
64
65
    /**
     * Default View Container
     *
66
     * @var string
67
68
69
70
71
72
73
74
75
76
77
78
     */
    protected $defaultViewObjectName = BackendTemplateView::class;

    /**
     * Displays the Form Manager
     *
     * @internal
     */
    public function indexAction()
    {
        $this->registerDocheaderButtons();
        $this->view->getModuleTemplate()->setModuleName($this->request->getPluginName() . '_' . $this->request->getControllerName());
79
        $this->view->getModuleTemplate()->setFlashMessageQueue($this->getFlashMessageQueue());
80
81
82
83
84
85
86
87
88
89

        $this->view->assign('forms', $this->getAvailableFormDefinitions());
        $this->view->assign('stylesheets', $this->resolveResourcePaths($this->formSettings['formManager']['stylesheets']));
        $this->view->assign('dynamicRequireJsModules', $this->formSettings['formManager']['dynamicRequireJsModules']);
        $this->view->assign('formManagerAppInitialData', $this->getFormManagerAppInitialData());
        if (!empty($this->formSettings['formManager']['javaScriptTranslationFile'])) {
            $this->getPageRenderer()->addInlineLanguageLabelFile($this->formSettings['formManager']['javaScriptTranslationFile']);
        }
    }

90
91
92
93
94
95
96
97
98
99
100
    /**
     * Initialize the create action.
     * This action uses the Fluid JsonView::class as view.
     *
     * @internal
     */
    public function initializeCreateAction()
    {
        $this->defaultViewObjectName = JsonView::class;
    }

101
102
103
104
105
106
107
108
109
110
    /**
     * Creates a new Form and redirects to the Form Editor
     *
     * @param string $formName
     * @param string $templatePath
     * @param string $prototypeName
     * @param string $savePath
     * @throws FormException
     * @internal
     */
111
    public function createAction(string $formName, string $templatePath, string $prototypeName, string $savePath)
112
113
114
115
116
    {
        if (!$this->isValidTemplatePath($prototypeName, $templatePath)) {
            throw new FormException(sprintf('The template path "%s" is not allowed', $templatePath), 1329233410);
        }
        if (empty($formName)) {
117
            throw new FormException('No form name', 1472312204);
118
119
        }

120
        $templatePath = GeneralUtility::getFileAbsFileName($templatePath);
121
        $form = Yaml::parse((string)file_get_contents($templatePath));
122
123
124
125
126
        $form['label'] = $formName;
        $form['identifier'] = $this->formPersistenceManager->getUniqueIdentifier($this->convertFormNameToIdentifier($formName));
        $form['prototypeName'] = $prototypeName;

        $formPersistenceIdentifier = $this->formPersistenceManager->getUniquePersistenceIdentifier($form['identifier'], $savePath);
Benni Mack's avatar
Benni Mack committed
127

128
129
130
131
132
133
134
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/form']['beforeFormCreate'] ?? [] as $className) {
            $hookObj = GeneralUtility::makeInstance($className);
            if (method_exists($hookObj, 'beforeFormCreate')) {
                $form = $hookObj->beforeFormCreate(
                    $formPersistenceIdentifier,
                    $form
                );
135
136
            }
        }
Benni Mack's avatar
Benni Mack committed
137

138
139
        $response = [
            'status' => 'success',
140
            'url' => $this->uriBuilder->uriFor('index', ['formPersistenceIdentifier' => $formPersistenceIdentifier], 'FormEditor')
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
        ];

        try {
            $this->formPersistenceManager->save($formPersistenceIdentifier, $form);
        } catch (PersistenceManagerException $e) {
            $response = [
                'status' => 'error',
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
            ];
        }

        $this->view->assign('response', $response);
        // createAction uses the Extbase JsonView::class.
        // That's why we have to set the view variables in this way.
        $this->view->setVariablesToRender([
            'response',
        ]);
    }
160

161
162
163
164
165
166
167
168
169
    /**
     * Initialize the duplicate action.
     * This action uses the Fluid JsonView::class as view.
     *
     * @internal
     */
    public function initializeDuplicateAction()
    {
        $this->defaultViewObjectName = JsonView::class;
170
171
172
173
174
175
176
177
178
179
    }

    /**
     * Duplicates a given formDefinition and redirects to the Form Editor
     *
     * @param string $formName
     * @param string $formPersistenceIdentifier persistence identifier of the form to duplicate
     * @param string $savePath
     * @internal
     */
180
    public function duplicateAction(string $formName, string $formPersistenceIdentifier, string $savePath)
181
    {
182
        $formToDuplicate = $this->formPersistenceManager->load($formPersistenceIdentifier);
183
184
185
186
        $formToDuplicate['label'] = $formName;
        $formToDuplicate['identifier'] = $this->formPersistenceManager->getUniqueIdentifier($this->convertFormNameToIdentifier($formName));

        $formPersistenceIdentifier = $this->formPersistenceManager->getUniquePersistenceIdentifier($formToDuplicate['identifier'], $savePath);
Benni Mack's avatar
Benni Mack committed
187

188
189
190
191
192
193
194
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/form']['beforeFormDuplicate'] ?? [] as $className) {
            $hookObj = GeneralUtility::makeInstance($className);
            if (method_exists($hookObj, 'beforeFormDuplicate')) {
                $formToDuplicate = $hookObj->beforeFormDuplicate(
                    $formPersistenceIdentifier,
                    $formToDuplicate
                );
195
196
            }
        }
Benni Mack's avatar
Benni Mack committed
197

198
199
        $response = [
            'status' => 'success',
200
            'url' => $this->uriBuilder->uriFor('index', ['formPersistenceIdentifier' => $formPersistenceIdentifier], 'FormEditor')
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        ];

        try {
            $this->formPersistenceManager->save($formPersistenceIdentifier, $formToDuplicate);
        } catch (PersistenceManagerException $e) {
            $response = [
                'status' => 'error',
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
            ];
        }

        $this->view->assign('response', $response);
        // createAction uses the Extbase JsonView::class.
        // That's why we have to set the view variables in this way.
        $this->view->setVariablesToRender([
            'response',
        ]);
    }
220

221
222
223
224
225
226
227
228
229
    /**
     * Initialize the references action.
     * This action uses the Fluid JsonView::class as view.
     *
     * @internal
     */
    public function initializeReferencesAction()
    {
        $this->defaultViewObjectName = JsonView::class;
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    }

    /**
     * Show references to this persistence identifier
     *
     * @param string $formPersistenceIdentifier persistence identifier of the form to duplicate
     * @internal
     */
    public function referencesAction(string $formPersistenceIdentifier)
    {
        $this->view->assign('references', $this->getProcessedReferencesRows($formPersistenceIdentifier));
        $this->view->assign('formPersistenceIdentifier', $formPersistenceIdentifier);
        // referencesAction uses the extbase JsonView::class.
        // That's why we have to set the view variables in this way.
        $this->view->setVariablesToRender([
            'references',
            'formPersistenceIdentifier'
        ]);
    }

    /**
     * Delete a formDefinition identified by the $formPersistenceIdentifier.
     *
     * @param string $formPersistenceIdentifier persistence identifier to delete
     * @internal
     */
    public function deleteAction(string $formPersistenceIdentifier)
    {
258
        if (empty($this->databaseService->getReferencesByPersistenceIdentifier($formPersistenceIdentifier))) {
259
260
261
262
263
264
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/form']['beforeFormDelete'] ?? [] as $className) {
                $hookObj = GeneralUtility::makeInstance($className);
                if (method_exists($hookObj, 'beforeFormDelete')) {
                    $hookObj->beforeFormDelete(
                        $formPersistenceIdentifier
                    );
265
266
                }
            }
Benni Mack's avatar
Benni Mack committed
267

268
269
            $this->formPersistenceManager->delete($formPersistenceIdentifier);
        } else {
270
271
            $controllerConfiguration = TranslationService::getInstance()->translateValuesRecursive(
                $this->formSettings['formManager']['controller'],
272
                $this->formSettings['formManager']['translationFiles'] ?? []
273
274
            );

275
            $this->addFlashMessage(
276
277
                sprintf($controllerConfiguration['deleteAction']['errorMessage'], $formPersistenceIdentifier),
                $controllerConfiguration['deleteAction']['errorTitle'],
278
279
280
281
282
283
284
285
286
287
288
289
                AbstractMessage::ERROR,
                true
            );
        }
        $this->redirect('index');
    }

    /**
     * Return a list of all accessible file mountpoints.
     *
     * Only registered mountpoints from
     * TYPO3.CMS.Form.persistenceManager.allowedFileMounts
290
     * are listed. This list will be reduced by the configured
291
292
293
294
295
296
297
298
299
300
301
302
303
     * mountpoints for the current backend user.
     *
     * @return array
     */
    protected function getAccessibleFormStorageFolders(): array
    {
        $preparedAccessibleFormStorageFolders = [];
        foreach ($this->formPersistenceManager->getAccessibleFormStorageFolders() as $identifier => $folder) {
            $preparedAccessibleFormStorageFolders[] = [
                'label' => $folder->getName(),
                'value' => $identifier
            ];
        }
304
305
306
307
308
309
310
311
312
313

        if ($this->formSettings['persistenceManager']['allowSaveToExtensionPaths']) {
            foreach ($this->formPersistenceManager->getAccessibleExtensionFolders() as $relativePath => $fullPath) {
                $preparedAccessibleFormStorageFolders[] = [
                    'label' => $relativePath,
                    'value' => $relativePath
                ];
            }
        }

314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        return $preparedAccessibleFormStorageFolders;
    }

    /**
     * Returns the json encoded data which is used by the form editor
     * JavaScript app.
     *
     * @return string
     */
    protected function getFormManagerAppInitialData(): string
    {
        $formManagerAppInitialData = [
            'selectablePrototypesConfiguration' => $this->formSettings['formManager']['selectablePrototypesConfiguration'],
            'accessibleFormStorageFolders' => $this->getAccessibleFormStorageFolders(),
            'endpoints' => [
329
330
331
332
                'create' => $this->uriBuilder->uriFor('create'),
                'duplicate' => $this->uriBuilder->uriFor('duplicate'),
                'delete' => $this->uriBuilder->uriFor('delete'),
                'references' => $this->uriBuilder->uriFor('references')
333
334
335
336
337
338
            ],
        ];

        $formManagerAppInitialData = ArrayUtility::reIndexNumericArrayKeysRecursive($formManagerAppInitialData);
        $formManagerAppInitialData = TranslationService::getInstance()->translateValuesRecursive(
            $formManagerAppInitialData,
339
            $this->formSettings['formManager']['translationFiles'] ?? []
340
341
342
343
344
345
346
347
348
349
350
        );
        return json_encode($formManagerAppInitialData);
    }

    /**
     * List all formDefinitions which can be loaded through t form persistence
     * manager. Enrich this data by a reference counter.
     * @return array
     */
    protected function getAvailableFormDefinitions(): array
    {
351
352
353
        $allReferencesForFileUid = $this->databaseService->getAllReferencesForFileUid();
        $allReferencesForPersistenceIdentifier = $this->databaseService->getAllReferencesForPersistenceIdentifier();

354
355
        $availableFormDefinitions = [];
        foreach ($this->formPersistenceManager->listForms() as $formDefinition) {
356
357
358
359
360
361
362
363
364
365
            $referenceCount  = 0;
            if (
                isset($formDefinition['fileUid'])
                && array_key_exists($formDefinition['fileUid'], $allReferencesForFileUid)
            ) {
                $referenceCount = $allReferencesForFileUid[$formDefinition['fileUid']];
            } elseif (array_key_exists($formDefinition['persistenceIdentifier'], $allReferencesForPersistenceIdentifier)) {
                $referenceCount = $allReferencesForPersistenceIdentifier[$formDefinition['persistenceIdentifier']];
            }

366
367
368
            $formDefinition['referenceCount'] = $referenceCount;
            $availableFormDefinitions[] = $formDefinition;
        }
369

370
371
372
373
        return $availableFormDefinitions;
    }

    /**
374
     * Returns an array with information about the references for a
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
     * formDefinition identified by $persistenceIdentifier.
     *
     * @param string $persistenceIdentifier
     * @return array
     * @throws \InvalidArgumentException
     */
    protected function getProcessedReferencesRows(string $persistenceIdentifier): array
    {
        if (empty($persistenceIdentifier)) {
            throw new \InvalidArgumentException('$persistenceIdentifier must not be empty.', 1477071939);
        }

        $references = [];
        $iconFactory = GeneralUtility::makeInstance(IconFactory::class);

390
        $referenceRows = $this->databaseService->getReferencesByPersistenceIdentifier($persistenceIdentifier);
391
        foreach ($referenceRows as &$referenceRow) {
392
            $record = $this->getRecord($referenceRow['tablename'], $referenceRow['recuid']);
393
394
395
            if (!$record) {
                continue;
            }
396
            $pageRecord = $this->getRecord('pages', $record['pid']);
397
398
399
400
401
402
            $urlParameters = [
                'edit' => [
                    $referenceRow['tablename'] => [
                        $referenceRow['recuid'] => 'edit'
                    ]
                ],
403
                'returnUrl' => $this->getModuleUrl('web_FormFormbuilder')
404
405
406
            ];

            $references[] = [
407
408
                'recordPageTitle' => is_array($pageRecord) ? $this->getRecordTitle('pages', $pageRecord) : '',
                'recordTitle' => $this->getRecordTitle($referenceRow['tablename'], $record, true),
409
410
                'recordIcon' => $iconFactory->getIconForRecord($referenceRow['tablename'], $record, Icon::SIZE_SMALL)->render(),
                'recordUid' => $referenceRow['recuid'],
411
                'recordEditUrl' => $this->getModuleUrl('record_edit', $urlParameters),
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
            ];
        }
        return $references;
    }

    /**
     * Check if a given $templatePath for a given $prototypeName is valid
     * and accessible.
     *
     * Valid template paths has to be configured within
     * TYPO3.CMS.Form.formManager.selectablePrototypesConfiguration.[('identifier':  $prototypeName)].newFormTemplates.[('templatePath': $templatePath)]
     *
     * @param string $prototypeName
     * @param string $templatePath
     * @return bool
     */
    protected function isValidTemplatePath(string $prototypeName, string $templatePath): bool
    {
        $isValid = false;
        foreach ($this->formSettings['formManager']['selectablePrototypesConfiguration'] as $prototypesConfiguration) {
            if ($prototypesConfiguration['identifier'] !== $prototypeName) {
                continue;
            }
            foreach ($prototypesConfiguration['newFormTemplates'] as $templatesConfiguration) {
                if ($templatesConfiguration['templatePath'] !== $templatePath) {
                    continue;
                }
                $isValid = true;
                break;
            }
        }

        $templatePath = GeneralUtility::getFileAbsFileName($templatePath);
        if (!is_file($templatePath)) {
            $isValid = false;
        }

        return $isValid;
    }

    /**
Björn Jacob's avatar
Björn Jacob committed
453
     * Register document header buttons
454
455
456
457
458
459
460
461
     *
     * @throws \InvalidArgumentException
     */
    protected function registerDocheaderButtons()
    {
        /** @var ButtonBar $buttonBar */
        $buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();

Björn Jacob's avatar
Björn Jacob committed
462
463
464
465
466
467
468
469
470
471
472
        // Create new
        $addFormButton = $buttonBar->makeLinkButton()
            ->setDataAttributes(['identifier' => 'newForm'])
            ->setHref('#')
            ->setTitle($this->getLanguageService()->sL('LLL:EXT:form/Resources/Private/Language/Database.xlf:formManager.create_new_form'))
            ->setIcon($this->view->getModuleTemplate()->getIconFactory()->getIcon('actions-add', Icon::SIZE_SMALL));
        $buttonBar->addButton($addFormButton, ButtonBar::BUTTON_POSITION_LEFT);

        // Reload
        $reloadButton = $buttonBar->makeLinkButton()
            ->setHref(GeneralUtility::getIndpEnv('REQUEST_URI'))
473
            ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.reload'))
Björn Jacob's avatar
Björn Jacob committed
474
475
476
477
            ->setIcon($this->view->getModuleTemplate()->getIconFactory()->getIcon('actions-refresh', Icon::SIZE_SMALL));
        $buttonBar->addButton($reloadButton, ButtonBar::BUTTON_POSITION_RIGHT);

        // Shortcut
478
        $shortcutButton = $buttonBar->makeShortcutButton()
479
            ->setRouteIdentifier('web_FormFormbuilder')
480
            ->setDisplayName($this->getLanguageService()->sL('LLL:EXT:form/Resources/Private/Language/Database.xlf:module.shortcut_name'));
481
        $buttonBar->addButton($shortcutButton, ButtonBar::BUTTON_POSITION_RIGHT);
482
483
484
485
486
487
488
489
490
491
    }

    /**
     * Returns a form identifier which is the lower cased form name.
     *
     * @param string $formName
     * @return string
     */
    protected function convertFormNameToIdentifier(string $formName): string
    {
492
493
494
        $csConverter = GeneralUtility::makeInstance(CharsetConverter::class);

        $formIdentifier = $csConverter->specCharsToASCII('utf-8', $formName);
495
        $formIdentifier = (string)preg_replace('/[^a-zA-Z0-9-_]/', '', $formIdentifier);
496
497
498
499
500
        $formIdentifier = lcfirst($formIdentifier);
        return $formIdentifier;
    }

    /**
501
     * Wrapper used for unit testing.
502
     *
503
504
     * @param string $table
     * @param int $uid
505
     * @return array|null
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
     */
    protected function getRecord(string $table, int $uid)
    {
        return BackendUtility::getRecord($table, $uid);
    }

    /**
     * Wrapper used for unit testing.
     *
     * @param string $table
     * @param array $row
     * @param bool $prep
     * @return string
     */
    protected function getRecordTitle(string $table, array $row, bool $prep = false): string
    {
        return BackendUtility::getRecordTitle($table, $row, $prep);
    }

    /**
     * Wrapper used for unit testing.
     *
     * @param string $moduleName
     * @param array $urlParameters
530
531
     * @return string
     */
532
    protected function getModuleUrl(string $moduleName, array $urlParameters = []): string
533
    {
534
        /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
535
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
536
        return (string)$uriBuilder->buildUriFromRoute($moduleName, $urlParameters);
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
    }

    /**
     * Returns the current BE user.
     *
     * @return BackendUserAuthentication
     */
    protected function getBackendUser(): BackendUserAuthentication
    {
        return $GLOBALS['BE_USER'];
    }

    /**
     * Returns the Language Service
     *
     * @return LanguageService
     */
    protected function getLanguageService(): LanguageService
    {
        return $GLOBALS['LANG'];
    }

    /**
     * Returns the page renderer
     *
     * @return PageRenderer
     */
    protected function getPageRenderer(): PageRenderer
    {
        return GeneralUtility::makeInstance(PageRenderer::class);
    }
}