Passed
Pull Request — master (#195)
by
unknown
19:02
created

SearchController::searchAction()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 44
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 28
nc 8
nop 0
dl 0
loc 44
rs 8.8497
c 0
b 0
f 0
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\Services\ElasticSearch\ElasticSearch;
18
use EWW\Dpf\Exceptions\DPFExceptionInterface;
19
use EWW\Dpf\Security\DocumentVoter;
20
use EWW\Dpf\Security\Security;
21
use EWW\Dpf\Domain\Workflow\DocumentWorkflow;
22
use TYPO3\CMS\Core\Messaging\AbstractMessage;
23
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
24
use EWW\Dpf\Session\SearchSessionData;
25
26
/**
27
 * SearchController
28
 */
29
class SearchController extends \EWW\Dpf\Controller\AbstractController
30
{
31
32
    /**
33
     * documentRepository
34
     *
35
     * @var \EWW\Dpf\Domain\Repository\DocumentRepository
36
     * @inject
37
     */
38
    protected $documentRepository = null;
39
40
    /**
41
     * documenTypeRepository
42
     *
43
     * @var \EWW\Dpf\Domain\Repository\DocumentTypeRepository
44
     * @inject
45
     */
46
    protected $documentTypeRepository;
47
48
    /**
49
     * clientRepository
50
     *
51
     * @var \EWW\Dpf\Domain\Repository\ClientRepository
52
     * @inject
53
     */
54
    protected $clientRepository = null;
55
56
57
    /**
58
     * elasticSearch
59
     *
60
     * @var \EWW\Dpf\Services\ElasticSearch\ElasticSearch
61
     * @inject
62
     */
63
    protected $elasticSearch = null;
64
65
66
    /**
67
     * queryBuilder
68
     *
69
     * @var \EWW\Dpf\Services\ElasticSearch\QueryBuilder
70
     * @inject
71
     */
72
    protected $queryBuilder = null;
73
74
75
    /**
76
     * persistence manager
77
     *
78
     * @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
79
     * @inject
80
     */
81
    protected $persistenceManager;
82
83
84
    /**
85
     * bookmarkRepository
86
     *
87
     * @var \EWW\Dpf\Domain\Repository\BookmarkRepository
88
     * @inject
89
     */
90
    protected $bookmarkRepository = null;
91
92
    /**
93
     * fisDataService
94
     *
95
     * @var \EWW\Dpf\Services\FeUser\FisDataService
96
     * @inject
97
     */
98
    protected $fisDataService = null;
99
100
    /**
101
     * metadataGroupRepository
102
     *
103
     * @var \EWW\Dpf\Domain\Repository\MetadataGroupRepository
104
     * @inject
105
     */
106
    protected $metadataGroupRepository;
107
108
    const RESULT_COUNT      = 500;
109
    const NEXT_RESULT_COUNT = 500;
110
111
    /**
112
     * list
113
     *
114
     * @param int $from
115
     * @param int $queryString
116
     *
117
     * @return void
118
     */
119
    protected function list($from = 0, $queryString = '')
120
    {
121
        /** @var SearchSessionData $workspaceSessionData */
122
        $workspaceSessionData = $this->session->getWorkspaceData();
123
        $filters = $workspaceSessionData->getFilters();
124
        $excludeFilters = $workspaceSessionData->getExcludeFilters();
125
126
        if (array_key_exists('bookmarks', $excludeFilters)) {
127
            unset($excludeFilters['bookmarks']);
128
        }
129
130
        $sortField = $workspaceSessionData->getSortField();
131
        $sortOrder = $workspaceSessionData->getSortOrder();
132
133
        if ($this->security->getUser()->getUserRole() == Security::ROLE_LIBRARIAN) {
134
            $query = $this->getSearchQuery($from, [],
135
                $filters, $excludeFilters, $sortField, $sortOrder, $queryString);
136
        } elseif ($this->security->getUser()->getUserRole() == Security::ROLE_RESEARCHER) {
137
            $query = $this->getSearchQuery($from, [],
138
                $filters, $excludeFilters, $sortField, $sortOrder, $queryString);
139
        }
140
141
        try {
142
            $results = $this->elasticSearch->search($query, 'object');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $query does not seem to be defined for all execution paths leading up to this point.
Loading history...
143
        } catch (\Exception $e) {
144
            $workspaceSessionData->clearSort();
145
            $workspaceSessionData->clearFilters();
146
            $this->session->setWorkspaceData($workspaceSessionData);
147
148
            $this->addFlashMessage(
149
                "Error while building the list!", '', AbstractMessage::ERROR
150
            );
151
        }
152
153
        if ($this->request->hasArgument('message')) {
154
            $this->view->assign('message', $this->request->getArgument('message'));
155
        }
156
157
        if ($this->request->hasArgument('errorFiles')) {
158
            $this->view->assign('errorFiles', $this->request->getArgument('errorFiles'));
159
        }
160
161
162
        $this->view->assign('documentCount', $results['hits']['total']['value']);
163
        $this->view->assign('documents', $results['hits']['hits']);
164
        $this->view->assign('pages', range(1, $results['hits']['total']['value']));
165
        $this->view->assign('itemsPerPage', $this->itemsPerPage());
166
        $this->view->assign('aggregations', $results['aggregations']);
167
        $this->view->assign('filters', $filters);
168
        $this->view->assign('isHideDiscarded', array_key_exists('aliasState', $excludeFilters));
169
        $this->view->assign('isBookmarksOnly', array_key_exists('bookmarks', $excludeFilters));
170
        $this->view->assign('bookmarkIdentifiers', []);
171
172
        if ($this->fisDataService->getPersonData($this->security->getUser()->getFisPersId())) {
173
            $this->view->assign('currentFisPersId', $this->security->getUser()->getFisPersId());
174
        }
175
176
        $personGroup = $this->metadataGroupRepository->findPersonGroup();
177
        $this->view->assign('personGroup', $personGroup->getUid());
178
    }
179
180
    /**
181
     * action list
182
     *
183
     * @return void
184
     */
185
    public function searchAction()
186
    {
187
        $args = $this->request->getArguments();
188
189
        /** @var SearchSessionData $workspaceSessionData */
190
        $workspaceSessionData = $this->session->getWorkspaceData();
191
192
        if ($args['query'] && array_key_exists('fulltext', $args['query'])) {
193
            $queryString = $args['query']['fulltext'];
194
            $workspaceSessionData->setSimpleQuery($queryString);
195
        }
196
197
        if ($args['refresh']) {
198
            $workspaceSessionData->clearSort();
199
            $workspaceSessionData->clearFilters();
200
            $workspaceSessionData->setSimpleQuery("");
201
        }
202
        $this->session->setWorkspaceData($workspaceSessionData);
203
204
        $simpleSearch = $workspaceSessionData->getSimpleQuery();
205
206
        $this->session->setStoredAction($this->getCurrentAction(), $this->getCurrentController(),
207
            $this->uriBuilder->getRequest()->getRequestUri()
0 ignored issues
show
introduced by
The method getRequestUri() does not exist on TYPO3\CMS\Extbase\Mvc\Request. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

207
            $this->uriBuilder->getRequest()->/** @scrutinizer ignore-call */ getRequestUri()
Loading history...
208
        );
209
210
        $currentPage = null;
211
        $checkedDocumentIdentifiers = [];
212
        $pagination = $this->getParametersSafely('@widget_0');
213
        if ($pagination) {
214
            $checkedDocumentIdentifiers = [];
215
            $currentPage = $pagination['currentPage'];
216
        } else {
217
            $currentPage = 1;
218
        }
219
220
        $this->list(
221
            (empty($currentPage)? 0 : ($currentPage-1) * $this->itemsPerPage()),
222
            $this->escapeQuery(trim($simpleSearch))
0 ignored issues
show
Bug introduced by
$this->escapeQuery(trim($simpleSearch)) of type string is incompatible with the type integer expected by parameter $queryString of EWW\Dpf\Controller\SearchController::list(). ( Ignorable by Annotation )

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

222
            /** @scrutinizer ignore-type */ $this->escapeQuery(trim($simpleSearch))
Loading history...
223
        );
224
225
        $this->view->assign('simpleSearch', $simpleSearch);
226
        $this->view->assign('currentPage', $currentPage);
227
        $this->view->assign('workspaceListAction', $this->getCurrentAction());
228
        $this->view->assign('checkedDocumentIdentifiers', $checkedDocumentIdentifiers);
229
    }
230
231
232
    /**
233
     * get list view data for the workspace
234
     *
235
     * @param int $from
236
     * @param array $bookmarkIdentifiers
237
     * @param array $filters
238
     * @param array $excludeFilters
239
     * @param string $sortField
240
     * @param string $sortOrder
241
     * @param string $queryString
242
     *
243
     * @return array
244
     */
245
    protected function getSearchQuery(
246
        $from = 0, $bookmarkIdentifiers = [], $filters= [], $excludeFilters = [],
247
        $sortField = null, $sortOrder = null, $queryString = null
248
    )
249
    {
250
        $workspaceFilter = [
251
            'bool' => [
252
                'must' => [
253
                    [
254
                        'bool' => [
255
                            'should' => [
256
                                [
257
                                    'term' => [
258
                                        'creator' => $this->security->getUser()->getUid()
259
                                    ]
260
                                ],
261
                                [
262
                                    'bool' => [
263
                                        'must_not' => [
264
                                            [
265
                                                'term' => [
266
                                                    'state' => DocumentWorkflow::STATE_NEW_NONE
267
                                                ]
268
                                            ]
269
                                        ]
270
                                    ]
271
                                ]
272
                            ]
273
                        ]
274
                    ]
275
                ]
276
            ]
277
        ];
278
279
        return $this->queryBuilder->buildQuery(
280
            $this->itemsPerPage(), $workspaceFilter, $from, $bookmarkIdentifiers, $filters,
281
            $excludeFilters, $sortField, $sortOrder, $queryString
282
        );
283
    }
284
285
286
    /**
287
     * Batch operations action.
288
     * @param array $listData
289
     */
290
    public function batchAction($listData)
291
    {
292
        if (array_key_exists('action', $listData)) {
293
            $this->forward($listData['action'], null, null, ['listData' => $listData]);
294
        }
295
    }
296
297
298
    /**
299
     * Batch operation, bookmark documents.
300
     * @param array $listData
301
     */
302
    public function batchBookmarkAction($listData)
303
    {
304
        $successful = [];
305
        $checkedDocumentIdentifiers = [];
306
307
        if (array_key_exists('documentIdentifiers', $listData) && is_array($listData['documentIdentifiers']) ) {
308
            $checkedDocumentIdentifiers = $listData['documentIdentifiers'];
309
310
            foreach ($listData['documentIdentifiers'] as $documentIdentifier) {
311
312
                if ( $listData['documentAliasState'][$documentIdentifier] != DocumentWorkflow::ALIAS_STATE_NEW) {
313
                    if (
314
                        $this->bookmarkRepository->addBookmark(
315
                            $documentIdentifier,
316
                            $this->security->getUser()->getUid()
317
                        )
318
                    ) {
319
                        $successful[] = $documentIdentifier;
320
                    }
321
                }
322
            }
323
324
            if (sizeof($successful) == 1) {
325
                $locallangKey = 'manager.workspace.batchAction.bookmark.success.singular';
326
            } else {
327
                $locallangKey = 'manager.workspace.batchAction.bookmark.success.plural';
328
            }
329
330
            $message = LocalizationUtility::translate(
331
                $locallangKey,
332
                'dpf',
333
                [sizeof($successful), sizeof($listData['documentIdentifiers'])]
334
            );
335
            $this->addFlashMessage(
336
                $message, '',
337
                (sizeof($successful) > 0 ? AbstractMessage::OK : AbstractMessage::WARNING)
338
            );
339
340
        } else {
341
            $message = LocalizationUtility::translate(
342
                'manager.workspace.batchAction.failure',
343
                'dpf');
344
            $this->addFlashMessage($message, '', AbstractMessage::ERROR);
345
        }
346
347
        list($redirectAction, $redirectController) = $this->session->getStoredAction();
348
        $this->redirect(
349
            $redirectAction, $redirectController, null,
350
            array('message' => $message, 'checkedDocumentIdentifiers' =>  $checkedDocumentIdentifiers));
351
    }
352
353
        /**
354
     * extended search action
355
     */
356
    public function extendedSearchAction()
357
    {
358
        /** @var FrontendUser $feUser */
359
        $feUser = $this->security->getUser();
0 ignored issues
show
Unused Code introduced by
The assignment to $feUser is dead and can be removed.
Loading history...
360
361
        $args = $this->request->getArguments();
362
363
        /** @var SearchSessionData $workspaceSessionData */
364
        $workspaceSessionData = $this->session->getWorkspaceData();
365
366
        if ($args['query'] && array_key_exists('fulltext', $args['query'])) {
367
            $queryString = $args['query']['fulltext'];
368
            $workspaceSessionData->setSimpleQuery($queryString);
369
        }
370
371
        if ($args['refresh']) {
372
            $workspaceSessionData->clearSort();
373
            $workspaceSessionData->clearFilters();
374
            $workspaceSessionData->setSimpleQuery("");
375
        }
376
        $this->session->setWorkspaceData($workspaceSessionData);
377
378
        $simpleSearch = $workspaceSessionData->getSimpleQuery();
379
380
        $documentTypes = $this->documentTypeRepository->findAll();
381
382
        $docTypes = [];
383
        foreach ($documentTypes as $documentType) {
384
            $docTypes[$documentType->getName()] = $documentType->getDisplayName();
385
        }
386
        asort($docTypes, SORT_LOCALE_STRING);
387
        $this->view->assign('documentTypes', $docTypes);
388
389
        $states[DocumentWorkflow::ALIAS_STATE_NEW] = LocalizationUtility::translate(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$states was never initialized. Although not strictly required by PHP, it is generally a good practice to add $states = array(); before regardless.
Loading history...
390
            "manager.documentList.state.".DocumentWorkflow::ALIAS_STATE_NEW, 'dpf'
391
        );
392
        $states[DocumentWorkflow::ALIAS_STATE_REGISTERED] = LocalizationUtility::translate(
393
            "manager.documentList.state.".DocumentWorkflow::ALIAS_STATE_REGISTERED, 'dpf'
394
        );
395
        $states[DocumentWorkflow::ALIAS_STATE_IN_PROGRESS] = LocalizationUtility::translate(
396
            "manager.documentList.state.".DocumentWorkflow::ALIAS_STATE_IN_PROGRESS, 'dpf'
397
        );
398
        $states[DocumentWorkflow::ALIAS_STATE_RELEASED] = LocalizationUtility::translate(
399
            "manager.documentList.state.".DocumentWorkflow::ALIAS_STATE_RELEASED, 'dpf'
400
        );
401
        $states[DocumentWorkflow::ALIAS_STATE_POSTPONED] = LocalizationUtility::translate(
402
            "manager.documentList.state.".DocumentWorkflow::ALIAS_STATE_POSTPONED, 'dpf'
403
        );
404
        $states[DocumentWorkflow::ALIAS_STATE_DISCARDED] = LocalizationUtility::translate(
405
            "manager.documentList.state.".DocumentWorkflow::ALIAS_STATE_DISCARDED, 'dpf'
406
        );
407
408
        $this->view->assign('states', $states);
409
410
        $this->session->setStoredAction($this->getCurrentAction(), $this->getCurrentController(),
411
            $this->uriBuilder->getRequest()->getRequestUri()
412
        );
413
414
        $currentPage = null;
415
        $checkedDocumentIdentifiers = [];
416
        $pagination = $this->getParametersSafely('@widget_0');
417
        if ($pagination) {
418
            $checkedDocumentIdentifiers = [];
419
            $currentPage = $pagination['currentPage'];
420
        } else {
421
            $currentPage = 1;
422
        }
423
424
        $this->list((empty($currentPage)? 0 : ($currentPage-1) * $this->itemsPerPage()), $simpleSearch);
0 ignored issues
show
Bug introduced by
$simpleSearch of type string is incompatible with the type integer expected by parameter $queryString of EWW\Dpf\Controller\SearchController::list(). ( Ignorable by Annotation )

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

424
        $this->list((empty($currentPage)? 0 : ($currentPage-1) * $this->itemsPerPage()), /** @scrutinizer ignore-type */ $simpleSearch);
Loading history...
425
426
        $this->view->assign('simpleSearch', $simpleSearch);
427
        $this->view->assign('currentPage', $currentPage);
428
        $this->view->assign('workspaceListAction', $this->getCurrentAction());
429
        $this->view->assign('checkedDocumentIdentifiers', $checkedDocumentIdentifiers);
430
    }
431
432
    /**
433
     * gets a list of latest documents
434
     */
435
    public function latestAction()
436
    {
437
        try {
438
            $query = $this->searchLatest();
439
440
            // set type local vs object
441
            $type = 'object';
442
443
            $results = $this->getResultList($query, $type);
0 ignored issues
show
Bug introduced by
The method getResultList() does not exist on EWW\Dpf\Controller\SearchController. ( Ignorable by Annotation )

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

443
            /** @scrutinizer ignore-call */ 
444
            $results = $this->getResultList($query, $type);

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...
444
        } catch (\Exception $exception) {
445
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
446
447
            if ($exception instanceof DPFExceptionInterface) {
448
                $key = $exception->messageLanguageKey();
449
            } else {
450
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
451
            }
452
453
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
454
455
            $this->addFlashMessage(
456
                $message,
457
                '',
458
                $severity,
459
                true
460
            );
461
        }
462
463
        if ($extSearch) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extSearch seems to be never defined.
Loading history...
464
            // redirect to extended search view
465
            $this->forward("extendedSearch", null, null, array('results' => $results, 'query' => $args['query']));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $results does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $args seems to be never defined.
Loading history...
466
        } else {
467
            // redirect to list view
468
            $this->forward("list", null, null, array('results' => $results, 'query' => $args['query']));
469
        }
470
    }
471
472
    /**
473
     * action import
474
     *
475
     * @param  string $documentObjectIdentifier
476
     * @param  string $objectState
477
     * @return void
478
     */
479
    public function importAction($documentObjectIdentifier, $objectState)
0 ignored issues
show
Unused Code introduced by
The parameter $objectState is not used and could be removed. ( Ignorable by Annotation )

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

479
    public function importAction($documentObjectIdentifier, /** @scrutinizer ignore-unused */ $objectState)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
480
    {
481
        $documentTransferManager = $this->objectManager->get(DocumentTransferManager::class);
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\DocumentTransferManager 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...
482
        $remoteRepository        = $this->objectManager->get(FedoraRepository::class);
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\FedoraRepository 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...
483
        $documentTransferManager->setRemoteRepository($remoteRepository);
484
485
        $args = array();
486
487
        try {
488
            if ($documentTransferManager->retrieve($documentObjectIdentifier)) {
489
                $key      = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_retrieve.success';
490
                $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::OK;
491
                $document = $this->documentRepository->findOneByObjectIdentifier($documentObjectIdentifier);
0 ignored issues
show
Bug introduced by
The method findOneByObjectIdentifier() 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

491
                /** @scrutinizer ignore-call */ 
492
                $document = $this->documentRepository->findOneByObjectIdentifier($documentObjectIdentifier);
Loading history...
492
                $args[] = $document->getObjectIdentifier()." (".$document->getTitle().")";
0 ignored issues
show
Bug introduced by
The method getTitle() 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

492
                $args[] = $document->getObjectIdentifier()." (".$document->/** @scrutinizer ignore-call */ getTitle().")";

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...
Bug introduced by
The method getObjectIdentifier() 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

492
                $args[] = $document->/** @scrutinizer ignore-call */ getObjectIdentifier()." (".$document->getTitle().")";

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...
493
            } else {
494
                $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
495
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.retrieve_failed';
496
            }
497
        } catch (\Exception $exception) {
498
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
499
500
            if ($exception instanceof DPFExceptionInterface) {
501
                $key = $exception->messageLanguageKey();
502
            } else {
503
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
504
            }
505
        }
506
507
        // Show success or failure of the action in a flash message
508
509
        $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf', $args);
510
511
        $this->addFlashMessage(
512
            $message,
513
            '',
514
            $severity,
515
            true
516
        );
517
518
        $this->forward('updateIndex', null, null, array('documentObjectIdentifier' => $documentObjectIdentifier));
519
    }
520
521
    /**
522
     *
523
     * @param  string $documentObjectIdentifier
524
     * @return void
525
     */
526
    public function updateIndexAction($documentObjectIdentifier)
527
    {
528
        $document = $this->documentRepository->findByObjectIdentifier($documentObjectIdentifier);
0 ignored issues
show
Bug introduced by
The method findByObjectIdentifier() 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

528
        /** @scrutinizer ignore-call */ 
529
        $document = $this->documentRepository->findByObjectIdentifier($documentObjectIdentifier);
Loading history...
529
530
        if (is_a($document, Document::class)) {
0 ignored issues
show
Bug introduced by
It seems like $document can also be of type array; however, parameter $object of is_a() does only seem to accept object|string, maybe add an additional type check? ( Ignorable by Annotation )

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

530
        if (is_a(/** @scrutinizer ignore-type */ $document, Document::class)) {
Loading history...
531
            $elasticsearchRepository = $this->objectManager->get(ElasticsearchRepository::class);
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\ElasticsearchRepository 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...
532
            $elasticsearchMapper     = $this->objectManager->get(ElasticsearchMapper::class);
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\ElasticsearchMapper 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...
533
            $json                    = $elasticsearchMapper->getElasticsearchJson($document);
534
            // send document to index
535
            $elasticsearchRepository->add($document, $json);
536
        }
537
538
        $this->redirect('search');
539
    }
540
541
542
    /**
543
     * action doubletCheck
544
     *
545
     * @param  \EWW\Dpf\Domain\Model\Document $document
546
     * @return void
547
     */
548
    public function doubletCheckAction(\EWW\Dpf\Domain\Model\Document $document)
549
    {
550
        $this->authorizationChecker->denyAccessUnlessGranted(DocumentVoter::DOUBLET_CHECK, $document);
551
552
        try {
553
            $elasticSearch = $this->objectManager->get(ElasticSearch::class);
554
555
            $client = $this->clientRepository->findAll()->current();
556
557
            // es source fields
558
            // title
559
            // abstract
560
            // author
561
            // language
562
            // publisher
563
            // publisher_place
564
            // distributor
565
            // distributor_place
566
            // distributor_date
567
            // classification
568
            // tag
569
            // identifier
570
            // submitter
571
            // project
572
573
            // is doublet existing?
574
            $query['body']['query']['bool']['must'][]['match']['title'] = $document->getTitle();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$query was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query = array(); before regardless.
Loading history...
575
576
            // set owner id
577
            $query['body']['query']['bool']['must'][]['term']['OWNER_ID'] = $client->getOwnerId();
578
579
            $results = $elasticSearch->search($query, '');
580
581
            $searchList = array();
582
583
            // filter out identical document from the search result list
584
            foreach ($results['hits'] as $entry) {
585
586
                if ($document->getObjectIdentifier() && ($document->getObjectIdentifier() === $entry['_source']['PID'])) {
587
                    continue;
588
                }
589
590
                $entryIdentifier = $entry['_source']['_dissemination']['_content']['identifier'][0];
591
                if (is_numeric($entryIdentifier) && $document->getUid() == $entryIdentifier) {
592
                    continue;
593
                }
594
595
                $searchList[] = $entry;
596
            }
597
598
599
            $objectIdentifiers = $this->documentRepository->getObjectIdentifiers();
600
601
            $this->view->assign('document', $document);
602
            $this->view->assign('searchList', $searchList);
603
            $this->view->assign('alreadyImported', $objectIdentifiers);
604
605
        } catch (\Exception $exception) {
606
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
607
608
            if ($exception instanceof DPFExceptionInterface) {
609
                $key = $exception->messageLanguageKey();
610
            } else {
611
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
612
            }
613
614
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
615
616
            $this->addFlashMessage(
617
                $message,
618
                '',
619
                $severity,
620
                true
621
            );
622
623
            $this->redirect('list', 'Document', null);
624
        }
625
626
    }
627
628
    /**
629
     * returns the query to get latest documents
630
     * @return mixed
631
     */
632
    public function searchLatest()
633
    {
634
        $client = $this->clientRepository->findAll()->current();
635
636
        // get the latest documents /CREATED_DATE
637
        $query['body']['sort'] = array('CREATED_DATE' => array('order' => 'desc'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
$query was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query = array(); before regardless.
Loading history...
638
639
        // add owner id
640
        $query['body']['query']['bool']['must']['term']['OWNER_ID'] = $client->getOwnerId(); // qucosa
641
642
        $query['body']['query']['bool']['should'][0]['query_string']['query']                       = '*';
643
        $query['body']['query']['bool']['should'][1]['has_child']['query']['query_string']['query'] = '*';
644
645
        $query['body']['query']['bool']['minimum_should_match'] = "1"; // 1
646
647
        // child_type is invalid in elasticsearch 7.5
648
        $query['body']['query']['bool']['should'][1]['has_child']['type'] = "datastream"; // 1
649
650
        return $query;
651
    }
652
653
654
    /**
655
     * Returns the number of items to be shown per page.
656
     *
657
     * @return int
658
     */
659
    protected function itemsPerPage()
660
    {
661
        /** @var SearchSessionData $workspaceData */
662
        $workspaceData = $this->session->getWorkspaceData();
663
        $itemsPerPage = $workspaceData->getItemsPerPage();
664
665
        $default = ($this->settings['workspaceItemsPerPage'])? $this->settings['workspaceItemsPerPage'] : 10;
666
        return ($itemsPerPage)? $itemsPerPage : $default;
667
    }
668
669
670
    /**
671
     * escapes lucene reserved characters from string
672
     * @param $string
673
     * @return mixed
674
     */
675
    private function escapeQuery($string)
676
    {
677
        $luceneReservedCharacters = preg_quote('+-&|!(){}[]^~?:\\');
678
        $string                   = preg_replace_callback(
679
            '/([' . $luceneReservedCharacters . '])/',
680
            function ($matches) {
681
                return '\\' . $matches[0];
682
            },
683
            $string
684
        );
685
686
        $string = str_replace("/", "\/", $string);
687
688
        return $string;
689
    }
690
691
}
692