Issues (3936)

Classes/Controller/ApiController.php (14 issues)

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\Domain\Workflow\DocumentWorkflow;
19
use EWW\Dpf\Services\ImportExternalMetadata\BibTexFileImporter;
20
use EWW\Dpf\Services\ImportExternalMetadata\CrossRefImporter;
21
use EWW\Dpf\Services\ImportExternalMetadata\DataCiteImporter;
22
use EWW\Dpf\Services\ImportExternalMetadata\FileImporter;
23
use EWW\Dpf\Services\ImportExternalMetadata\K10plusImporter;
24
use EWW\Dpf\Services\ImportExternalMetadata\PubMedImporter;
25
use EWW\Dpf\Services\ImportExternalMetadata\RisWosFileImporter;
26
use TYPO3\CMS\Core\Utility\GeneralUtility;
27
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
28
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
29
use TYPO3\CMS\Core\Log\LogManager;
30
use EWW\Dpf\Services\ProcessNumber\ProcessNumberGenerator;
31
32
/**
33
 * DocumentController
34
 */
35
class ApiController extends ActionController
36
{
37
    /**
38
     * @var \TYPO3\CMS\Extbase\Mvc\View\JsonView
39
     */
40
    protected $view;
41
42
    /**
43
     * @var string
44
     */
45
    protected $defaultViewObjectName = \TYPO3\CMS\Extbase\Mvc\View\JsonView::class;
46
47
48
    /**
49
     * security
50
     *
51
     * @var \EWW\Dpf\Security\Security
52
     * @TYPO3\CMS\Extbase\Annotation\Inject
53
     */
54
    protected $security = null;
55
56
    /**
57
     * documentRepository
58
     *
59
     * @var \EWW\Dpf\Domain\Repository\DocumentRepository
60
     * @TYPO3\CMS\Extbase\Annotation\Inject
61
     */
62
    protected $documentRepository = null;
63
64
    /**
65
     * frontendUserRepository
66
     *
67
     * @var \EWW\Dpf\Domain\Repository\FrontendUserRepository
68
     * @TYPO3\CMS\Extbase\Annotation\Inject
69
     */
70
    protected $frontendUserRepository = null;
71
72
    /**
73
     * documentManager
74
     *
75
     * @var \EWW\Dpf\Services\Document\DocumentManager
76
     * @TYPO3\CMS\Extbase\Annotation\Inject
77
     */
78
    protected $documentManager = null;
79
80
    /**
81
     * clientRepository
82
     *
83
     * @var \EWW\Dpf\Domain\Repository\ClientRepository
84
     * @TYPO3\CMS\Extbase\Annotation\Inject
85
     */
86
    protected $clientRepository;
87
88
    /**
89
     * persistence manager
90
     *
91
     * @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
92
     * @TYPO3\CMS\Extbase\Annotation\Inject
93
     */
94
    protected $persistenceManager;
95
96
    /**
97
     * signalSlotDispatcher
98
     *
99
     * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
100
     * @TYPO3\CMS\Extbase\Annotation\Inject
101
     */
102
    protected $signalSlotDispatcher = null;
103
104
    /**
105
     * logger
106
     *
107
     * @var \TYPO3\CMS\Core\Log\Logger
108
     */
109
    protected $logger = null;
110
111
    protected $frontendUser = null;
112
113
    protected $validActions = [
114
        'show', 'create', 'suggestion', 'importDoiWithoutSaving',
115
        'importPubmedWithoutSaving', 'importIsbnWithoutSaving',
116
        'importBibtexWithoutSaving', 'importRisWithoutSaving', 'addFisId'
117
    ];
118
119
    public function __construct()
120
    {
121
        /** @var $logger \TYPO3\CMS\Core\Log\Logger */
122
        $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
123
    }
124
125
    public function checkToken($token) {
126
        // check if token exists
127
128
        $frontendUser = $this->frontendUserRepository->findOneByApiToken($token);
0 ignored issues
show
The method findOneByApiToken() does not exist on EWW\Dpf\Domain\Repository\FrontendUserRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

128
        /** @scrutinizer ignore-call */ 
129
        $frontendUser = $this->frontendUserRepository->findOneByApiToken($token);
Loading history...
129
130
        if ($frontendUser) {
131
            $this->frontendUser = $frontendUser;
132
            return true;
133
        } else {
134
            return false;
135
        }
136
    }
137
138
    /**
139
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
140
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
141
     */
142
    public function initializeShowAction()
143
    {
144
        $this->checkMandatoryParameters(['document', 'token']);
145
    }
146
147
    /**
148
     * @param string $document
149
     * @param string $token
150
     */
151
    public function showAction($document, $token) {
152
        if ($this->checkToken($token)) {
153
            /** @var Document $doc */
154
            $doc = $this->documentManager->read($document);
155
156
            if ($doc) {
0 ignored issues
show
$doc is of type EWW\Dpf\Domain\Model\Document, thus it always evaluated to true.
Loading history...
157
                $this->security->getUser()->getUid();
158
159
                /** @var $client \EWW\Dpf\Domain\Model\Client */
160
                $client = $this->clientRepository->findAllByPid($this->frontendUser->getPid())->current();
0 ignored issues
show
The method getPid() does not exist on TYPO3\CMS\Extbase\Persistence\QueryResultInterface. ( Ignorable by Annotation )

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

160
                $client = $this->clientRepository->findAllByPid($this->frontendUser->/** @scrutinizer ignore-call */ getPid())->current();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
The method getPid() does not exist on null. ( Ignorable by Annotation )

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

160
                $client = $this->clientRepository->findAllByPid($this->frontendUser->/** @scrutinizer ignore-call */ getPid())->current();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
161
162
                $mapper = new \EWW\Dpf\Services\Api\DocumentToJsonMapper();
163
                $mapper->setMapping($client->getFisMapping());
164
                $jsonData = $mapper->getJson($doc);
165
                return $jsonData;
166
            }
167
168
            return '{"error": "No data found"}';
169
        }
170
        return '{"error": "Token failed"}';
171
    }
172
173
174
    /**
175
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
176
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
177
     */
178
    public function initializeCreateAction()
179
    {
180
        $this->checkMandatoryParameters(['json', 'token']);
181
    }
182
183
    /**
184
     * @param string $json
185
     * @param string $token
186
     */
187
    public function createAction($json, $token) {
188
189
        if ($this->checkToken($token)) {
190
191
            if (is_null(json_decode($json))) {
192
                return '{"error": "Invalid data in parameter json"}';
193
            }
194
195
            $mapper = $this->objectManager->get(\EWW\Dpf\Services\Api\JsonToDocumentMapper::class);
196
197
            /** @var Document $document */
198
            $document = $mapper->getDocument($json);
199
200
            if ($this->tokenUserId) {
0 ignored issues
show
Bug Best Practice introduced by
The property tokenUserId does not exist on EWW\Dpf\Controller\ApiController. Did you maybe forget to declare it?
Loading history...
201
                $document->setCreator($this->security->getUser()->getUid());
202
            }
203
204
            // xml data fields are limited to 64 KB
205
            if (strlen($document->getXmlData()) >= Document::XML_DATA_SIZE_LIMIT) {
206
                return '{"error": "Maximum document size exceeded"}';
207
            }
208
209
            $processNumber = $document->getProcessNumber();
210
            if (empty($processNumber)) {
211
                $processNumberGenerator = $this->objectManager->get(ProcessNumberGenerator::class);
212
                $processNumber = $processNumberGenerator->getProcessNumber();
213
                $document->setProcessNumber($processNumber);
214
            }
215
216
            $this->documentRepository->add($document);
217
            $this->persistenceManager->persistAll();
218
219
            // index the document
220
            $this->signalSlotDispatcher->dispatch(
221
                AbstractController::class, 'indexDocument', [$document]
222
            );
223
224
            return '{"success": "Document created", "id": "' . $document->getProcessNumber() . '"}';
225
        }
226
        return '{"error": "Token failed"}';
227
228
    }
229
230
    /**
231
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
232
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
233
     */
234
    public function initializeAddFisIdAction()
235
    {
236
        $this->checkMandatoryParameters(['document', 'id', 'token']);
237
    }
238
239
    /**
240
     * @param string $document
241
     * @param string $id
242
     * @param string $token
243
     * @throws \Exception
244
     */
245
    public function addFisIdAction($document, $id, $token) {
246
        if ($this->checkToken($token)) {
247
            /** @var Document $doc */
248
            $doc = $this->documentManager->read($document);
249
250
            $internalFormat = new \EWW\Dpf\Helper\InternalFormat($doc->getXmlData());
251
            $internalFormat->setFisId($id);
252
            $doc->setXmlData($internalFormat->getXml());
253
254
            $processNumber = $doc->getProcessNumber();
255
            if (empty($processNumber)) {
256
                $processNumberGenerator = $this->objectManager->get(ProcessNumberGenerator::class);
257
                $processNumber = $processNumberGenerator->getProcessNumber();
258
                $doc->setProcessNumber($processNumber);
259
            }
260
261
            if ($this->documentManager->update($doc, null,true)) {
262
                return '{"success": "Document '.$document.' added '.$id.'"}';
263
            } else {
264
                return '{"failed": Could not update the Document"}';
265
            }
266
        }
267
        return '{"error": "Token failed"}';
268
269
    }
270
271
    /**
272
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
273
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
274
     */
275
    public function initializeSuggestionAction()
276
    {
277
        $this->checkMandatoryParameters(['document', 'json', 'comment', 'token']);
278
        if ($this->request->hasArgument('restore')) {
279
            $restore = $this->request->getArgument('restore');
280
            $this->request->setArgument('restore', ($restore === 'true' || $restore == 1));
281
        }
282
    }
283
284
    /**
285
     * @param string $document
286
     * @param string $json
287
     * @param string $comment
288
     * @param string $token
289
     * @param bool $restore
290
     * @return string
291
     */
292
    public function suggestionAction($document, $json, $comment, $token, $restore = false) {
293
294
        if ($this->checkToken($token)) {
295
296
            if ($restore) {
297
                if (!empty($json) && is_null(json_decode($json))) {
298
                    return '{"error": "Invalid data in parameter json."}';
299
                }
300
            } else {
301
                if (empty($json) || json_decode($json,true) === []) {
302
                    return '{"error": "Parameter json can not be empty."}';
303
                }
304
                if (is_null(json_decode($json))) {
305
                    return '{"error": "Invalid data in parameter json."}';
306
                }
307
            }
308
309
            /** @var Document $doc */
310
            $doc = $this->documentManager->read($document);
311
312
            if (!$doc) {
0 ignored issues
show
$doc is of type EWW\Dpf\Domain\Model\Document, thus it always evaluated to true.
Loading history...
313
                return '{"failed": "Document does not exist: '.$document.'"}';
314
            }
315
316
            if ($doc->getState() === DocumentWorkflow::STATE_NEW_NONE) {
317
                return '{"failed": "Access denied. The document is private."}';
318
            }
319
320
            $linkedDocument = $this->documentRepository->findOneByLinkedUid($doc->getUid());
0 ignored issues
show
The method findOneByLinkedUid() does not exist on EWW\Dpf\Domain\Repository\DocumentRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

320
            /** @scrutinizer ignore-call */ 
321
            $linkedDocument = $this->documentRepository->findOneByLinkedUid($doc->getUid());
Loading history...
321
            if (!$linkedDocument && $doc->getObjectIdentifier()) {
322
                $linkedDocument = $this->documentRepository->findOneByLinkedUid($doc->getObjectIdentifier());
323
            }
324
325
            if ($linkedDocument) {
326
                return '{"failed": "There is already a suggestion for the document: '.$linkedDocument->getUid().'"}';
327
            }
328
329
            $mapper = $this->objectManager->get(\EWW\Dpf\Services\Api\JsonToDocumentMapper::class);
330
331
            /** @var Document $editOrigDocument */
332
            $editOrigDocument = $mapper->editDocument($doc, $json);
333
            $editOrigDocument->setCreator($this->frontendUser->getUid());
0 ignored issues
show
The method getUid() does not exist on TYPO3\CMS\Extbase\Persistence\QueryResultInterface. ( Ignorable by Annotation )

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

333
            $editOrigDocument->setCreator($this->frontendUser->/** @scrutinizer ignore-call */ getUid());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
334
            $suggestionDocument = $this->documentManager->addSuggestion($editOrigDocument, $restore, $comment);
335
336
            if ($restore) {
337
                $suggestionDocument->setTransferStatus("RESTORE");
338
            }
339
340
            if ($suggestionDocument) {
341
                return '{"success": "Suggestion created", "id": "' . $suggestionDocument->getDocumentIdentifier() . '"}';
342
            } else {
343
                return '{"failed": "Suggestion not created"}';
344
            }
345
        }
346
        return '{"error": "Token failed"}';
347
    }
348
349
350
    /**
351
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
352
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
353
     */
354
    public function initializeImportDoiWithoutSavingAction()
355
    {
356
        $this->checkMandatoryParameters(['doi', 'token']);
357
    }
358
359
    /**
360
     * @param string $doi
361
     * @param string $token
362
     */
363
    public function importDoiWithoutSavingAction(string $doi, $token) {
364
        if ($this->checkToken($token)) {
365
            $importer = $this->objectManager->get(CrossRefImporter::class);
366
            $importer->deactivateProcessNumberGeneration();
367
368
            $externalMetadata = $importer->findByIdentifier($doi);
369
            if (!$externalMetadata) {
370
                $importer = $this->objectManager->get(DataCiteImporter::class);
371
                $externalMetadata = $importer->findByIdentifier($doi);
372
            }
373
374
            if ($externalMetadata) {
375
                // create document
376
                try {
377
                    /** @var Document $newDocument */
378
                    $newDocument = $importer->import($externalMetadata);
379
                    if ($newDocument) {
0 ignored issues
show
$newDocument is of type EWW\Dpf\Domain\Model\Document, thus it always evaluated to true.
Loading history...
380
                        /** @var $client \EWW\Dpf\Domain\Model\Client */
381
                        $client = $this->clientRepository->findAllByPid($this->frontendUser->getPid())->current();
382
383
                        $mapper = new \EWW\Dpf\Services\Api\DocumentToJsonMapper();
384
                        $mapper->setMapping($client->getFisMapping());
385
                        $jsonData = $mapper->getJson($newDocument);
386
                        return $jsonData;
387
                    } else {
388
                        return '{"failed": "Import failed"}';
389
                    }
390
391
                } catch (\Throwable $throwable) {
392
393
                    $this->logger->log(\TYPO3\CMS\Core\Log\LogLevel::ERROR, $throwable->getMessage());
394
                    return '{"failed": "' . $throwable->getMessage() . '"}';
395
                }
396
397
            } else {
398
                // error
399
                return '{"failed": "Nothing found"}';
400
            }
401
        }
402
        return '{"error": "Token failed"}';
403
    }
404
405
    /**
406
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
407
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
408
     */
409
    public function initializeImportPubmedWithoutSavingAction()
410
    {
411
        $this->checkMandatoryParameters(['pmid', 'token']);
412
    }
413
414
    /**
415
     * @param string $pmid
416
     * @param string $token
417
     * @return string
418
     */
419
    public function importPubmedWithoutSavingAction($pmid, $token) {
420
        if ($this->checkToken($token)) {
421
            $importer = $this->objectManager->get(PubMedImporter::class);
422
            $importer->deactivateProcessNumberGeneration();
423
424
            $externalMetadata = $importer->findByIdentifier($pmid);
425
426
            if ($externalMetadata) {
427
                // create document
428
                try {
429
                    /** @var Document $newDocument */
430
                    $newDocument = $importer->import($externalMetadata);
431
                    if ($newDocument) {
0 ignored issues
show
$newDocument is of type EWW\Dpf\Domain\Model\Document, thus it always evaluated to true.
Loading history...
432
                        /** @var $client \EWW\Dpf\Domain\Model\Client */
433
                        $client = $this->clientRepository->findAllByPid($this->frontendUser->getPid())->current();
434
435
                        $mapper = new \EWW\Dpf\Services\Api\DocumentToJsonMapper();
436
                        $mapper->setMapping($client->getFisMapping());
437
                        $jsonData = $mapper->getJson($newDocument);
438
                        return $jsonData;
439
                    } else {
440
                        return '{"failed": "Import failed"}';
441
                    }
442
443
                } catch (\Throwable $throwable) {
444
445
                    $this->logger->log(\TYPO3\CMS\Core\Log\LogLevel::ERROR, $throwable->getMessage());
446
                    return '{"failed": "' . $throwable->getMessage() . '"}';
447
                }
448
449
            } else {
450
                // error
451
                return '{"failed": "Nothing found"}';
452
            }
453
        }
454
        return '{"error": "Token failed"}';
455
    }
456
457
    /**
458
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
459
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
460
     */
461
    public function initializeImportIsbnWithoutSavingAction()
462
    {
463
        $this->checkMandatoryParameters(['isbn', 'token']);
464
    }
465
466
    /**
467
     * @param string $isbn
468
     * @param string $token
469
     * @return string
470
     */
471
    public function importIsbnWithoutSavingAction($isbn, $token) {
472
        if ($this->checkToken($token)) {
473
            $importer = $this->objectManager->get(K10plusImporter::class);
474
            $importer->deactivateProcessNumberGeneration();
475
476
            $externalMetadata = $importer->findByIdentifier(str_replace('- ', '', $isbn));
477
478
            if ($externalMetadata) {
479
                // create document
480
                try {
481
                    /** @var Document $newDocument */
482
                    $newDocument = $importer->import($externalMetadata);
483
                    if ($newDocument) {
0 ignored issues
show
$newDocument is of type EWW\Dpf\Domain\Model\Document, thus it always evaluated to true.
Loading history...
484
                        /** @var $client \EWW\Dpf\Domain\Model\Client */
485
                        $client = $this->clientRepository->findAllByPid($this->frontendUser->getPid())->current();
486
487
                        $mapper = new \EWW\Dpf\Services\Api\DocumentToJsonMapper();
488
                        $mapper->setMapping($client->getFisMapping());
489
                        $jsonData = $mapper->getJson($newDocument);
490
                        return $jsonData;
491
                    } else {
492
                        return '{"failed": "Import failed"}';
493
                    }
494
495
                } catch (\Throwable $throwable) {
496
497
                    $this->logger->log(\TYPO3\CMS\Core\Log\LogLevel::ERROR, $throwable->getMessage());
498
                    return '{"failed": "' . $throwable->getMessage() . '"}';
499
                }
500
501
            } else {
502
                // error
503
                return '{"failed": "Nothing found"}';
504
            }
505
        }
506
        return '{"error": "Token failed"}';
507
    }
508
509
    /**
510
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
511
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
512
     */
513
    public function initializeImportBibtexWithoutSavingAction()
514
    {
515
        $this->checkMandatoryParameters(['bibtex', 'token']);
516
        if ($this->request->hasArgument('force')) {
517
            $force = $this->request->getArgument('force');
518
            $this->request->setArgument('force', ($force === 'true' || $force == 1));
519
        }
520
    }
521
522
    /**
523
     * @param string $bibtex content of a bibtex file
524
     * @param string $token
525
     * @param bool $force
526
     * @return string
527
     */
528
    public function importBibtexWithoutSavingAction($bibtex, $token, $force = false) {
529
530
        if ($this->checkToken($token)) {
531
            $importer = $this->objectManager->get(BibTexFileImporter::class);
532
            $importer->deactivateProcessNumberGeneration();
533
534
            try {
535
                $externalMetadata = $importer->loadFile($bibtex, $this->settings['bibTexMandatoryFields'], true);
536
                $mandatoryErrors = $importer->getMandatoryErrors();
537
            } catch (\Throwable $throwable) {
538
                return '{"failed": "' . $throwable->getMessage() . '"}';
539
            }
540
541
            if ($externalMetadata && (!$mandatoryErrors || $force)) {
542
                // create document
543
                try {
544
                    $jsonDataElements = [];
545
                    foreach ($externalMetadata as $externalMetadataItem) {
546
                        /** @var Document $newDocument */
547
                        $newDocument = $importer->import($externalMetadataItem);
548
                        if ($newDocument) {
549
                            /** @var $client \EWW\Dpf\Domain\Model\Client */
550
                            $client = $this->clientRepository->findAllByPid($this->frontendUser->getPid())->current();
551
                            $mapper = new \EWW\Dpf\Services\Api\DocumentToJsonMapper();
552
                            $mapper->setMapping($client->getFisMapping());
553
                            $jsonDataElements[] = $mapper->getJson($newDocument);
554
                        } else {
555
                            return '{"failed": "Import failed"}';
556
                        }
557
                    }
558
                    return "[" . implode(", ", $jsonDataElements) . "]";
559
                } catch (\Throwable $throwable) {
560
                    $this->logger->log(\TYPO3\CMS\Core\Log\LogLevel::ERROR, $throwable->getMessage());
561
                    return '{"failed": "' . $throwable->getMessage() . '"}';
562
                }
563
            } else {
564
                if ($mandatoryErrors) {
565
                    $message = [];
566
                    $message['failed'] = "Missing mandatory fields.";
567
568
                    foreach ($mandatoryErrors as $mandatoryError) {
569
                        $message['mandatoryErrors'][] = [
570
                            'index'=> $mandatoryError['index'],
571
                            'title' => ($mandatoryError['title'] ? ' (' . $mandatoryError['title'] . ')' : ''),
572
                            'fields' => array_values($mandatoryError['fields'])
573
                        ];
574
                    }
575
576
                    return json_encode($message);
577
578
                } else {
579
                    return '{"failed": "Invalid BibTex-Data"}';
580
                }
581
            }
582
        } else {
583
            return '{"error": "Token failed"}';
584
        }
585
586
        return '{"error": "Unexpected error"}';
0 ignored issues
show
return '{"error": "Unexpected error"}' is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
587
    }
588
589
    /**
590
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
591
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
592
     */
593
    public function initializeImportRisWithoutSavingAction()
594
    {
595
        $this->checkMandatoryParameters(['ris', 'token']);
596
        if ($this->request->hasArgument('force')) {
597
            $force = $this->request->getArgument('force');
598
            $this->request->setArgument('force', ($force === 'true' || $force == 1));
599
        }
600
    }
601
602
    /**
603
     * @param string $ris
604
     * @param string $token
605
     * @param bool $force
606
     * @return string
607
     */
608
    public function importRisWithoutSavingAction($ris, $token, $force = false) {
609
610
        if ($this->checkToken($token)) {
611
            /** @var FileImporter $fileImporter */
612
            $importer = $this->objectManager->get(RisWosFileImporter::class);
613
            $importer->deactivateProcessNumberGeneration();
614
615
            try {
616
                $externalMetadata = $importer->loadFile($ris, $this->settings['riswosMandatoryFields'], true);
617
                $mandatoryErrors = $importer->getMandatoryErrors();
618
            } catch (\Throwable $throwable) {
619
                return '{"failed": "' . $throwable->getMessage() . '"}';
620
            }
621
622
            if ($externalMetadata && (!$mandatoryErrors || $force)) {
623
                // create document
624
                try {
625
                    $jsonDataElements = [];
626
                    foreach ($externalMetadata as $externalMetadataItem) {
627
                        /** @var Document $newDocument */
628
                        $newDocument = $importer->import($externalMetadataItem);
629
                        if ($newDocument) {
630
                            /** @var $client \EWW\Dpf\Domain\Model\Client */
631
                            $client = $this->clientRepository->findAllByPid($this->frontendUser->getPid())->current();
632
633
                            $mapper = new \EWW\Dpf\Services\Api\DocumentToJsonMapper();
634
                            $mapper->setMapping($client->getFisMapping());
635
                            $jsonDataElements[] = $mapper->getJson($newDocument);
636
                        } else {
637
                            return '{"failed": "Import failed"}';
638
                        }
639
                    }
640
                    return "[" . implode(", ", $jsonDataElements) . "]";
641
642
                } catch (\Throwable $throwable) {
643
644
                    $this->logger->log(\TYPO3\CMS\Core\Log\LogLevel::ERROR, $throwable->getMessage());
645
                    return '{"failed": "' . $throwable->getMessage() . '"}';
646
                }
647
648
            } else {
649
                if ($mandatoryErrors) {
650
                    $message = [];
651
                    $message['failed'] = "Missing mandatory fields";
652
653
                    foreach ($mandatoryErrors as $mandatoryError) {
654
                        $message['mandatoryErrors'][] = [
655
                            'index'=> $mandatoryError['index'],
656
                            'title' => ($mandatoryError['title'] ? ' (' . $mandatoryError['title'] . ')' : ''),
657
                            'fields' => array_values($mandatoryError['fields'])
658
                        ];
659
                    }
660
661
                    return json_encode($message);
662
663
                } else {
664
                    return '{"failed": "Invalid RIS-Data"}';
665
                }
666
            }
667
        } else {
668
            return '{"error": "Token failed"}';
669
        }
670
        return '{"error": "Unexpected error"}';
0 ignored issues
show
return '{"error": "Unexpected error"}' is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
671
    }
672
673
674
    /**
675
     * @param $parameterNames array
676
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
677
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
678
     */
679
    protected function checkMandatoryParameters($parameterNames)
680
    {
681
        $missingArguments = [];
682
        foreach ($parameterNames as $parameterName) {
683
            if (!$this->request->hasArgument($parameterName)) {
684
                $missingArguments[] =  $parameterName;
685
            }
686
        }
687
688
        if ($missingArguments) {
689
            $this->throwStatus(
690
                400,
691
                null,
692
                '{"error": "Missing parameters: '.implode(", ", $missingArguments).'"}'
693
            );
694
        }
695
696
    }
697
698
    /**
699
     * Resolves and checks the current action method name
700
     *
701
     * @return string Method name of the current action
702
     */
703
    protected function resolveActionMethodName()
704
    {
705
        if ($this->request->hasArgument('action')) {
706
            $actionName = $this->request->getArgument('action');
707
        }
708
709
        if (empty($actionName)) {
710
            $this->throwStatus(
711
                400,
712
                null,
713
                '{"error": "No action has been specified"}'
714
            );
715
716
        }
717
718
        if (!in_array($actionName, $this->validActions)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $actionName does not seem to be defined for all execution paths leading up to this point.
Loading history...
719
            $this->throwStatus(
720
                400,
721
                null,
722
            '{"error": "An invalid action hes been called: '.$actionName.'"}'
723
            );
724
        }
725
726
        return $actionName . 'Action';
727
    }
728
}
729