tx_dlf_collection::showSingleCollection()   F
last analyzed

Complexity

Conditions 15
Paths 0

Size

Total Lines 131
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 60
nc 0
nop 1
dl 0
loc 131
rs 2
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
/**
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
/**
13
 * Plugin 'DLF: Collection' for the 'dlf' extension.
14
 *
15
 * @author	Sebastian Meyer <[email protected]>
16
 * @package	TYPO3
17
 * @subpackage	tx_dlf
18
 * @access	public
19
 */
20
class tx_dlf_collection extends tx_dlf_plugin {
21
22
    public $scriptRelPath = 'plugins/collection/class.tx_dlf_collection.php';
23
24
    /**
25
     * This holds the hook objects
26
     *
27
     * @var	array
28
     * @access protected
29
     */
30
    protected $hookObjects = array ();
31
32
    /**
33
     * The main method of the PlugIn
34
     *
35
     * @access	public
36
     *
37
     * @param	string		$content: The PlugIn content
38
     * @param	array		$conf: The PlugIn configuration
39
     *
40
     * @return	string		The content that is displayed on the website
41
     */
42
    public function main($content, $conf) {
43
44
        $this->init($conf);
45
46
        // Turn cache on.
47
        $this->setCache(TRUE);
48
49
        // Quit without doing anything if required configuration variables are not set.
50
        if (empty($this->conf['pages'])) {
51
52
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
53
54
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_collection->main('.$content.', [data])] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf);
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\GeneralUtility 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...
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
55
56
            }
57
58
            return $content;
59
60
        }
61
62
        // Load template file.
63
        if (!empty($this->conf['templateFile'])) {
64
65
            $this->template = $this->cObj->getSubpart($this->cObj->fileResource($this->conf['templateFile']), '###TEMPLATE###');
66
67
        } else {
68
69
            $this->template = $this->cObj->getSubpart($this->cObj->fileResource('EXT:dlf/plugins/collection/template.tmpl'), '###TEMPLATE###');
70
71
        }
72
73
        // Get hook objects.
74
        $this->hookObjects = tx_dlf_helper::getHookObjects($this->scriptRelPath);
75
76
        if (!empty($this->piVars['collection'])) {
77
78
            $this->showSingleCollection(intval($this->piVars['collection']));
79
80
        } else {
81
82
            $content .= $this->showCollectionList();
83
84
        }
85
86
        return $this->pi_wrapInBaseClass($content);
87
88
    }
89
90
    /**
91
     * Builds a collection list
92
     *
93
     * @access	protected
94
     *
95
     * @return	string		The list of collections ready to output
96
     */
97
    protected function showCollectionList() {
98
99
        $additionalWhere = '';
100
101
        $orderBy = 'tx_dlf_collections.label';
102
103
        // Handle collections set by configuration.
104
        if ($this->conf['collections']) {
105
106
            if (count(explode(',', $this->conf['collections'])) == 1 && empty($this->conf['dont_show_single'])) {
107
108
                $this->showSingleCollection(intval(trim($this->conf['collections'], ' ,')));
109
110
            }
111
112
            $additionalWhere .= ' AND tx_dlf_collections.uid IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')';
113
114
            $orderBy = 'FIELD(tx_dlf_collections.uid, '.$GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']).')';
115
116
        }
117
118
        // Should user-defined collections be shown?
119
        if (empty($this->conf['show_userdefined'])) {
120
121
            $additionalWhere .= ' AND tx_dlf_collections.fe_cruser_id=0';
122
123
        } elseif ($this->conf['show_userdefined'] > 0) {
124
125
            if (!empty($GLOBALS['TSFE']->fe_user->user['uid'])) {
126
127
                $additionalWhere .= ' AND tx_dlf_collections.fe_cruser_id='.intval($GLOBALS['TSFE']->fe_user->user['uid']);
128
129
            } else {
130
131
                $additionalWhere .= ' AND NOT tx_dlf_collections.fe_cruser_id=0';
132
133
            }
134
135
        }
136
137
        // Get collections.
138
        $result = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
139
            'tx_dlf_collections.uid AS 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,COUNT(tx_dlf_documents.uid) AS titles',
140
            'tx_dlf_documents',
141
            'tx_dlf_relations',
142
            'tx_dlf_collections',
143
            'AND tx_dlf_collections.pid='.intval($this->conf['pages']).' AND tx_dlf_documents.partof=0 AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations').$additionalWhere.tx_dlf_helper::whereClause('tx_dlf_documents').tx_dlf_helper::whereClause('tx_dlf_collections'),
144
            'tx_dlf_collections.uid',
145
            $orderBy,
146
            ''
147
        );
148
149
        $count = $GLOBALS['TYPO3_DB']->sql_num_rows($result);
150
151
        $content = '';
