Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — dev-extbase-fluid (#754)
by Alexander
02:59
created

SearchController::injectMetadataRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
/**
3
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
4
 *
5
 * This file is part of the Kitodo and TYPO3 projects.
6
 *
7
 * @license GNU General Public License version 3 or later.
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 */
11
12
namespace Kitodo\Dlf\Controller;
13
14
use Kitodo\Dlf\Common\Doc;
15
use Kitodo\Dlf\Common\DocumentList;
16
use Kitodo\Dlf\Common\Helper;
17
use Kitodo\Dlf\Common\Indexer;
18
use Kitodo\Dlf\Common\Solr;
19
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
20
use TYPO3\CMS\Core\Utility\GeneralUtility;
21
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
22
use Kitodo\Dlf\Domain\Repository\MetadataRepository;
23
24
class SearchController extends AbstractController
25
{
26
    /**
27
     * @var CollectionRepository
28
     */
29
    protected $collectionRepository;
30
31
    /**
32
     * @param CollectionRepository $collectionRepository
33
     */
34
    public function injectCollectionRepository(CollectionRepository $collectionRepository)
35
    {
36
        $this->collectionRepository = $collectionRepository;
37
    }
38
39
    /**
40
     * @var MetadataRepository
41
     */
42
    protected $metadataRepository;
43
44
    /**
45
     * @param MetadataRepository $metadataRepository
46
     */
47
    public function injectMetadataRepository(MetadataRepository $metadataRepository)
48
    {
49
        $this->metadataRepository = $metadataRepository;
50
    }
51
52
    /**
53
     * Search Action
54
     *
55
     * @return void
56
     */
57
    public function searchAction()
58
    {
59
        // if search was triggered, get search parameters from POST variables
60
        $searchParams = $this->getParametersSafely('searchParameter');
0 ignored issues
show
Unused Code introduced by
The assignment to $searchParams is dead and can be removed.
Loading history...
61
62
        // output is done by main action
63
//        $this->forward('main', null, null, ['searchParameter' => $searchParams]);
64
//        $this->forward('main', 'ListView', null, ['searchParameter' => $searchParams]);
65
    }
66
67
    /**
68
     * Main action
69
     *
70
     * @return void
71
     */
72
    public function mainAction()
73
    {
74
        // Quit without doing anything if required variables are not set.
75
        if (empty($this->settings['solrcore'])) {
76
            $this->logger->warning('Incomplete plugin configuration');
77
            return;
78
        }
79
80
        // if search was triggered, get search parameters from POST variables
81
        $searchParams = $this->getParametersSafely('searchParameter');
82
83
        // Pagination of Results: Pass the currentPage to the fluid template to calculate current index of search result.
84
        $widgetPage = $this->getParametersSafely('@widget_0');
85
        if (empty($widgetPage)) {
86
            $widgetPage = ['currentPage' => 1];
87
        }
88
89
        // If a targetPid is given, the results will be shown by ListView on the target page.
90
        if (!empty($this->settings['targetPid']) && !empty($searchParams)) {
91
            $this->redirect('main', 'ListView', null,
92
                [
93
                    'searchParameter' => $searchParams,
94
                    'widgetPage' => $widgetPage,
95
                    'solrcore' => $this->settings['solrcore']
96
                ], $this->settings['targetPid']
97
            );
98
        }
99
100
        // get results from search
101
        // find all documents from Solr
102
        $solrResults = [];
103
        if (is_array($searchParams) && !empty($searchParams)) {
104
            // get all sortable metadata records
105
            $sortableMetadata = $this->metadataRepository->findByIsSortable(true);
0 ignored issues
show
Bug introduced by
The method findByIsSortable() does not exist on Kitodo\Dlf\Domain\Repository\MetadataRepository. 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

105
            /** @scrutinizer ignore-call */ 
106
            $sortableMetadata = $this->metadataRepository->findByIsSortable(true);
Loading history...
106
107
            // get all metadata records to be shown in results
108
            $listedMetadata = $this->metadataRepository->findByIsListed(true);
0 ignored issues
show
Bug introduced by
The method findByIsListed() does not exist on Kitodo\Dlf\Domain\Repository\MetadataRepository. 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

108
            /** @scrutinizer ignore-call */ 
109
            $listedMetadata = $this->metadataRepository->findByIsListed(true);
Loading history...
109
110
            if (is_array($searchParams) && !empty($searchParams)) {
111
                $solrResults = $this->documentRepository->findSolrByCollection('', $this->settings, $searchParams, $listedMetadata);
0 ignored issues
show
Bug introduced by
'' of type string is incompatible with the type Kitodo\Dlf\Domain\Model\Collection expected by parameter $collection of Kitodo\Dlf\Domain\Reposi...:findSolrByCollection(). ( Ignorable by Annotation )

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

111
                $solrResults = $this->documentRepository->findSolrByCollection(/** @scrutinizer ignore-type */ '', $this->settings, $searchParams, $listedMetadata);
Loading history...
112
            }
113
114
            $documents = $solrResults['documents'] ? : [];
115
            $this->view->assign('documents', $documents);
116
            $this->view->assign('widgetPage', $widgetPage);
117
            $this->view->assign('lastSearch', $searchParams);
118
119
            $this->view->assign('listedMetadata', $listedMetadata);
120
            $this->view->assign('sortableMetadata', $sortableMetadata);
121
        }
122
123
        // ABTODO: facets and extended search might fail
124
        // Add the facets menu
125
        $this->addFacetsMenu();
126
127
        // Get additional fields for extended search.
128
        $this->addExtendedSearch();
129
    }
130
131
    /**
132
     * Adds the current document's UID or parent ID to the search form
133
     *
134
     * @access protected
135
     *
136
     * @return string HTML input fields with current document's UID
137
     */
138
    protected function addCurrentDocument()
139
    {
140
        // Load current list object.
141
        $list = GeneralUtility::makeInstance(DocumentList::class);
142
        // Load current document.
143
        if (
144
            !empty($this->requestData['id'])
145
            && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->requestData['id'])
146
        ) {
147
            $this->loadDocument($this->requestData);
148
            // Get document's UID
149
            if ($this->document) {
150
                $this->view->assign('DOCUMENT_ID', $this->document->getUid());
151
            }
152
        } elseif (!empty($list->metadata['options']['params']['filterquery'])) {
153
            // Get document's UID from search metadata.
154
            // The string may be e.g. "{!join from=uid to=partof}uid:{!join from=uid to=partof}uid:2" OR {!join from=uid to=partof}uid:2 OR uid:2"
155
            // or "collection_faceting:("Some Collection Title")"
156
            foreach ($list->metadata['options']['params']['filterquery'] as $facet) {
157
                if (($lastUidPos = strrpos($facet['query'], 'uid:')) !== false) {
158
                    $facetKeyVal = explode(':', substr($facet['query'], $lastUidPos));
159
                    if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($facetKeyVal[1])) {
160
                        $documentId = (int) $facetKeyVal[1];
161
                    }
162
                }
163
            }
164
            if (!empty($documentId)) {
165
                $this->view->assign('DOCUMENT_ID', $documentId);
166
            }
167
        }
168
    }
