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.
Completed
Push — master ( 70fd28...767599 )
by Sebastian
23s queued 11s
created

Collection::showCollectionList()   F

Complexity

Conditions 26
Paths > 20000

Size

Total Lines 137
Code Lines 95

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 26
eloc 95
nc 56160
nop 0
dl 0
loc 137
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Kitodo\Dlf\Plugins;
3
4
/**
5
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
6
 *
7
 * This file is part of the Kitodo and TYPO3 projects.
8
 *
9
 * @license GNU General Public License version 3 or later.
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 */
13
14
use Kitodo\Dlf\Common\DocumentList;
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\Solr;
17
18
/**
19
 * Plugin 'Collection' for the 'dlf' extension
20
 *
21
 * @author Sebastian Meyer <[email protected]>
22
 * @package TYPO3
23
 * @subpackage dlf
24
 * @access public
25
 */
26
class Collection extends \Kitodo\Dlf\Common\AbstractPlugin {
27
    public $scriptRelPath = 'Classes/Plugins/Collection.php';
28
29
    /**
30
     * This holds the hook objects
31
     *
32
     * @var array
33
     * @access protected
34
     */
35
    protected $hookObjects = [];
36
37
    /**
38
     * The main method of the PlugIn
39
     *
40
     * @access public
41
     *
42
     * @param string $content: The PlugIn content
43
     * @param array $conf: The PlugIn configuration
44
     *
45
     * @return string The content that is displayed on the website
46
     */
47
    public function main($content, $conf) {
48
        $this->init($conf);
49
        // Turn cache on.
50
        $this->setCache(TRUE);
51
        // Quit without doing anything if required configuration variables are not set.
52
        if (empty($this->conf['pages'])) {
53
            Helper::devLog('Incomplete plugin configuration', DEVLOG_SEVERITY_WARNING);
54
            return $content;
55
        }
56
        // Load template file.
57
        $this->getTemplate();
58
        // Get hook objects.
59
        $this->hookObjects = Helper::getHookObjects($this->scriptRelPath);
60
        if (!empty($this->piVars['collection'])) {
61
            $this->showSingleCollection(intval($this->piVars['collection']));
62
        } else {
63
            $content .= $this->showCollectionList();
64
        }
65
        return $this->pi_wrapInBaseClass($content);
66
    }
67
68
    /**
69
     * Builds a collection list
70
     *
71
     * @access protected
72
     *
73
     * @return string The list of collections ready to output
74
     */
75
    protected function showCollectionList() {
76
        $selectedCollections = 'tx_dlf_collections.uid != 0';
77
        $orderBy = 'tx_dlf_collections.label';
78
        $showUserDefinedColls = '';
79
        // Handle collections set by configuration.
80
        if ($this->conf['collections']) {
81
            if (count(explode(',', $this->conf['collections'])) == 1
82
                && empty($this->conf['dont_show_single'])) {
83
                $this->showSingleCollection(intval(trim($this->conf['collections'], ' ,')));
84
            }
85
            $selectedCollections = 'tx_dlf_collections.uid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')';
86
            $orderBy = 'FIELD(tx_dlf_collections.uid,'.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')';
87
        }
88
        // Should user-defined collections be shown?
89
        if (empty($this->conf['show_userdefined'])) {
90
            $showUserDefinedColls = ' AND tx_dlf_collections.fe_cruser_id=0';
91
        } elseif ($this->conf['show_userdefined'] > 0) {
92
            if (!empty($GLOBALS['TSFE']->fe_user->user['uid'])) {
93
                $showUserDefinedColls = ' AND tx_dlf_collections.fe_cruser_id='.intval($GLOBALS['TSFE']->fe_user->user['uid']);
94
            } else {
95
                $showUserDefinedColls = ' AND NOT tx_dlf_collections.fe_cruser_id=0';
96
            }
97
        }
98
        // Get collections.
99
        $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
100
            'tx_dlf_collections.index_name AS index_name,tx_dlf_collections.index_search as index_query,tx_dlf_collections.uid AS uid,tx_dlf_collections.sys_language_uid AS sys_language_uid,tx_dlf_collections.label AS label,tx_dlf_collections.thumbnail AS thumbnail,tx_dlf_collections.description AS description,tx_dlf_collections.priority AS priority',
101
            'tx_dlf_collections',
102
            $selectedCollections
103
                .$showUserDefinedColls
104
                .' AND tx_dlf_collections.pid='.intval($this->conf['pages'])
105
                .' AND (tx_dlf_collections.sys_language_uid IN (-1,0) OR (tx_dlf_collections.sys_language_uid = '.$GLOBALS['TSFE']->sys_language_uid.' AND tx_dlf_collections.l18n_parent = 0))'
106
                .Helper::whereClause('tx_dlf_collections'),
107
            '',
108
            $orderBy,
109
            ''
110
        );
