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 — master (#715)
by Alexander
07:45
created

CollectionController::mainAction()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 22
rs 9.9666
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\DocumentList;
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\Solr;
17
use Kitodo\Dlf\Domain\Model\Document;
18
use TYPO3\CMS\Core\Utility\GeneralUtility;
19
use TYPO3\CMS\Core\Utility\MathUtility;
20
use Kitodo\Dlf\Domain\Repository\CollectionRepository;
21
22
class CollectionController extends AbstractController
23
{
24
    /**
25
     * This holds the hook objects
26
     *
27
     * @var array
28
     * @access protected
29
     */
30
    protected $hookObjects = [];
31
32
    /**
33
     * @var CollectionRepository
34
     */
35
    protected $collectionRepository;
36
37
    /**
38
     * @param CollectionRepository $collectionRepository
39
     */
40
    public function injectCollectionRepository(CollectionRepository $collectionRepository)
41
    {
42
        $this->collectionRepository = $collectionRepository;
43
    }
44
45
    /**
46
     * The main method of the plugin
47
     *
48
     * @return void
49
     */
50
    public function mainAction()
51
    {
52
        // access to GET parameter tx_dlf_collection['collection']
53
        $requestData = $this->request->getArguments();
54
55
        $collection = $requestData['collection'];
56
57
        // Quit without doing anything if required configuration variables are not set.
58
        if (empty($this->settings['storagePid'])) {
59
            $this->logger->warning('Incomplete plugin configuration');
60
        }
61
62
        // Get hook objects.
63
        // TODO: $this->hookObjects = Helper::getHookObjects($this->scriptRelPath);
64
65
        if ($collection) {
66
            $this->showSingleCollection($this->collectionRepository->findByUid($collection[0]));
0 ignored issues
show
Bug introduced by
It seems like $this->collectionReposit...ndByUid($collection[0]) can also be of type null; however, parameter $collection of Kitodo\Dlf\Controller\Co...:showSingleCollection() does only seem to accept Kitodo\Dlf\Domain\Model\Collection, 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

66
            $this->showSingleCollection(/** @scrutinizer ignore-type */ $this->collectionRepository->findByUid($collection[0]));
Loading history...
67
        } else {
68
            $this->showCollectionList();
69
        }
70
71
        $this->view->assign('currentPageUid', $GLOBALS['TSFE']->id);
72
    }
73
74
    /**
75
     * Builds a collection list
76
     * @return void
77
     */
78
    protected function showCollectionList()
79
    {
80
        $solr = Solr::getInstance($this->settings['solrcore']);
81
82
        if (!$solr->ready) {
83
            $this->logger->error('Apache Solr not available');
84
            return;
85
        }
86
        // We only care about the UID and partOf in the results and want them sorted
87
        $params['fields'] = 'uid,partof';
88
        $params['sort'] = ['uid' => 'asc'];
89
        $collections = [];
90
91
        // Sort collections according to flexform configuration
92
        if ($this->settings['collections']) {
93
            $sortedCollections = [];
94
            foreach (GeneralUtility::intExplode(',', $this->settings['collections']) as $uid) {
95
                $sortedCollections[$uid] = $this->collectionRepository->findByUid($uid);
96
            }
97
            $collections = $sortedCollections;
98
        }
99
100
        if (count($collections) == 1 && empty($this->settings['dont_show_single'])) {
101
            $this->showSingleCollection(array_pop($collections));
102
        }
103
104
        $processedCollections = [];
105
106
        // Process results.
107
        foreach ($collections as $collection) {
108
            $solr_query = '';
109
            if ($collection->getIndexSearch() != '') {
110
                $solr_query .= '(' . $collection->getIndexSearch() . ')';
111
            } else {
112
                $solr_query .= 'collection:("' . Solr::escapeQuery($collection->getIndexName()) . '")';
113
            }
114
            $partOfNothing = $solr->search_raw($solr_query . ' AND partof:0 AND toplevel:true', $params);
115
            $partOfSomething = $solr->search_raw($solr_query . ' AND NOT partof:0 AND toplevel:true', $params);
116
            // Titles are all documents that are "root" elements i.e. partof == 0
117
            $collectionInfo['titles'] = [];
118
            foreach ($partOfNothing as $doc) {
119
                $collectionInfo['titles'][$doc->uid] = $doc->uid;
120
            }
121
            // Volumes are documents that are both
122
            // a) "leaf" elements i.e. partof != 0
123
            // b) "root" elements that are not referenced by other documents ("root" elements that have no descendants)
124
            $collectionInfo['volumes'] = $collectionInfo['titles'];
125
            foreach ($partOfSomething as $doc) {
126
                $collectionInfo['volumes'][$doc->uid] = $doc->uid;
127
                // If a document is referenced via partof, it’s not a volume anymore.
128
                unset($collectionInfo['volumes'][$doc->partof]);
129
            }
130
131
            // Generate random but unique array key taking priority into account.
132
            do {
133
                $_key = ($collectionInfo['priority'] * 1000) + mt_rand(0, 1000);
134
            } while (!empty($processedCollections[$_key]));
135
136
            $processedCollections[$_key]['collection'] = $collection;
137
            $processedCollections[$_key]['info'] = $collectionInfo;
138
        }
139
140
        // Randomize sorting?
141
        if (!empty($this->settings['randomize'])) {
142
            ksort($processedCollections, SORT_NUMERIC);
143
        }
144
145
        // TODO: Hook for getting custom collection hierarchies/subentries (requested by SBB).
146
        /*    foreach ($this->hookObjects as $hookObj) {
147
                if (method_exists($hookObj, 'showCollectionList_getCustomCollectionList')) {
148
                    $hookObj->showCollectionList_getCustomCollectionList($this, $this->settings['templateFile'], $content, $markerArray);
149
                }
150
            }
151
        */
152
153
        $this->view->assign('collections', $processedCollections);
154
    }
155
156
    /**
157
     * Builds a collection's list
158
     *
159
     * @access protected
160
     *
161
     * @param \Kitodo\Dlf\Domain\Model\Collection $collection: The collection object
162
     *
163
     * @return void
164
     */
165
    protected function showSingleCollection(\Kitodo\Dlf\Domain\Model\Collection $collection)
166
    {
167
        // access storagePid from TypoScript
168
        $pageSettings = $this->configurationManager->getConfiguration($this->configurationManager::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);
169
        $this->settings['storagePid'] = $pageSettings["plugin."]["tx_dlf."]["persistence."]["storagePid"];
170
171
        // Fetch corresponding document UIDs from Solr.
172
        if ($collection->getIndexSearch() != '') {
173
            $solr_query = '(' . $collection->getIndexSearch() . ')';
174
        } else {
175
            $solr_query = 'collection:("' . Solr::escapeQuery($collection->getIndexName()) . '") AND toplevel:true';
176
        }
177
        $solr = Solr::getInstance($this->settings['solrcore']);
178
        if (!$solr->ready) {
179
            $this->logger->error('Apache Solr not available');
180
            return;
181
        }
182
        $params['fields'] = 'uid';
183
        $params['sort'] = ['uid' => 'asc'];
184
        $solrResult = $solr->search_raw($solr_query, $params);
185
        // Initialize array
186
        $documentSet = [];
187
        foreach ($solrResult as $doc) {
188
            if ($doc->uid) {
189
                $documentSet[] = $doc->uid;
190
            }
191
        }
192
        $documentSet = array_unique($documentSet);
193
194
        $this->settings['documentSets'] = implode(',', $documentSet);
195
196
        $documents = $this->documentRepository->findDocumentsBySettings($this->settings);
197
198
        $toplevel = [];
199
        $subparts = [];
200
        $listMetadata = [];
201
        // Process results.
202
        /** @var Document $document */
203
        foreach ($documents as $document) {
204
            if (empty($listMetadata)) {
205
                $listMetadata = [
206
                    'label' => htmlspecialchars($collection->getLabel()),
207
                    'description' => $collection->getDescription(),
208
                    'thumbnail' => htmlspecialchars($collection->getThumbnail()),
209
                    'options' => [
210
                        'source' => 'collection',
211
                        'select' => $collection->getUid(),
212
                        'userid' => $collection->getFeCruserId(),
213
                        'params' => ['filterquery' => [['query' => 'collection_faceting:("' . $collection->getIndexName() . '")']]],
214
                        'core' => '',
215
                        'order' => 'title',
216
                        'order.asc' => true
217
                    ]
218
                ];
219
            }
220
            // Prepare document's metadata for sorting.
221
            $sorting = unserialize($document->getMetadataSorting());
222
            if (!empty($sorting['type']) && MathUtility::canBeInterpretedAsInteger($sorting['type'])) {
223
                $sorting['type'] = Helper::getIndexNameFromUid($sorting['type'], 'tx_dlf_structures', $this->settings['storagePid']);
224
            }
225
            if (!empty($sorting['owner']) && MathUtility::canBeInterpretedAsInteger($sorting['owner'])) {
226
                $sorting['owner'] = Helper::getIndexNameFromUid($sorting['owner'], 'tx_dlf_libraries', $this->settings['storagePid']);
227
            }
228
            if (!empty($sorting['collection']) && MathUtility::canBeInterpretedAsInteger($sorting['collection'])) {
229
                $sorting['collection'] = Helper::getIndexNameFromUid($sorting['collection'], 'tx_dlf_collections', $this->settings['storagePid']);
230
            }
231
            // Split toplevel documents from volumes.
232
            if ($document->getPartof() == 0) {
233
                $toplevel[$document->getUid()] = [
234
                    'u' => $document->getUid(),
235
                    'h' => '',
236
                    's' => $sorting,
237
                    'p' => []
238
                ];
239
            } else {
240
                // volume_sorting should be always set - but it's not a required field. We append the uid to the array key to make it always unique.
241
                $subparts[$document->getPartof()][$document->getVolumeSorting() . str_pad($document->getUid(), 9, '0', STR_PAD_LEFT)] = [
242
                    'u' => $document->getUid(),
243
                    'h' => '',
244
                    's' => $sorting,
245
                    'p' => []
246
                ];
247
            }
248
        }
249
250
        // Add volumes to the corresponding toplevel documents.
251
        foreach ($subparts as $partof => $parts) {
252
            ksort($parts);
253
            foreach ($parts as $part) {
254
                if (!empty($toplevel[$partof])) {
255
                    $toplevel[$partof]['p'][] = ['u' => $part['u']];
256
                } else {
257
                    $toplevel[$part['u']] = $part;
258
                }
259
            }
260
        }
261
        // Save list of documents.
262
        $list = GeneralUtility::makeInstance(DocumentList::class);
263
        $list->reset();
264
        $list->add(array_values($toplevel));
265
        $listMetadata['options']['numberOfToplevelHits'] = count($list);
266
        $list->metadata = $listMetadata;
267
        $list->sort('title');
268
        $list->save();
269
        // Clean output buffer.
270
        ob_end_clean();
271
272
        $uri = $this->uriBuilder
273
            ->reset()
274
            ->setTargetPageUid($this->settings['targetPid'])
275
            ->uriFor('main', [], 'ListView', 'dlf', 'ListView');
276
        $this->redirectToURI($uri);
277
    }
278
}
279