169
170
171
    /**
172
     * Adds the current collection's UID to the search form
173
     *
174
     * @access protected
175
     *
176
     * @return string HTML input fields with current document's UID and parent ID
177
     */
178
    protected function addCurrentCollection()
179
    {
180
        // Load current collection.
181
        $list = GeneralUtility::makeInstance(DocumentList::class);
182
        if (
183
            !empty($list->metadata['options']['source'])
184
            && $list->metadata['options']['source'] == 'collection'
185
        ) {
186
            $this->view->assign('COLLECTION_ID', $list->metadata['options']['select']);
187
            // Get collection's UID.
188
        } elseif (!empty($list->metadata['options']['params']['filterquery'])) {
189
            // Get collection's UID from search metadata.
190
            foreach ($list->metadata['options']['params']['filterquery'] as $facet) {
191
                $facetKeyVal = explode(':', $facet['query'], 2);
192
                if (
193
                    $facetKeyVal[0] == 'collection_faceting'
194
                    && !strpos($facetKeyVal[1], '" OR "')
195
                ) {
196
                    $collectionId = Helper::getUidFromIndexName(trim($facetKeyVal[1], '(")'), 'tx_dlf_collections');
197
                }
198
            }
199
            $this->view->assign('COLLECTION_ID', $collectionId);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $collectionId does not seem to be defined for all execution paths leading up to this point.
Loading history...
200
        }
201
    }