111
        $count = $GLOBALS['TYPO3_DB']->sql_num_rows($result);
112
        $content = '';
113
        if ($count == 1
114
            && empty($this->conf['dont_show_single'])) {
115
            $resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
116
            $this->showSingleCollection(intval($resArray['uid']));
117
        }
118
        $solr = Solr::getInstance($this->conf['solrcore']);
119
        // We only care about the UID and partOf in the results and want them sorted
120
        $params['fields'] = 'uid,partof';
1 ignored issue
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
121
        $params['sort'] = ['uid' => 'asc'];
122
        $collections = [];
123
        while ($collectionData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
124
            if ($collectionData['sys_language_uid'] != $GLOBALS['TSFE']->sys_language_content && $GLOBALS['TSFE']->sys_language_contentOL) {
125
                $collections[$collectionData['uid']] = $GLOBALS['TSFE']->sys_page->getRecordOverlay('tx_dlf_collections', $collectionData, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
126
            } else {
127
                $collections[$collectionData['uid']] = $collectionData;
128
            }
129
        }
130
        $markerArray = [];
131
        // Process results.
132
        foreach ($collections as $collection) {
133
            $solr_query = '';
134
            if ($collection['index_query'] != '') {
135
                $solr_query .= '('.$collection['index_query'].')';
136
            } else {
137
                $solr_query .= 'collection:("'.$collection['index_name'].'")';
138
            }
139
            $partOfNothing = $solr->search_raw($solr_query.' AND partof:0', $params);
140
            $partOfSomething = $solr->search_raw($solr_query.' AND NOT partof:0', $params);
141
            // Titles are all documents that are "root" elements i.e. partof == 0
142
            $collection['titles'] = [];
143
            foreach ($partOfNothing as $doc) {
144
                $collection['titles'][$doc->uid] = $doc->uid;
145
            }
146
            // Volumes are documents that are both
147
            // a) "leaf" elements i.e. partof != 0
148
            // b) "root" elements that are not referenced by other documents ("root" elements that have no descendants)
149
            $collection['volumes'] = $collection['titles'];
150
            foreach ($partOfSomething as $doc) {
151
                $collection['volumes'][$doc->uid] = $doc->uid;
152
                // If a document is referenced via partof, it’s not a volume anymore.
153
                unset($collection['volumes'][$doc->partof]);
154
            }
155
            // Generate random but unique array key taking priority into account.
156
            do {
157
                $_key = ($collection['priority'] * 1000) + mt_rand(0, 1000);
158
            } while (!empty($markerArray[$_key]));
159
            // Merge plugin variables with new set of values.
160
            $additionalParams = ['collection' => $collection['uid']];
161
            if (is_array($this->piVars)) {
162
                $piVars = $this->piVars;
163
                unset($piVars['DATA']);
164
                $additionalParams = \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($piVars, $additionalParams);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $additionalParams is correct as TYPO3\CMS\Core\Utility\A...ars, $additionalParams) targeting TYPO3\CMS\Core\Utility\A...RecursiveWithOverrule() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
165
            }
166
            // Build typolink configuration array.
167
            $conf = [
168
                'useCacheHash' => 1,
169
                'parameter' => $GLOBALS['TSFE']->id,
170
                'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', TRUE, FALSE)
0 ignored issues
show
Bug introduced by
$additionalParams of type null is incompatible with the type array expected by parameter $theArray of TYPO3\CMS\Core\Utility\G...y::implodeArrayForUrl(). ( Ignorable by Annotation )

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

170
                'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, /** @scrutinizer ignore-type */ $additionalParams, '', TRUE, FALSE)
Loading history...
171
            ];
