Passed
Pull Request — master (#176)
by
unknown
07:49
created

DocumentFormBackofficeController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 8
rs 10
1
<?php
2
namespace EWW\Dpf\Controller;
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 EWW\Dpf\Domain\Model\Document;
18
use EWW\Dpf\Helper\DocumentMapper;
19
use EWW\Dpf\Exceptions\AccessDeniedExcepion;
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Exceptions\AccessDeniedExcepion was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
use EWW\Dpf\Security\DocumentVoter;
21
use EWW\Dpf\Security\Security;
22
use EWW\Dpf\Exceptions\DPFExceptionInterface;
23
use EWW\Dpf\Domain\Workflow\DocumentWorkflow;
24
use EWW\Dpf\Services\Email\Notifier;
25
use EWW\Dpf\Services\Transfer\DocumentTransferManager;
26
use EWW\Dpf\Services\Transfer\FedoraRepository;
27
use TYPO3\CMS\Core\Messaging\AbstractMessage;
28
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
29
30
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;
31
32
class DocumentFormBackofficeController extends AbstractDocumentFormController
33
{
34
    /**
35
     * documentTransferManager
36
     *
37
     * @var \EWW\Dpf\Services\Transfer\DocumentTransferManager $documentTransferManager
38
     */
39
    protected $documentTransferManager;
40
41
    /**
42
     * fedoraRepository
43
     *
44
     * @var \EWW\Dpf\Services\Transfer\FedoraRepository $fedoraRepository
45
     */
46
    protected $fedoraRepository;
47
48
    /**
49
     * editingLockService
50
     *
51
     * @var \EWW\Dpf\Services\Document\EditingLockService
52
     * @inject
53
     */
54
    protected $editingLockService = null;
55
56
    /**
57
     * documentManager
58
     *
59
     * @var \EWW\Dpf\Services\Document\DocumentManager
60
     * @inject
61
     */
62
    protected $documentManager = null;
63
64
    /**
65
     * bookmarkRepository
66
     *
67
     * @var \EWW\Dpf\Domain\Repository\BookmarkRepository
68
     * @inject
69
     */
70
    protected $bookmarkRepository = null;
71
72
    /**
73
     * clientConfigurationManager
74
     *
75
     * @var \EWW\Dpf\Configuration\ClientConfigurationManager
76
     * @inject
77
     */
78
    protected $clientConfigurationManager;
79
80
    /**
81
     * DocumentController constructor.
82
     */
83
    public function __construct()
84
    {
85
        parent::__construct();
86
87
        $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
88
        $this->documentTransferManager = $objectManager->get(DocumentTransferManager::class);
89
        $this->fedoraRepository = $objectManager->get(FedoraRepository::class);
90
        $this->documentTransferManager->setRemoteRepository($this->fedoraRepository);
91
    }
92
93
    public function arrayRecursiveDiff($aArray1, $aArray2) {
94
        $aReturn = array();
95
96
        foreach ($aArray1 as $mKey => $mValue) {
97
            if (array_key_exists($mKey, $aArray2)) {
98
                if (is_array($mValue)) {
99
                    $aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
100
                    if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
101
                } else {
102
                    if ($mValue != $aArray2[$mKey]) {
103
                        $aReturn[$mKey] = $mValue;
104
                    }
105
                }
106
            } else {
107
                $aReturn[$mKey] = $mValue;
108
            }
109
        }
110
        return $aReturn;
111
    }
112
113
114
    /**
115
     * action edit
116
     *
117
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
118
     * @param bool $suggestMod
119
     * @param bool activeFileTab
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\activeFileTab was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
120
     * @ignorevalidation $documentForm
121
     * @return void
122
     */
123
    public function editAction(
124
        \EWW\Dpf\Domain\Model\DocumentForm $documentForm, bool $suggestMod = false, $activeFileTab = false
125
    )
126
    {
127
        /** @var \EWW\Dpf\Domain\Model\Document $document */
128
        $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
129
130
        if ($suggestMod) {
131
            $documentVoterAttribute = DocumentVoter::SUGGEST_MODIFICATION;
132
        } else {
133
            $documentVoterAttribute = DocumentVoter::EDIT;
134
        }
135
136
        if (!$this->authorizationChecker->isGranted($documentVoterAttribute, $document)) {
137
138
            if ($document->getCreator() !== $this->security->getUser()->getUid()) {
139
                $message = LocalizationUtility::translate(
140
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_edit.accessDenied',
141
                    'dpf',
142
                    array($document->getTitle())
143
                );
144
            } else {
145
                $message = LocalizationUtility::translate(
146
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_edit.failureBlocked',
147
                    'dpf',
148
                    array($document->getTitle())
149
                );
150
            }
151
152
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
153
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
154
            return FALSE;
0 ignored issues
show
Bug Best Practice introduced by
The expression return FALSE returns the type false which is incompatible with the documented return type void.
Loading history...
155
        }
156
157
        $this->view->assign('document', $document);
158
        $this->view->assign('suggestMod', $suggestMod);
159
160
        $this->editingLockService->lock(
161
            ($document->getObjectIdentifier()? $document->getObjectIdentifier() : $document->getUid()),
162
            $this->security->getUser()->getUid()
163
        );
164
165
        $this->view->assign('activeFileTab', $activeFileTab);
166
        parent::editAction($documentForm);
167
    }
168
169
    /**
170
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
171
     * @param bool $restore
172
     */
173
    public function createSuggestionDocumentAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm, $restore = FALSE)
174
    {
175
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
176
177
        $hasFilesFlag = true;
178
179
        $workingCopy = $this->documentRepository->findByUid($documentForm->getDocumentUid());
180
181
        if ($workingCopy->isTemporary()) {
182
            $workingCopy->setTemporary(false);
183
        }
184
185
        if (empty($workingCopy->getFileData())) {
186
            // no files are linked to the document
187
            $hasFilesFlag = false;
188
        }
189
190
        $newDocument = $this->objectManager->get(Document::class);
191
192
        $this->documentRepository->add($newDocument);
193
        $this->persistenceManager->persistAll();
194
195
        /* @var $document \EWW\Dpf\Domain\Model\Document */
196
        $document = $documentMapper->getDocument($documentForm);
197
198
        /* @var $newDocument \EWW\Dpf\Domain\Model\Document */
199
        $newDocument = $newDocument->copy($document);
200
201
        if ($document->getObjectIdentifier()) {
202
            $newDocument->setLinkedUid($document->getObjectIdentifier());
203
        } else {
204
            $newDocument->setLinkedUid($document->getUid());
205
        }
206
207
        $newDocument->setSuggestion(true);
208
        $newDocument->setComment($document->getComment());
209
210
        if ($restore) {
211
            $newDocument->setTransferStatus("RESTORE");
212
        }
213
214
        if (!$hasFilesFlag) {
215
            // Add or update files
216
            foreach ($documentForm->getNewFiles() as $newFile) {
217
                if ($newFile->getUID()) {
218
                    $this->fileRepository->update($newFile);
219
                } else {
220
                    $newFile->setDocument($newDocument);
221
                    $this->fileRepository->add($newFile);
222
                }
223
224
                $newDocument->addFile($newFile);
225
            }
226
        } else {
227
            // remove files for suggest object
228
            $newDocument->setFile($this->objectManager->get(ObjectStorage::class));
229
        }
230
231
232
        try {
233
            $newDocument->setCreator($this->security->getUser()->getUid());
234
            $this->documentRepository->add($newDocument);
235
236
            $flashMessage = $this->clientConfigurationManager->getSuggestionFlashMessage();
237
            if (!$flashMessage) {
238
                $flashMessage = LocalizationUtility::translate(
239
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:message.suggestion_flashmessage',
240
                    'dpf',
241
                    ''
0 ignored issues
show
Bug introduced by
'' of type string is incompatible with the type array expected by parameter $arguments of TYPO3\CMS\Extbase\Utilit...ionUtility::translate(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

241
                    /** @scrutinizer ignore-type */ ''
Loading history...
242
                );
243
            }
244
            $this->addFlashMessage($flashMessage, '', AbstractMessage::OK, true);
245
246
            $notifier = $this->objectManager->get(Notifier::class);
247
            $notifier->sendAdminNewSuggestionNotification($newDocument);
248
249
        } catch (\Throwable $t) {
250
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
251
            $this->addFlashMessage("Failed", '', $severity,false);
252
        }
253
254
        $this->redirectToDocumentList();
255
    }
256
257
258
    public function updateAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm)
259
    {
260
        if ($this->request->getArgument('documentData')['suggestMod']) {
261
            $restore = $this->request->getArgument('documentData')['suggestRestore'];
262
            $this->forward('createSuggestionDocument', null, null, ['documentForm' => $documentForm, 'restore' => $restore]);
263
        }
264
265
        if ($this->request->hasArgument('saveAndUpdate')) {
266
            $saveMode = 'saveAndUpdate';
267
        } elseif ($this->request->hasArgument('saveWorkingCopy')) {
268
            $saveMode = 'saveWorkingCopy';
269
        } else {
270
            $saveMode = null;
271
        }
272
273
        $this->forward(
274
275
            'updateDocument',
276
            NULL,
277
            NULL,
278
                [
279
                    'documentForm' => $documentForm,
280
                    'saveMode' => $saveMode
281
                ]
282
        );
283
    }
284
285
286
    /**
287
     * @param \EWW\Dpf\Domain\Model\DocumentForm $documentForm
288
     * @param string $saveMode
289
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
290
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
291
     */
292
    public function updateDocumentAction(\EWW\Dpf\Domain\Model\DocumentForm $documentForm, $saveMode = null)
293
    {
294
        try {
295
            /** @var \EWW\Dpf\Domain\Model\Document $document */
296
            $document = $this->documentRepository->findByUid($documentForm->getDocumentUid());
297
298
            if (
299
                !$this->authorizationChecker->isGranted(DocumentVoter::UPDATE, $document) ||
300
                (
301
                    $saveMode == 'saveWorkingCopy' &&
302
                    $this->security->getUser()->getUserRole() !== Security::ROLE_LIBRARIAN
303
                )
304
            ) {
305
                $message = LocalizationUtility::translate(
306
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.accessDenied',
307
                    'dpf',
308
                    array($document->getTitle())
309
                );
310
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
311
                $this->redirect(
312
                    'showDetails', 'Document',
313
                    null, ['document' => $document]
314
                );
315
            }
316
317
            /** @var  \EWW\Dpf\Helper\DocumentMapper $documentMapper */
318
            $documentMapper = $this->objectManager->get(DocumentMapper::class);
319
320
            /** @var \EWW\Dpf\Domain\Model\Document $updateDocument */
321
            $updateDocument = $documentMapper->getDocument($documentForm);
322
323
            $saveWorkingCopy = false;
324
            $workflowTransition = null;
325
326
            // Convert the temporary copy into a local working copy if needed.
327
            if ( $updateDocument->isTemporaryCopy() && $saveMode == 'saveWorkingCopy') {
328
                $saveWorkingCopy = true;
329
                $updateDocument->setTemporary(false);
330
                $workflowTransition = DocumentWorkflow::TRANSITION_IN_PROGRESS;
331
            } elseif ($updateDocument->isTemporaryCopy() && $saveMode == 'saveAndUpdate') {
332
                $workflowTransition = DocumentWorkflow::TRANSITION_REMOTE_UPDATE;
333
            } elseif (
334
                $this->security->getUser()->getUserRole() === Security::ROLE_LIBRARIAN &&
335
                $updateDocument->getState() === DocumentWorkflow::STATE_REGISTERED_NONE
336
            ) {
337
                $workflowTransition = DocumentWorkflow::TRANSITION_IN_PROGRESS;
338
            }
339
340
            if (
341
                $this->documentManager->update(
342
                    $updateDocument, $workflowTransition,
343
                    $documentForm->getDeletedFiles(), $documentForm->getNewFiles()
344
                )
345
            ) {
346
347
                $message = LocalizationUtility::translate(
348
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.success',
349
                    'dpf',
350
                    array($updateDocument->getTitle())
351
                );
352
                $this->addFlashMessage($message, '', AbstractMessage::OK);
353
354
                if ($this->security->getUser()->getUserRole() === Security::ROLE_LIBRARIAN) {
355
                    if ($saveWorkingCopy) {
356
                        if (
357
                            $this->bookmarkRepository->addBookmark(
358
                                $updateDocument,
359
                                $this->security->getUser()->getUid()
360
                            )
361
                        ) {
362
                            $this->addFlashMessage(
363
                                LocalizationUtility::translate(
364
                                    "manager.workspace.bookmarkAdded", "dpf"
365
                                ),
366
                                '',
367
                                AbstractMessage::INFO
368
                            );
369
                        }
370
                    } else {
371
                        switch ($document->getState()) {
372
                            case DocumentWorkflow::STATE_POSTPONED_NONE:
373
                            case DocumentWorkflow::STATE_DISCARDED_NONE:
374
                            case DocumentWorkflow::STATE_NONE_INACTIVE:
375
                            case DocumentWorkflow::STATE_NONE_ACTIVE:
376
                            case DocumentWorkflow::STATE_NONE_DELETED:
377
378
                                if (
379
                                    $this->bookmarkRepository->removeBookmark(
380
                                        $updateDocument,
381
                                        $this->security->getUser()->getUid()
382
                                    )
383
                                ) {
384
                                    $this->addFlashMessage(
385
                                        LocalizationUtility::translate(
386
                                            "manager.workspace.bookmarkRemoved.singular", "dpf"
387
                                        ),
388
                                        '',
389
                                        AbstractMessage::INFO
390
                                    );
391
                                }
392
393
                                $this->redirectToDocumentList();
394
395
                                break;
396
                        }
397
                    }
398
                }
399
400
            } else {
401
                $message = LocalizationUtility::translate(
402
                    'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
403
                    'dpf',
404
                    array($updateDocument->getTitle())
405
                );
406
                $this->addFlashMessage($message, '', AbstractMessage::ERROR);
407
            }
408
409
            if ($workflowTransition && $workflowTransition === DocumentWorkflow::TRANSITION_REMOTE_UPDATE) {
410
                $this->redirectToDocumentList();
411
            } else {
412
                $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
413
            }
414
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
415
            // A redirect always throws this exception, but in this case, however,
416
            // redirection is desired and should not lead to an exception handling
417
        } catch (\Exception $exception) {
418
419
            $severity = AbstractMessage::ERROR;
420
421
            if ($exception instanceof DPFExceptionInterface) {
422
                $key = $exception->messageLanguageKey();
423
            } else {
424
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
425
            }
426
427
            $exceptionMsg[] = LocalizationUtility::translate(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$exceptionMsg was never initialized. Although not strictly required by PHP, it is generally a good practice to add $exceptionMsg = array(); before regardless.
Loading history...
428
                'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_update.failure',
429
                'dpf',
430
                array($updateDocument->getTitle())
431
            );
432
433
            $exceptionMsg[] = LocalizationUtility::translate($key, 'dpf');
434
435
            $this->addFlashMessage(implode(" ", $exceptionMsg), '', $severity, true);
436
            $this->redirect('showDetails', 'Document', null, ['document' => $updateDocument]);
437
        }
438
    }
439
440
    public function createAction(\EWW\Dpf\Domain\Model\DocumentForm $newDocumentForm)
441
    {
442
        /** @var \EWW\Dpf\Helper\DocumentMapper $documentMapper */
443
        $documentMapper = $this->objectManager->get(DocumentMapper::class);
444
445
        /** @var \EWW\Dpf\Domain\Model\Document $document */
446
        $document = $documentMapper->getDocument($newDocumentForm);
447
448
        if (!$this->authorizationChecker->isGranted(DocumentVoter::CREATE, $document)) {
449
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.accessDenied';
450
            $args[] = $document->getTitle();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $args = array(); before regardless.
Loading history...
451
            $message = LocalizationUtility::translate($key, 'dpf', $args);
452
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
453
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
454
            return FALSE;
455
        }
456
457
        try {
458
            parent::createAction($newDocumentForm);
459
460
            $severity = AbstractMessage::OK;
461
            $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:documentForm.create.ok';
462
            $message = LocalizationUtility::translate($key, 'dpf');
463
            $this->addFlashMessage(
464
                $message,
465
                '',
466
                $severity,
467
                true
468
            );
469
470
        } catch (\TYPO3\CMS\Extbase\Mvc\Exception\StopActionException $e) {
471
            // A redirect always throws this exception, but in this case, however,
472
            // redirection is desired and should not lead to an exception handling
473
        } catch (\Exception $exception) {
474
475
            $severity = AbstractMessage::ERROR;
476
477
            if ($exception instanceof DPFExceptionInterface) {
478
                $key = $exception->messageLanguageKey();
479
            } else {
480
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
481
            }
482
483
            $message[] = LocalizationUtility::translate($key, 'dpf');
484
485
            $this->addFlashMessage(
486
                implode(" ", $message),
487
                '',
488
                $severity,
489
                true
490
            );
491
        }
492
493
        $this->redirect('listWorkspace', 'Workspace');
494
    }
495
496
497
    /**
498
     * action cancel edit
499
     *
500
     * @param integer $documentUid
501
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
502
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
503
     *
504
     * @return void
505
     */
506
    public function cancelEditAction($documentUid = 0)
507
    {
508
        if ($documentUid) {
509
            /** @var $document \EWW\Dpf\Domain\Model\Document */
510
            $document = $this->documentRepository->findByUid($documentUid);
511
512
            $this->redirect('showDetails', 'Document', null, ['document' => $document]);
513
        } else {
514
            $this->redirectToDocumentList();
515
        }
516
    }
517
518
    /**
519
     * action cancel new
520
     *
521
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
522
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
523
     *
524
     * @return void
525
     */
526
    public function cancelNewAction()
527
    {
528
        $this->redirect('list');
529
    }
530
531
532
    public function initializeAction()
533
    {
534
        $this->authorizationChecker->denyAccessUnlessLoggedIn();
535
536
        parent::initializeAction();
537
538
    }
539
540
    /**
541
     * Redirect to the current document list.
542
     *
543
     * @param null $message
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $message is correct as it would always require null to be passed?
Loading history...
544
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
545
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
546
     */
547
    protected function redirectToDocumentList($message = null)
548
    {
549
        list($action, $controller, $redirectUri) = $this->session->getStoredAction();
550
551
        if ($redirectUri) {
552
            $this->redirectToUri($redirectUri);
553
        } else {
554
            $this->redirect($action, $controller, null, array('message' => $message));
555
        }
556
    }
557
558
559
}
560