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
06:09 queued 03:33
created

CollectionController   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 255
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 127
c 2
b 0
f 0
dl 0
loc 255
rs 9.76
wmc 33

4 Methods

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