172
            // Link collection's title to list view.
173
            $markerArray[$_key]['###TITLE###'] = $this->cObj->typoLink(htmlspecialchars($collection['label']), $conf);
174
            // Add feed link if applicable.
175
            if (!empty($this->conf['targetFeed'])) {
176
                $img = '<img src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'Resources/Public/Icons/txdlffeeds.png" alt="'.$this->pi_getLL('feedAlt', '', TRUE).'" title="'.$this->pi_getLL('feedTitle', '', TRUE).'" />';
177
                $markerArray[$_key]['###FEED###'] = $this->pi_linkTP($img, [$this->prefixId => ['collection' => $collection['uid']]], FALSE, $this->conf['targetFeed']);
178
            } else {
179
                $markerArray[$_key]['###FEED###'] = '';
180
            }
181
            // Add thumbnail.
182
            if (!empty($collection['thumbnail'])) {
183
                $markerArray[$_key]['###THUMBNAIL###'] = '<img alt="" title="'.htmlspecialchars($collection['label']).'" src="'.$collection['thumbnail'].'" />';
184
            } else {
185
                $markerArray[$_key]['###THUMBNAIL###'] = '';
186
            }
187
            // Add description.
188
            $markerArray[$_key]['###DESCRIPTION###'] = $this->pi_RTEcssText($collection['description']);
189
            // Build statistic's output.
190
            $labelTitles = $this->pi_getLL((count($collection['titles']) > 1 ? 'titles' : 'title'), '', FALSE);
191
            $markerArray[$_key]['###COUNT_TITLES###'] = htmlspecialchars(count($collection['titles']).$labelTitles);
192
            $labelVolumes = $this->pi_getLL((count($collection['volumes']) > 1 ? 'volumes' : 'volume'), '', FALSE);
193
            $markerArray[$_key]['###COUNT_VOLUMES###'] = htmlspecialchars(count($collection['volumes']).$labelVolumes);
194
        }
195
        // Randomize sorting?
196
        if (!empty($this->conf['randomize'])) {
197
            ksort($markerArray, SORT_NUMERIC);
198
            // Don't cache the output.
199
            $this->setCache(FALSE);
200
        }
201
        $entry = $this->cObj->getSubpart($this->template, '###ENTRY###');
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Conte...tRenderer::getSubpart() has been deprecated: since TYPO3 v8, will be removed in TYPO3 v9, please use the MarkerBasedTemplateService instead. ( Ignorable by Annotation )

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

201
        $entry = /** @scrutinizer ignore-deprecated */ $this->cObj->getSubpart($this->template, '###ENTRY###');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
202
        foreach ($markerArray as $marker) {
203
            $content .= $this->cObj->substituteMarkerArray($entry, $marker);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Conte...substituteMarkerArray() has been deprecated: since TYPO3 v8, will be removed in TYPO3 v9, please use the MarkerBasedTemplateService instead. ( Ignorable by Annotation )

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

203
            $content .= /** @scrutinizer ignore-deprecated */ $this->cObj->substituteMarkerArray($entry, $marker);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
204
        }
205
        // Hook for getting custom collection hierarchies/subentries (requested by SBB).