202
203
    /**
204
     * Adds the facets menu to the search form
205
     *
206
     * @access protected
207
     *
208
     * @return string HTML output of facets menu
209
     */
210
    protected function addFacetsMenu()
211
    {
212
        // Check for typoscript configuration to prevent fatal error.
213
        if (empty($this->settings['facetsConf'])) {
214
            $this->logger->warning('Incomplete plugin configuration');
215
            return '';
216
        }
217
        // Quit without doing anything if no facets are selected.
218
        if (empty($this->settings['facets']) && empty($this->settings['facetCollections'])) {
219
            return '';
220
        }
221
222
        // Get facets from plugin configuration.
223
        $facets = [];
224
        foreach (GeneralUtility::trimExplode(',', $this->settings['facets'], true) as $facet) {
225
            $facets[$facet . '_faceting'] = Helper::translate($facet, 'tx_dlf_metadata', $this->settings['storagePid']);
226
        }
227
228
        $this->view->assign('facetsMenu', $this->makeFacetsMenuArray($facets));
229
    }
230
231
    /**
232
     * This builds a menu array for HMENU
233
     *
234
     * @access public
235
     *
236
     * @param string $content: The PlugIn content
237
     * @param array $conf: The PlugIn configuration
238
     *
239
     * @return array HMENU array
240
     */
241
    public function makeFacetsMenuArray($facets)