152
153
        if ($count == 1 && empty($this->conf['dont_show_single'])) {
154
155
            $resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
156
157
            $this->showSingleCollection(intval($resArray['uid']));
158
159
        } elseif ($count > 0) {
160
161
            // Get number of volumes per collection.
162
            $resultVolumes = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
163
                'tx_dlf_collections.uid AS uid,COUNT(tx_dlf_documents.uid) AS volumes',
164
                'tx_dlf_documents',
165
                'tx_dlf_relations',
166
                'tx_dlf_collections',
167
                'AND tx_dlf_collections.pid='.intval($this->conf['pages']).' AND NOT tx_dlf_documents.uid IN (SELECT DISTINCT tx_dlf_documents.partof FROM tx_dlf_documents WHERE NOT tx_dlf_documents.partof=0'.tx_dlf_helper::whereClause('tx_dlf_documents').') AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations').$additionalWhere.tx_dlf_helper::whereClause('tx_dlf_documents').tx_dlf_helper::whereClause('tx_dlf_collections'),
168
                'tx_dlf_collections.uid',
169
                '',
170
                ''
171
            );
172
173
            $volumes = array ();
174
175
            while ($resArrayVolumes = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultVolumes)) {
176
177
                $volumes[$resArrayVolumes['uid']] = $resArrayVolumes['volumes'];
178
179
            }
180
181
            // Process results.
182
            while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
183
184
                // Generate random but unique array key taking priority into account.
185
                do {
186
187
                    $_key = ($resArray['priority'] * 1000) + mt_rand(0, 1000);
188
189
                } while (!empty($markerArray[$_key]));
190
191
                // Merge plugin variables with new set of values.
192
                $additionalParams = array ('collection' => $resArray['uid']);
193
194
                if (is_array($this->piVars)) {
195
196
                    $piVars = $this->piVars;
197
198
                    unset($piVars['DATA']);
199
200
                    $additionalParams = tx_dlf_helper::array_merge_recursive_overrule($piVars, $additionalParams);
201
202
                }
203
204
                // Build typolink configuration array.
205
                $conf = array (
206
                    'useCacheHash' => 1,
207
                    'parameter' => $GLOBALS['TSFE']->id,
208
                    'additionalParams' => \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl($this->prefixId, $additionalParams, '', TRUE, FALSE)
209
                );
210
211
                // Link collection's title to list view.
212
                $markerArray[$_key]['###TITLE###'] = $this->cObj->typoLink(htmlspecialchars($resArray['label']), $conf);
213
214
                // Add feed link if applicable.
215
                if (!empty($this->conf['targetFeed'])) {
216
217
                    $img = '<img src="'.\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::siteRelPath($this->extKey).'res/icons/txdlffeeds.png" alt="'.$this->pi_getLL('feedAlt', '', TRUE).'" title="'.$this->pi_getLL('feedTitle', '', TRUE).'" />';
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\ExtensionManagementUtility 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...
218
219
                    $markerArray[$_key]['###FEED###'] = $this->pi_linkTP($img, array ($this->prefixId => array ('collection' => $resArray['uid'])), FALSE, $this->conf['targetFeed']);
220
221
                } else {
222
223
                    $markerArray[$_key]['###FEED###'] = '';
224
225
                }
226
227
                // Add thumbnail.
228
                if (!empty($resArray['thumbnail'])) {
229
230
                    $markerArray[$_key]['###THUMBNAIL###'] = '<img alt="" title="'.htmlspecialchars($resArray['label']).'" src="'.$resArray['thumbnail'].'" />';
231
232
                } else {
233
234
                    $markerArray[$_key]['###THUMBNAIL###'] = '';
235
236
                }
237
238
                // Add description.
239
                $markerArray[$_key]['###DESCRIPTION###'] = $this->pi_RTEcssText($resArray['description']);
240
241
                // Build statistic's output.
242
                $labelTitles = $this->pi_getLL(($resArray['titles'] > 1 ? 'titles' : 'title'), '', FALSE);
243
244
                $markerArray[$_key]['###COUNT_TITLES###'] = htmlspecialchars($resArray['titles'].$labelTitles);
245
246
                $labelVolumes = $this->pi_getLL(($volumes[$resArray['uid']] > 1 ? 'volumes' : 'volume'), '', FALSE);
247
248
                $markerArray[$_key]['###COUNT_VOLUMES###'] = htmlspecialchars($volumes[$resArray['uid']].$labelVolumes);
249
250
            }
251
252
            // Randomize sorting?
253
            if (!empty($this->conf['randomize'])) {
254
255
                ksort($markerArray, SORT_NUMERIC);
256
257
                // Don't cache the output.
258
                $this->setCache(FALSE);
259
260
            }
261
262
            $entry = $this->cObj->getSubpart($this->template, '###ENTRY###');
263
264
            foreach ($markerArray as $marker) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $markerArray does not seem to be defined for all execution paths leading up to this point.
Loading history...
265
266
                $content .= $this->cObj->substituteMarkerArray($entry, $marker);
267
268
            }
269
270
            // Hook for getting custom collection hierarchies/subentries (requested by SBB).
271
            foreach ($this->hookObjects as $hookObj) {
272
273
                if (method_exists($hookObj, 'showCollectionList_getCustomCollectionList')) {
274
275
                    $hookObj->showCollectionList_getCustomCollectionList($this, $this->conf['templateFile'], $content, $markerArray);
276
277
                }
278
279
            }