206
        foreach ($this->hookObjects as $hookObj) {
207
            if (method_exists($hookObj, 'showCollectionList_getCustomCollectionList')) {
208
                $hookObj->showCollectionList_getCustomCollectionList($this, $this->conf['templateFile'], $content, $markerArray);
209
            }
210
        }
211
        return $this->cObj->substituteSubpart($this->template, '###ENTRY###', $content, TRUE);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Conte...er::substituteSubpart() has been deprecated: since TYPO3 v8, will be removed in TYPO3 v9, please use the MarkerBasedTemplateService instead. ( Ignorable by Annotation )

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

211
        return /** @scrutinizer ignore-deprecated */ $this->cObj->substituteSubpart($this->template, '###ENTRY###', $content, TRUE);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
212
    }
213
214
    /**
215
     * Builds a collection's list
216
     *
217
     * @access protected
218
     *
219
     * @param integer $id: The collection's UID
220
     *
221
     * @return void
222
     */
223
    protected function showSingleCollection($id) {
224
        $additionalWhere = '';
225
        // Should user-defined collections be shown?
226
        if (empty($this->conf['show_userdefined'])) {
227
            $additionalWhere = ' AND tx_dlf_collections.fe_cruser_id=0';
228
        } elseif ($this->conf['show_userdefined'] > 0) {
229
            $additionalWhere = ' AND NOT tx_dlf_collections.fe_cruser_id=0';
230
        }
231
        // Get collection information from DB
232
        $collection = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
233
            'tx_dlf_collections.index_name AS index_name, tx_dlf_collections.index_search as index_query, tx_dlf_collections.label AS collLabel, tx_dlf_collections.description AS collDesc, tx_dlf_collections.thumbnail AS collThumb, tx_dlf_collections.fe_cruser_id',
234
            'tx_dlf_collections',
235
            'tx_dlf_collections.pid='.intval($this->conf['pages'])
236
                .' AND tx_dlf_collections.uid='.intval($id)
237
                .$additionalWhere
238
                .Helper::whereClause('tx_dlf_collections'),
239
            '',
240
            '',
241
            '1'
242
        );
243
        // Fetch corresponding document UIDs from Solr.
244
        $solr_query = '';
245
        $collectionData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($collection);
246
        if ($collectionData['index_query'] != '') {
247
            $solr_query .= '('.$collectionData['index_query'].')';
248
        } else {
249
            $solr_query .= 'collection:("'.$collectionData['index_name'].'")';
250
        }
251
        $solr = Solr::getInstance($this->conf['solrcore']);
252
        if (!$solr->ready) {
0 ignored issues
show
Bug Best Practice introduced by
The property $ready is declared protected in Kitodo\Dlf\Common\Solr. Since you implement __get, consider adding a @property or @property-read.
Loading history...
253
            Helper::devLog('Apache Solr not available', DEVLOG_SEVERITY_ERROR);
254
            return;
255
        }
256
        $params['fields'] = 'uid';
1 ignored issue
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
257
        $params['sort'] = ['uid' => 'asc'];
258
        $solrResult = $solr->search_raw($solr_query, $params);
259
        // Initialize array
260
        $documentSet = [];
261
        foreach ($solrResult as $doc) {
262
            $documentSet[] = $doc->uid;
263
        }
264
        $documentSet = array_unique($documentSet);
265
        // Fetch document info for UIDs in $documentSet from DB
266
        $documents = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
267
            'tx_dlf_documents.uid AS uid, tx_dlf_documents.metadata_sorting AS metadata_sorting, tx_dlf_documents.volume_sorting AS volume_sorting, tx_dlf_documents.partof AS partof',
268
            'tx_dlf_documents',
269
            'tx_dlf_documents.pid='.intval($this->conf['pages'])
270
                .' AND tx_dlf_documents.uid IN ('.implode(',', $documentSet).')'
271
                .Helper::whereClause('tx_dlf_documents'),
272
            '',
273
            '',
274
            ''
275
        );
276
        $toplevel = [];