242
    {
243
        $menuArray = [];
244
        // Set default value for facet search.
245
        $search = [
246
            'query' => '*',
247
            'params' => [
248
                'component' => [
249
                    'facetset' => [
250
                        'facet' => []
251
                    ]
252
                ]
253
            ]
254
        ];
255
        // Extract query and filter from last search.
256
        $list = GeneralUtility::makeInstance(DocumentList::class);
257
        if (!empty($list->metadata['options']['source'])) {
258
            if ($list->metadata['options']['source'] == 'search') {
259
                $search['query'] = $list->metadata['options']['select'];
260
            }
261
            $search['params'] = $list->metadata['options']['params'];
262
        }
263
        // Get applicable facets.
264
        $solr = Solr::getInstance($this->settings['solrcore']);
265
        if (!$solr->ready) {
266
            $this->logger->error('Apache Solr not available');
267
            return [];
268
        }
269
        // Set needed parameters for facet search.
270
        if (empty($search['params']['filterquery'])) {
271
            $search['params']['filterquery'] = [];
272
        }
273
274
        foreach (array_keys($facets) as $field) {
275
            $search['params']['component']['facetset']['facet'][] = [
276
                'type' => 'field',
277
                'key' => $field,
278
                'field' => $field,
279
                'limit' => $this->settings['limitFacets'],
280
                'sort' => isset($this->settings['sortingFacets']) ? $this->settings['sortingFacets'] : 'count'
281
            ];
282
        }
283
284
        // Set additional query parameters.
285
        $search['params']['start'] = 0;
286
        $search['params']['rows'] = 0;
287
        // Set query.
288
        $search['params']['query'] = $search['query'];
289
        // Perform search.
290
        $selectQuery = $solr->service->createSelect($search['params']);
291
        $results = $solr->service->select($selectQuery);
292
        $facet = $results->getFacetSet();
293
294
        $facetCollectionArray = [];
295
296
        // replace everything expect numbers and comma
297
        $facetCollections = preg_replace('/[^0-9,]/', '', $this->settings['facetCollections']);
298
299
        if (!empty($facetCollections)) {
300
            $collections = $this->collectionRepository->findCollectionsBySettings(['collections' => $facetCollections]);
301
302
            /** @var Collection $collection */
303
            foreach ($collections as $collection) {
304
                $facetCollectionArray[] = $collection->getIndexName();
305
            }
306
        }
307
308
        // Process results.
309
        if ($facet) {
310
            foreach ($facet as $field => $values) {
311
                $entryArray = [];
312
                $entryArray['title'] = htmlspecialchars($facets[$field]);
313
                $entryArray['count'] = 0;
314
                $entryArray['_OVERRIDE_HREF'] = '';
315
                $entryArray['doNotLinkIt'] = 1;
316
                $entryArray['ITEM_STATE'] = 'NO';
317
                // Count number of facet values.
318
                $i = 0;
319
                foreach ($values as $value => $count) {
320
                    if ($count > 0) {
321
                        // check if facet collection configuration exists
322
                        if (!empty($this->settings['facetCollections'])) {
323
                            if ($field == "collection_faceting" && !in_array($value, $facetCollectionArray)) {
324
                                continue;
325
                            }
326
                        }
327
                        $entryArray['count']++;
328
                        if ($entryArray['ITEM_STATE'] == 'NO') {
329
                            $entryArray['ITEM_STATE'] = 'IFSUB';
330
                        }
331
                        $entryArray['_SUB_MENU'][] = $this->getFacetsMenuEntry($field, $value, $count, $search, $entryArray['ITEM_STATE']);
332
                        if (++$i == $this->settings['limit']) {
333
                            break;
334
                        }
335
                    } else {
336
                        break;
337
                    }
338
                }
339
                $menuArray[] = $entryArray;
340
            }
341
        }
342
        return $menuArray;
343
    }
344
345
    /**
346
     * Creates an array for a HMENU entry of a facet value.
347
     *
348
     * @access protected
349
     *
350
     * @param string $field: The facet's index_name
351
     * @param string $value: The facet's value
352
     * @param int $count: Number of hits for this facet
353
     * @param array $search: The parameters of the current search query
354
     * @param string &$state: The state of the parent item
355
     *
356
     * @return array The array for the facet's menu entry
357
     */
358
    protected function getFacetsMenuEntry($field, $value, $count, $search, &$state)
359
    {
360
        $entryArray = [];
361
        // Translate value.
362
        if ($field == 'owner_faceting') {
363
            // Translate name of holding library.
364
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->settings['storagePid']));
365
        } elseif ($field == 'type_faceting') {
366
            // Translate document type.
367
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->settings['storagePid']));
368
        } elseif ($field == 'collection_faceting') {
369
            // Translate name of collection.
370
            $entryArray['title'] = htmlspecialchars(Helper::translate($value, 'tx_dlf_collections', $this->settings['storagePid']));
371
        } elseif ($field == 'language_faceting') {
372
            // Translate ISO 639 language code.
373
            $entryArray['title'] = htmlspecialchars(Helper::getLanguageName($value));
374
        } else {
375
            $entryArray['title'] = htmlspecialchars($value);
376
        }
377
        $entryArray['count'] = $count;
378
        $entryArray['doNotLinkIt'] = 0;
379
        // Check if facet is already selected.
380
        $queryColumn = array_column($search['params']['filterquery'], 'query');
381
        $index = array_search($field . ':("' . Solr::escapeQuery($value) . '")', $queryColumn);
