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 (#734)
by Alexander
03:26
created

MetadataController::parseTS()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 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\Document;
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\IiifManifest;
17
use TYPO3\CMS\Core\Database\Connection;
18
use TYPO3\CMS\Core\Database\ConnectionPool;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
use TYPO3\CMS\Extbase\Configuration\ConfigurationManager;
21
use Ubl\Iiif\Context\IRI;
22
23
class MetadataController extends AbstractController
24
{
25
    public $prefixId = 'tx_dlf';
26
27
    /**
28
     * @return string|void
29
     */
30
    public function mainAction()
31
    {
32
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
33
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
34
35
        $this->cObj = $this->configurationManager->getContentObject();
0 ignored issues
show
Bug Best Practice introduced by
The property cObj does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
36
37
        // Load current document.
38
        $this->loadDocument($requestData);
39
        if ($this->doc === null) {
40
            // Quit without doing anything if required variables are not set.
41
            return '';
42
        } else {
43
            // Set default values if not set.
44
            if (!isset($this->settings['rootline'])) {
45
                $this->settings['rootline'] = 0;
46
            }
47
            if (!isset($this->settings['originalIiifMetadata'])) {
48
                $this->settings['originalIiifMetadata'] = 0;
49
            }
50
            if (!isset($this->settings['displayIiifDescription'])) {
51
                $this->settings['displayIiifDescription'] = 1;
52
            }
53
            if (!isset($this->settings['displayIiifRights'])) {
54
                $this->settings['displayIiifRights'] = 1;
55
            }
56
            if (!isset($this->settings['displayIiifLinks'])) {
57
                $this->settings['displayIiifLinks'] = 1;
58
            }
59
        }
60
        $useOriginalIiifManifestMetadata = $this->settings['originalIiifMetadata'] == 1 && $this->doc instanceof IiifManifest;
61
        $metadata = [];
62
        if ($this->settings['rootline'] < 2) {
63
            // Get current structure's @ID.
64
            $ids = [];
65
            if (!empty($this->doc->physicalStructure[$requestData['page']]) && !empty($this->doc->smLinks['p2l'][$this->doc->physicalStructure[$requestData['page']]])) {
66
                foreach ($this->doc->smLinks['p2l'][$this->doc->physicalStructure[$requestData['page']]] as $logId) {
67
                    $count = $this->doc->getStructureDepth($logId);
68
                    $ids[$count][] = $logId;
69
                }
70
            }
71
            ksort($ids);
72
            reset($ids);
73
            // Check if we should display all metadata up to the root.
74
            if ($this->settings['rootline'] == 1) {
75
                foreach ($ids as $id) {
76
                    foreach ($id as $sid) {
77
                        if ($useOriginalIiifManifestMetadata) {
78
                            $data = $this->doc->getManifestMetadata($sid, $this->settings['pages']);
79
                        } else {
80
                            $data = $this->doc->getMetadata($sid, $this->settings['pages']);
81
                        }
82
                        if (!empty($data)) {
83
                            $data['_id'] = $sid;
84
                            $metadata[] = $data;
85
                        }
86
                    }
87
                }
88
            } else {
89
                $id = array_pop($ids);
90
                if (is_array($id)) {
91
                    foreach ($id as $sid) {
92
                        if ($useOriginalIiifManifestMetadata) {
93
                            $data = $this->doc->getManifestMetadata($sid, $this->settings['pages']);
94
                        } else {
95
                            $data = $this->doc->getMetadata($sid, $this->settings['pages']);
96
                        }
97
                        if (!empty($data)) {
98
                            $data['_id'] = $sid;
99
                            $metadata[] = $data;
100
                        }
101
                    }
102
                }
103
            }
104
        }
105
        // Get titledata?
106
        if (empty($metadata) || ($this->settings['rootline'] == 1 && $metadata[0]['_id'] != $this->doc->toplevelId)) {
107
            $data = $useOriginalIiifManifestMetadata ? $this->doc->getManifestMetadata($this->doc->toplevelId, $this->settings['pages']) : $this->doc->getTitleData($this->settings['pages']);
0 ignored issues
show
Bug introduced by
The method getManifestMetadata() does not exist on Kitodo\Dlf\Common\Document. It seems like you code against a sub-type of Kitodo\Dlf\Common\Document such as Kitodo\Dlf\Common\IiifManifest. ( Ignorable by Annotation )

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

107
            $data = $useOriginalIiifManifestMetadata ? $this->doc->/** @scrutinizer ignore-call */ getManifestMetadata($this->doc->toplevelId, $this->settings['pages']) : $this->doc->getTitleData($this->settings['pages']);
Loading history...
108
            $data['_id'] = $this->doc->toplevelId;
109
            array_unshift($metadata, $data);
110
        }
111
        if (empty($metadata)) {
112
            $this->logger->warning('No metadata found for document with UID ' . $this->doc->uid);
1 ignored issue
show
Bug introduced by
The method warning() does not exist on null. ( Ignorable by Annotation )

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

112
            $this->logger->/** @scrutinizer ignore-call */ 
113
                           warning('No metadata found for document with UID ' . $this->doc->uid);

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...
113
            return '';
114
        }
115
        ksort($metadata);
116
        // Get hook objects.
117
        $this->hookObjects = Helper::getHookObjects($this->scriptRelPath);
0 ignored issues
show
Bug Best Practice introduced by
The property hookObjects does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug Best Practice introduced by
The property scriptRelPath does not exist on Kitodo\Dlf\Controller\MetadataController. Did you maybe forget to declare it?
Loading history...
118
        // Hook for getting a customized title bar (requested by SBB).
119
        foreach ($this->hookObjects as $hookObj) {
120
            if (method_exists($hookObj, 'main_customizeTitleBarGetCustomTemplate')) {
121
                $hookObj->main_customizeTitleBarGetCustomTemplate($this, $metadata);
122
            }
123
        }
124
        $this->printMetadata($metadata, $useOriginalIiifManifestMetadata);
125
    }
126
127
    /**
128
     * Prepares the metadata array for output
129
     *
130
     * @access protected
131
     *
132
     * @param array $metadataArray: The metadata array
133
     * @param bool $useOriginalIiifManifestMetadata: Output IIIF metadata as simple key/value pairs?
134
     *
135
     * @return string The metadata array ready for output
136
     */
137
    protected function printMetadata(array $metadataArray, $useOriginalIiifManifestMetadata = false)
138
    {
139
        // Save original data array.
140
        $cObjData = $this->cObj->data;
141
        // Get list of metadata to show.
142
        $metaList = [];
143
        if ($useOriginalIiifManifestMetadata) {
144
            if ($this->settings['iiifMetadataWrap']) {
145
                $iiifwrap = $this->parseTS($this->settings['iiifMetadataWrap']);
146
            } else {
147
                $iiifwrap['key.']['wrap'] = '<dt>|</dt>';
148
                $iiifwrap['value.']['required'] = 1;
149
                $iiifwrap['value.']['wrap'] = '<dd>|</dd>';
150
            }
151
            $iiifLink = [];
152
            $iiifLink['key.']['wrap'] = '<dt>|</dt>';
153
            $iiifLink['value.']['required'] = 1;
154
            $iiifLink['value.']['setContentToCurrent'] = 1;
155
            $iiifLink['value.']['typolink.']['parameter.']['current'] = 1;
156
            $iiifLink['value.']['typolink.']['forceAbsoluteUrl'] = !empty($this->settings['forceAbsoluteUrl']) ? 1 : 0;
157
            $iiifLink['value.']['typolink.']['forceAbsoluteUrl.']['scheme'] = !empty($this->settings['forceAbsoluteUrl']) && !empty($this->settings['forceAbsoluteUrlHttps']) ? 'https' : 'http';
158
            $iiifLink['value.']['wrap'] = '<dd>|</dd>';
159
            foreach ($metadataArray as $metadata) {
160
                foreach ($metadata as $key => $group) {
161
                    $markerArray['METADATA'] = '<span class="tx-dlf-metadata-group">' . $this->pi_getLL($key) . '</span>';
162
                    // Reset content object's data array.
163
                    $this->cObj->data = $cObjData;
164
                    if (!is_array($group)) {
165
                        if ($key == '_id') {
166
                            continue;
167
                        }
168
                        $this->cObj->data[$key] = $group;
169
                        if (
170
                            IRI::isAbsoluteIri($this->cObj->data[$key])
171
                            && (($scheme = (new IRI($this->cObj->data[$key]))->getScheme()) == 'http' || $scheme == 'https')
172
                        ) {
173
                            $field = $this->cObj->stdWrap('', $iiifLink['key.']);
174
                            $field .= $this->cObj->stdWrap($this->cObj->data[$key], $iiifLink['value.']);
175
                        } else {
176
                            $field = $this->cObj->stdWrap('', $iiifwrap['key.']);
177
                            $field .= $this->cObj->stdWrap($this->cObj->data[$key], $iiifwrap['value.']);
178
                        }
179
                        $markerArray['METADATA'] .= $this->cObj->stdWrap($field, $iiifwrap['all.']);
180
                    } else {
181
                        // Load all the metadata values into the content object's data array.
182
                        foreach ($group as $label => $value) {
183
                            if ($label == '_id') {
184
                                continue;
185
                            }
186
                            if (is_array($value)) {
187
                                $this->cObj->data[$label] = implode($this->settings['separator'], $value);
188
                            } else {
189
                                $this->cObj->data[$label] = $value;
190
                            }
191
                            if (IRI::isAbsoluteIri($this->cObj->data[$label]) && (($scheme = (new IRI($this->cObj->data[$label]))->getScheme()) == 'http' || $scheme == 'https')) {
192
                                $nolabel = $this->cObj->data[$label] == $label;
193
                                $field = $this->cObj->stdWrap($nolabel ? '' : htmlspecialchars($label), $iiifLink['key.']);
194
                                $field .= $this->cObj->stdWrap($this->cObj->data[$label], $iiifLink['value.']);
195
                            } else {
196
                                $field = $this->cObj->stdWrap(htmlspecialchars($label), $iiifwrap['key.']);
197
                                $field .= $this->cObj->stdWrap($this->cObj->data[$label], $iiifwrap['value.']);
198
                            }
199
                            $markerArray['METADATA'] .= $this->cObj->stdWrap($field, $iiifwrap['all.']);
200
                        }
201
                    }
202
                }
203
            }
204
        } else {
205
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
206
                ->getQueryBuilderForTable('tx_dlf_metadata');
207
            $result = $queryBuilder
208
                ->select(
209
                    'tx_dlf_metadata.index_name AS index_name',
210
                    'tx_dlf_metadata.is_listed AS is_listed',
211
                    'tx_dlf_metadata.wrap AS wrap',
212
                    'tx_dlf_metadata.sys_language_uid AS sys_language_uid'
213
                )
214
                ->from('tx_dlf_metadata')
215
                ->where(
216
                    $queryBuilder->expr()->andX(
217
                        $queryBuilder->expr()->orX(
218
                            $queryBuilder->expr()->in('tx_dlf_metadata.sys_language_uid', [-1, 0]),
219
                            $queryBuilder->expr()->eq('tx_dlf_metadata.sys_language_uid', $GLOBALS['TSFE']->sys_language_uid)
220
                        ),
221
                        $queryBuilder->expr()->eq('tx_dlf_metadata.l18n_parent', 0)
222
                    ),
223
                    $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($this->settings['pages']))
224
                )
225
                ->orderBy('tx_dlf_metadata.sorting')
226
                ->execute();
227
            while ($resArray = $result->fetch()) {
228
                if (is_array($resArray) && $resArray['sys_language_uid'] != $GLOBALS['TSFE']->sys_language_content && $GLOBALS['TSFE']->sys_language_contentOL) {
229
                    $resArray = $GLOBALS['TSFE']->sys_page->getRecordOverlay('tx_dlf_metadata', $resArray, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
230
                }
231
                if ($resArray) {
232
                    if ($this->settings['showFull'] || $resArray['is_listed']) {
233
                        $metaList[$resArray['index_name']] = [
234
                            'wrap' => $resArray['wrap'],
235
                            'label' => Helper::translate($resArray['index_name'], 'tx_dlf_metadata', $this->settings['pages'])
236
                        ];
237
                    }
238
                }
239
            }
240
            // Get list of collections to show.
241
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
242
                ->getQueryBuilderForTable('tx_dlf_collections');
243
            $collList = [];
244
            $result = $queryBuilder
245
                ->select('tx_dlf_collections.index_name AS index_name')
246
                ->from('tx_dlf_collections')
247
                ->where(
248
                    $queryBuilder->expr()->eq('tx_dlf_collections.pid', intval($this->settings['pages']))
249
                )
250
                ->execute();
251
            while ($resArray = $result->fetch()) {
252
                $collList[] = $resArray['index_name'];
253
            }
254
            // Parse the metadata arrays.
255
            foreach ($metadataArray as $metadata) {
256
                $markerArray['METADATA'] = '';
257
                // Reset content object's data array.
258
                $this->cObj->data = $cObjData;
259
                // Load all the metadata values into the content object's data array.
260
                foreach ($metadata as $index_name => $value) {
261
                    if (is_array($value)) {
262
                        $this->cObj->data[$index_name] = implode($this->settings['separator'], $value);
263
                    } else {
264
                        $this->cObj->data[$index_name] = $value;
265
                    }
266
                }
267
                // Process each metadate.
268
                foreach ($metaList as $index_name => $metaConf) {
269
                    $parsedValue = '';
270
                    $fieldwrap = $this->parseTS($metaConf['wrap']);
271
                    do {
272
                        $value = @array_shift($metadata[$index_name]);
273
                        if ($index_name == 'title') {
274
                            // Get title of parent document if needed.
275
                            if (empty($value) && $this->settings['getTitle'] && $this->doc->parentId) {
276
                                $superiorTitle = Document::getTitle($this->doc->parentId, true);
277
                                if (!empty($superiorTitle)) {
278
                                    $value = '[' . $superiorTitle . ']';
279
                                }
280
                            }
281
                            if (!empty($value)) {
282
                                $value = htmlspecialchars($value);
283
                                // Link title to pageview.
284
                                if ($this->settings['linkTitle'] && $metadata['_id']) {
285
                                    $details = $this->doc->getLogicalStructure($metadata['_id']);
286
                                    $uri = $this->uriBuilder->reset()
287
                                        ->setArguments([
288
                                            $this->prefixId => [
289
                                                'id' => $this->doc->uid,
290
                                                'page' => (!empty($details['points']) ? intval($details['points']) : 1)
291
                                            ]
292
                                        ])
293
                                        ->setTargetPageUid($this->settings['targetPid'])
294
                                        ->build();
295
                                    $value = '<a href="' . $uri . '">' . $value . '</a>';
296
                                }
297
                            }
298
                        } elseif ($index_name == 'owner' && !empty($value)) {
299
                            // Translate name of holding library.
300
                            $value = htmlspecialchars(Helper::translate($value, 'tx_dlf_libraries', $this->settings['pages']));
301
                        } elseif ($index_name == 'type' && !empty($value)) {
302
                            // Translate document type.
303
                            $value = htmlspecialchars(Helper::translate($value, 'tx_dlf_structures', $this->settings['pages']));
304
                        } elseif ($index_name == 'collection' && !empty($value)) {
305
                            // Check if collections isn't hidden.
306
                            if (in_array($value, $collList)) {
307
                                // Translate collection.
308
                                $value = htmlspecialchars(Helper::translate($value, 'tx_dlf_collections', $this->settings['pages']));
309
                            } else {
310
                                $value = '';
311
                            }
312
                        } elseif ($index_name == 'language' && !empty($value)) {
313
                            // Translate ISO 639 language code.
314
                            $value = htmlspecialchars(Helper::getLanguageName($value));
315
                        } elseif (!empty($value)) {
316
                            // Sanitize value for output.
317
                            $value = htmlspecialchars($value);
318
                        }
319
                        // Hook for getting a customized value (requested by SBB).
320
                        foreach ($this->hookObjects as $hookObj) {
321
                            if (method_exists($hookObj, 'printMetadata_customizeMetadata')) {
322
                                $hookObj->printMetadata_customizeMetadata($value);
323
                            }
324
                        }
325
                        // $value might be empty for aggregation metadata fields including other "hidden" fields.
326
                        $value = $this->cObj->stdWrap($value, $fieldwrap['value.']);
327
                        if (!empty($value)) {
328
                            $parsedValue .= $value;
329
                        }
330
                    } while (is_array($metadata[$index_name]) && count($metadata[$index_name]) > 0);
331
332
                    if (!empty($parsedValue)) {
333
                        $field = $this->cObj->stdWrap(htmlspecialchars($metaConf['label']), $fieldwrap['key.']);
334
                        $field .= $parsedValue;
335
                        $markerArray['METADATA'] .= $this->cObj->stdWrap($field, $fieldwrap['all.']);
336
                    }
337
                }
338
            }
339
        }
340
        $this->view->assign('metadata', $markerArray['METADATA']);
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...
341
    }
342
343
    // TODO: Needs to be placed in an abstract class (like before in AbstractPlugin)
344
    /**
345
     * Parses a string into a Typoscript array
346
     *
347
     * @access protected
348
     *
349
     * @param string $string: The string to parse
350
     *
351
     * @return array The resulting typoscript array
352
     */
353
    protected function parseTS($string = '')
354
    {
355
        $parser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
356
        $parser->parse($string);
357
        return $parser->setup;
358
    }
359
360
    protected function pi_getLL($label)
361
    {
362
        return $GLOBALS['TSFE']->sL('LLL:EXT:dlf/Resources/Private/Language/Metadata.xml:' . $label);
363
    }
364
365
}
366