277
        $subparts = [];
278
        $listMetadata = [];
279
        // Process results.
280
        while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($documents)) {
281
            if (empty($l10nOverlay)) {
282
                $l10nOverlay = $GLOBALS['TSFE']->sys_page->getRecordOverlay('tx_dlf_collections', $resArray, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
283
            }
284
            if (empty($listMetadata)) {
285
                $listMetadata = [
286
                    'label' => !empty($l10nOverlay['label']) ? htmlspecialchars($l10nOverlay['label']) : htmlspecialchars($collectionData['collLabel']),
287
                    'description' => !empty($l10nOverlay['description']) ? $this->pi_RTEcssText($l10nOverlay['description']) : $this->pi_RTEcssText($collectionData['collDesc']),
288
                    'thumbnail' => htmlspecialchars($collectionData['collThumb']),
289
                    'options' => [
290
                        'source' => 'collection',
291
                        'select' => $id,
292
                        'userid' => $collectionData['userid'],
293
                        'params' => ['filterquery' => [['query' => 'collection_faceting:("'.$collectionData['index_name'].'")']]],
294
                        'core' => '',
295
                        'pid' => $this->conf['pages'],
296
                        'order' => 'title',
297
                        'order.asc' => TRUE
298
                    ]
299
                ];
300
            }
301
            // Split toplevel documents from volumes.
302
            if ($resArray['partof'] == 0) {
303
                // Prepare document's metadata for sorting.
304
                $sorting = unserialize($resArray['metadata_sorting']);
305
                if (!empty($sorting['type']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['type'])) {
306
                    $sorting['type'] = Helper::getIndexNameFromUid($sorting['type'], 'tx_dlf_structures', $this->conf['pages']);
307
                }
308
                if (!empty($sorting['owner']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['owner'])) {
309
                    $sorting['owner'] = Helper::getIndexNameFromUid($sorting['owner'], 'tx_dlf_libraries', $this->conf['pages']);
310
                }
311
                if (!empty($sorting['collection']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['collection'])) {
312
                    $sorting['collection'] = Helper::getIndexNameFromUid($sorting['collection'], 'tx_dlf_collections', $this->conf['pages']);
313
                }
314
                $toplevel[$resArray['uid']] = [
315
                    'u' => $resArray['uid'],
316
                    'h' => '',
317
                    's' => $sorting,
318
                    'p' => []
319
                ];
320
            } else {
321
                $subparts[$resArray['partof']][$resArray['volume_sorting']] = $resArray['uid'];
322
            }
323
        }
324
        // Add volumes to the corresponding toplevel documents.
325
        foreach ($subparts as $partof => $parts) {
326
            if (!empty($toplevel[$partof])) {
327
                ksort($parts);
328
                foreach ($parts as $part) {
329
                    $toplevel[$partof]['p'][] = ['u' => $part];
330
                }
331
            }
332
        }
333
        // Save list of documents.
334
        $list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(DocumentList::class);
335
        $list->reset();
336
        $list->add(array_values($toplevel));
337
        $listMetadata['options']['numberOfToplevelHits'] = count($list);
338
        $list->metadata = $listMetadata;
339
        $list->save();
340
        // Clean output buffer.
341
        \TYPO3\CMS\Core\Utility\GeneralUtility::cleanOutputBuffers();
0 ignored issues
show
Bug introduced by
The method cleanOutputBuffers() does not exist on TYPO3\CMS\Core\Utility\GeneralUtility. ( Ignorable by Annotation )

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

341
        \TYPO3\CMS\Core\Utility\GeneralUtility::/** @scrutinizer ignore-call */ 
342
                                                cleanOutputBuffers();

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...
342
        // Send headers.
343
        header('Location: '.\TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl($this->cObj->typoLink_URL(['parameter' => $this->conf['targetPid']])));
344
        // Flush output buffer and end script processing.
345
        ob_end_flush();
346
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
347
    }
348
}
349