382
        if ($index !== false) {
383
            // Facet is selected, thus remove it from filter.
384
            unset($queryColumn[$index]);
385
            $queryColumn = array_values($queryColumn);
386
            $entryArray['ITEM_STATE'] = 'CUR';
387
            $state = 'ACTIFSUB';
388
            //Reset facets
389
            if ($this->settings['resetFacets']) {
390
                //remove ($count) for selected facet in template
391
                $entryArray['count'] = false;
392
                //build link to delete selected facet
393
                $uri = $this->uriBuilder->reset()
394
                    ->setTargetPageUid($GLOBALS['TSFE']->id)
395
                    ->setArguments(['tx_dlf' => ['query' => $search['query'], 'fq' => $queryColumn], 'tx_dlf_search' => ['action' => 'search']])
396
                    ->setAddQueryString(true)
397
                    ->build();
398
                $entryArray['_OVERRIDE_HREF'] = $uri;
399
                $entryArray['title'] = sprintf(LocalizationUtility::translate('search.resetFacet', 'dlf'), $entryArray['title']);
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Extbase\Utilit...rch.resetFacet', 'dlf') can also be of type null; however, parameter $format of sprintf() does only seem to accept 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

399
                $entryArray['title'] = sprintf(/** @scrutinizer ignore-type */ LocalizationUtility::translate('search.resetFacet', 'dlf'), $entryArray['title']);
Loading history...
400
            }
401
        } else {
402
            // Facet is not selected, thus add it to filter.
403
            $queryColumn[] = $field . ':("' . Solr::escapeQuery($value) . '")';
404
            $entryArray['ITEM_STATE'] = 'NO';
405
        }
406
        $uri = $this->uriBuilder->reset()
407
            ->setTargetPageUid($GLOBALS['TSFE']->id)
408
            ->setArguments(['tx_dlf' => ['query' => $search['query'], 'fq' => $queryColumn], 'tx_dlf_search' => ['action' => 'search']])
409
            ->setArgumentPrefix('tx_dlf')
410
            ->build();
411
        $entryArray['_OVERRIDE_HREF'] = $uri;
412
413
        return $entryArray;
414
    }
415
416
    /**
417
     * Returns the extended search form and adds the JS files necessary for extended search.
418
     *
419
     * @access protected
420
     *
421
     * @return string The extended search form or an empty string
422
     */
423
    protected function addExtendedSearch()
424
    {
425
        // Quit without doing anything if no fields for extended search are selected.
426
        if (
427
            empty($this->settings['extendedSlotCount'])
428
            || empty($this->settings['extendedFields'])
429
        ) {
430
            return '';
431
        }
432
        // Get operator options.
433
        $operatorOptions = [];
434
        foreach (['AND', 'OR', 'NOT'] as $operator) {
435
            $operatorOptions[$operator] = htmlspecialchars(LocalizationUtility::translate('search.' . $operator, 'dlf'));
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Extbase\Utilit...h.' . $operator, 'dlf') can also be of type null; however, parameter $string of htmlspecialchars() does only seem to accept 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

435
            $operatorOptions[$operator] = htmlspecialchars(/** @scrutinizer ignore-type */ LocalizationUtility::translate('search.' . $operator, 'dlf'));
Loading history...
436
        }
437
        // Get field selector options.
438
        $fieldSelectorOptions = [];
439
        $searchFields = GeneralUtility::trimExplode(',', $this->settings['extendedFields'], true);
440
        foreach ($searchFields as $searchField) {
441
            $fieldSelectorOptions[$searchField] = Helper::translate($searchField, 'tx_dlf_metadata', $this->settings['storagePid']);
442
        }
443
        $slotCountArray = [];
444
        for ($i = 0; $i < $this->settings['extendedSlotCount']; $i++) {
445
            $slotCountArray[] = $i;
446
        }
447
448
        $this->view->assign('extendedSlotCount', $slotCountArray);
449
        $this->view->assign('extendedFields', $this->settings['extendedFields']);
450
        $this->view->assign('operators', $operatorOptions);
451
        $this->view->assign('searchFields', $fieldSelectorOptions);
452
    }
453
}
454