280
281
            return $this->cObj->substituteSubpart($this->template, '###ENTRY###', $content, TRUE);
282
283
        }
284
285
        return $content;
286
287
    }
288
289
    /**
290
     * Builds a collection's list
291
     *
292
     * @access	protected
293
     *
294
     * @param	integer		$id: The collection's UID
295
     *
296
     * @return	void
297
     */
298
    protected function showSingleCollection($id) {
299
300
        // Should user-defined collections be shown?
301
        if (empty($this->conf['show_userdefined'])) {
302
303
            $additionalWhere = ' AND tx_dlf_collections.fe_cruser_id=0';
304
305
        } elseif ($this->conf['show_userdefined'] > 0) {
306
307
            $additionalWhere = ' AND NOT tx_dlf_collections.fe_cruser_id=0';
308
309
        }
310
311
        // Get all documents in collection.
312
        $result = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
313
            'tx_dlf_collections.index_name AS index_name,tx_dlf_collections.label AS collLabel,tx_dlf_collections.description AS collDesc,tx_dlf_collections.thumbnail AS collThumb,tx_dlf_collections.fe_cruser_id AS userid,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',
314
            'tx_dlf_documents',
315
            'tx_dlf_relations',
316
            'tx_dlf_collections',
317
            'AND tx_dlf_collections.uid='.intval($id).' AND tx_dlf_collections.pid='.intval($this->conf['pages']).' AND tx_dlf_relations.ident='.$GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations').$additionalWhere.tx_dlf_helper::whereClause('tx_dlf_documents').tx_dlf_helper::whereClause('tx_dlf_collections'),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $additionalWhere does not seem to be defined for all execution paths leading up to this point.
Loading history...
318
            '',
319
            'tx_dlf_documents.title_sorting ASC',
320
            ''
321
        );
322
323
        $toplevel = array ();
324
325
        $subparts = array ();
326
327
        $listMetadata = array ();
328
329
        // Process results.
330
        while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
331
332
            if (empty($listMetadata)) {
333
334
                $listMetadata = array (
335
                    'label' => htmlspecialchars($resArray['collLabel']),
336
                    'description' => $this->pi_RTEcssText($resArray['collDesc']),
337
                    'thumbnail' => htmlspecialchars($resArray['collThumb']),
338
                    'options' => array (
339
                        'source' => 'collection',
340
                        'select' => $id,
341
                        'userid' => $resArray['userid'],
342
                        'params' => array ('fq' => array ('collection_faceting:("'.$resArray['index_name'].'")')),
343
                        'core' => '',
344
                        'pid' => $this->conf['pages'],
345
                        'order' => 'title',
346
                        'order.asc' => TRUE
347
                    )
348
                );
349
350
            }
351
352
            // Split toplevel documents from volumes.
353
            if ($resArray['partof'] == 0) {
354
355
                // Prepare document's metadata for sorting.
356
                $sorting = unserialize($resArray['metadata_sorting']);
357
358
                if (!empty($sorting['type']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['type'])) {
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\MathUtility 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...
359
360
                    $sorting['type'] = tx_dlf_helper::getIndexName($sorting['type'], 'tx_dlf_structures', $this->conf['pages']);
361
362
                }
363
364
                if (!empty($sorting['owner']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['owner'])) {
365
366
                    $sorting['owner'] = tx_dlf_helper::getIndexName($sorting['owner'], 'tx_dlf_libraries', $this->conf['pages']);
367
368
                }
369
370
                if (!empty($sorting['collection']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($sorting['collection'])) {
371
372
                    $sorting['collection'] = tx_dlf_helper::getIndexName($sorting['collection'], 'tx_dlf_collections', $this->conf['pages']);
373
374
                }
375
376
                $toplevel[$resArray['uid']] = array (
377
                    'u' => $resArray['uid'],
378
                    'h' => '',
379
                    's' => $sorting,
380
                    'p' => array ()
381
                );
382
383
            } else {
384
385
                $subparts[$resArray['partof']][$resArray['volume_sorting']] = $resArray['uid'];
386
387
            }
388
389
        }
390
391
        // Add volumes to the corresponding toplevel documents.
392
        foreach ($subparts as $partof => $parts) {
393
394
            if (!empty($toplevel[$partof])) {
395
396
                ksort($parts);
397
398
                foreach ($parts as $part) {
399
400
                    $toplevel[$partof]['p'][] = array ('u' => $part);
401
402
                }
403
404
            }
405
406
        }
407
408
        // Save list of documents.
409
        $list = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_dlf_list');
410
411
        $list->reset();
412
413
        $list->add(array_values($toplevel));
414
415
        $list->metadata = $listMetadata;
416
417
        $list->save();
418
419
        // Clean output buffer.
420
        \TYPO3\CMS\Core\Utility\GeneralUtility::cleanOutputBuffers();
421
422
        // Send headers.
423
        header('Location: '.\TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl($this->cObj->typoLink_URL(array ('parameter' => $this->conf['targetPid']))));
424
425
        // Flush output buffer and end script processing.
426
        ob_end_flush();
427
428
        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...
429
430
    }
431
432
}
433