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
Push — master ( 5ba47e...6fff5d )
by
unknown
03:29
created

MetsDocument::ensureHasFulltextIsSet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 5
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
namespace Kitodo\Dlf\Common;
14
15
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
16
use TYPO3\CMS\Core\Database\ConnectionPool;
17
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
18
use TYPO3\CMS\Core\Log\LogManager;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
use Ubl\Iiif\Tools\IiifHelper;
21
use Ubl\Iiif\Services\AbstractImageService;
22
23
/**
24
 * MetsDocument class for the 'dlf' extension.
25
 *
26
 * @author Sebastian Meyer <[email protected]>
27
 * @author Henrik Lochmann <[email protected]>
28
 * @package TYPO3
29
 * @subpackage dlf
30
 * @access public
31
 * @property int $cPid This holds the PID for the configuration
32
 * @property-read array $mdSec Associative array of METS metadata sections indexed by their IDs.
33
 * @property-read array $dmdSec Subset of `$mdSec` storing only the dmdSec entries; kept for compatibility.
34
 * @property-read array $fileGrps This holds the file ID -> USE concordance
35
 * @property-read bool $hasFulltext Are there any fulltext files available?
36
 * @property-read array $metadataArray This holds the documents' parsed metadata array
37
 * @property-read \SimpleXMLElement $mets This holds the XML file's METS part as \SimpleXMLElement object
38
 * @property-read int $numPages The holds the total number of pages
39
 * @property-read int $parentId This holds the UID of the parent document or zero if not multi-volumed
40
 * @property-read array $physicalStructure This holds the physical structure
41
 * @property-read array $physicalStructureInfo This holds the physical structure metadata
42
 * @property-read int $pid This holds the PID of the document or zero if not in database
43
 * @property-read bool $ready Is the document instantiated successfully?
44
 * @property-read string $recordId The METS file's / IIIF manifest's record identifier
45
 * @property-read int $rootId This holds the UID of the root document or zero if not multi-volumed
46
 * @property-read array $smLinks This holds the smLinks between logical and physical structMap
47
 * @property-read array $tableOfContents This holds the logical structure
48
 * @property-read string $thumbnail This holds the document's thumbnail location
49
 * @property-read string $toplevelId This holds the toplevel structure's @ID (METS) or the manifest's @id (IIIF)
50
 * @property-read string $parentHref URL of the parent document (determined via mptr element), or empty string if none is available
51
 */
52
final class MetsDocument extends AbstractDocument
53
{
54
    /**
55
     * Subsections / tags that may occur within `<mets:amdSec>`.
56
     *
57
     * @link https://www.loc.gov/standards/mets/docs/mets.v1-9.html#amdSec
58
     * @link https://www.loc.gov/standards/mets/docs/mets.v1-9.html#mdSecType
59
     *
60
     * @var string[]
61
     */
62
    protected const ALLOWED_AMD_SEC = ['techMD', 'rightsMD', 'sourceMD', 'digiprovMD'];
63
64
    /**
65
     * This holds the whole XML file as string for serialization purposes
66
     * @see __sleep() / __wakeup()
67
     *
68
     * @var string
69
     * @access protected
70
     */
71
    protected $asXML = '';
72
73
    /**
74
     * This maps the ID of each amdSec to the IDs of its children (techMD etc.).
75
     * When an ADMID references an amdSec instead of techMD etc., this is used to iterate the child elements.
76
     *
77
     * @var array
78
     * @access protected
79
     */
80
    protected $amdSecChildIds = [];
81
82
    /**
83
     * Associative array of METS metadata sections indexed by their IDs.
84
     *
85
     * @var array
86
     * @access protected
87
     */
88
    protected $mdSec = [];
89
90
    /**
91
     * Are the METS file's metadata sections loaded?
92
     * @see MetsDocument::$mdSec
93
     *
94
     * @var bool
95
     * @access protected
96
     */
97
    protected $mdSecLoaded = false;
98
99
    /**
100
     * Subset of $mdSec storing only the dmdSec entries; kept for compatibility.
101
     *
102
     * @var array
103
     * @access protected
104
     */
105
    protected $dmdSec = [];
106
107
    /**
108
     * The extension key
109
     *
110
     * @var	string
111
     * @access public
112
     */
113
    public static $extKey = 'dlf';
114
115
    /**
116
     * This holds the file ID -> USE concordance
117
     * @see _getFileGrps()
118
     *
119
     * @var array
120
     * @access protected
121
     */
122
    protected $fileGrps = [];
123
124
    /**
125
     * Are the image file groups loaded?
126
     * @see $fileGrps
127
     *
128
     * @var bool
129
     * @access protected
130
     */
131
    protected $fileGrpsLoaded = false;
132
133
    /**
134
     * This holds the XML file's METS part as \SimpleXMLElement object
135
     *
136
     * @var \SimpleXMLElement
137
     * @access protected
138
     */
139
    protected $mets;
140
141
    /**
142
     * This holds the whole XML file as \SimpleXMLElement object
143
     *
144
     * @var \SimpleXMLElement
145
     * @access protected
146
     */
147
    protected $xml;
148
149
    /**
150
     * URL of the parent document (determined via mptr element),
151
     * or empty string if none is available
152
     *
153
     * @var string|null
154
     * @access protected
155
     */
156
    protected $parentHref;
157
158
    /**
159
     * This adds metadata from METS structural map to metadata array.
160
     *
161
     * @access	public
162
     *
163
     * @param	array	&$metadata: The metadata array to extend
164
     * @param	string	$id: The "@ID" attribute of the logical structure node
165
     *
166
     * @return  void
167
     */
168
    public function addMetadataFromMets(&$metadata, $id)
169
    {
170
        $details = $this->getLogicalStructure($id);
171
        if (!empty($details)) {
172
            $metadata['mets_order'][0] = $details['order'];
173
            $metadata['mets_label'][0] = $details['label'];
174
            $metadata['mets_orderlabel'][0] = $details['orderlabel'];
175
        }
176
    }
177
178
    /**
179
     * @see AbstractDocument::establishRecordId()
180
     */
181
    protected function establishRecordId($pid)
182
    {
183
        // Check for METS object @ID.
184
        if (!empty($this->mets['OBJID'])) {
185
            $this->recordId = (string) $this->mets['OBJID'];
186
        }
187
        // Get hook objects.
188
        $hookObjects = Helper::getHookObjects('Classes/Common/MetsDocument.php');
189
        // Apply hooks.
190
        foreach ($hookObjects as $hookObj) {
191
            if (method_exists($hookObj, 'construct_postProcessRecordId')) {
192
                $hookObj->construct_postProcessRecordId($this->xml, $this->recordId);
193
            }
194
        }
195
    }
196
197
    /**
198
     * @see AbstractDocument::getDownloadLocation()
199
     */
200
    public function getDownloadLocation($id)
201
    {
202
        $file = $this->getFileInfo($id);
203
        if ($file['mimeType'] === 'application/vnd.kitodo.iiif') {
204
            $file['location'] = (strrpos($file['location'], 'info.json') === strlen($file['location']) - 9) ? $file['location'] : (strrpos($file['location'], '/') === strlen($file['location']) ? $file['location'] . 'info.json' : $file['location'] . '/info.json');
205
            $conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
206
            IiifHelper::setUrlReader(IiifUrlReader::getInstance());
207
            IiifHelper::setMaxThumbnailHeight($conf['iiifThumbnailHeight']);
208
            IiifHelper::setMaxThumbnailWidth($conf['iiifThumbnailWidth']);
209
            $service = IiifHelper::loadIiifResource($file['location']);
210
            if ($service !== null && $service instanceof AbstractImageService) {
211
                return $service->getImageUrl();
212
            }
213
        } elseif ($file['mimeType'] === 'application/vnd.netfpx') {
214
            $baseURL = $file['location'] . (strpos($file['location'], '?') === false ? '?' : '');
215
            // TODO CVT is an optional IIP server capability; in theory, capabilities should be determined in the object request with '&obj=IIP-server'
216
            return $baseURL . '&CVT=jpeg';
217
        }
218
        return $file['location'];
219
    }
220
221
    /**
222
     * {@inheritDoc}
223
     * @see AbstractDocument::getFileInfo()
224
     */
225
    public function getFileInfo($id)
226
    {
227
        $this->_getFileGrps();
228
229
        if (isset($this->fileInfos[$id]) && empty($this->fileInfos[$id]['location'])) {
230
            $this->fileInfos[$id]['location'] = $this->getFileLocation($id);
0 ignored issues
show
Bug introduced by
The property fileInfos is declared read-only in Kitodo\Dlf\Common\AbstractDocument.
Loading history...
231
        }
232
233
        if (isset($this->fileInfos[$id]) && empty($this->fileInfos[$id]['mimeType'])) {
234
            $this->fileInfos[$id]['mimeType'] = $this->getFileMimeType($id);
235
        }
236
237
        return $this->fileInfos[$id];
238
    }
239
240
    /**
241
     * @see AbstractDocument::getFileLocation()
242
     */
243
    public function getFileLocation($id)
244
    {
245
        $location = $this->mets->xpath('./mets:fileSec/mets:fileGrp/mets:file[@ID="' . $id . '"]/mets:FLocat[@LOCTYPE="URL"]');
246
        if (
247
            !empty($id)
248
            && !empty($location)
249
        ) {
250
            return (string) $location[0]->attributes('http://www.w3.org/1999/xlink')->href;
251
        } else {
252
            $this->logger->warning('There is no file node with @ID "' . $id . '"');
253
            return '';
254
        }
255
    }
256
257
    /**
258
     * @see AbstractDocument::getFileMimeType()
259
     */
260
    public function getFileMimeType($id)
261
    {
262
        $mimetype = $this->mets->xpath('./mets:fileSec/mets:fileGrp/mets:file[@ID="' . $id . '"]/@MIMETYPE');
263
        if (
264
            !empty($id)
265
            && !empty($mimetype)
266
        ) {
267
            return (string) $mimetype[0];
268
        } else {
269
            $this->logger->warning('There is no file node with @ID "' . $id . '" or no MIME type specified');
270
            return '';
271
        }
272
    }
273
274
    /**
275
     * @see AbstractDocument::getLogicalStructure()
276
     */
277
    public function getLogicalStructure($id, $recursive = false)
278
    {
279
        $details = [];
280
        // Is the requested logical unit already loaded?
281
        if (
282
            !$recursive
283
            && !empty($this->logicalUnits[$id])
284
        ) {
285
            // Yes. Return it.
286
            return $this->logicalUnits[$id];
287
        } elseif (!empty($id)) {
288
            // Get specified logical unit.
289
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]');
290
        } else {
291
            // Get all logical units at top level.
292
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]/mets:div');
293
        }
294
        if (!empty($divs)) {
295
            if (!$recursive) {
296
                // Get the details for the first xpath hit.
297
                $details = $this->getLogicalStructureInfo($divs[0]);
298
            } else {
299
                // Walk the logical structure recursively and fill the whole table of contents.
300
                foreach ($divs as $div) {
301
                    $this->tableOfContents[] = $this->getLogicalStructureInfo($div, $recursive);
302
                }
303
            }
304
        }
305
        return $details;
306
    }
307
308
    /**
309
     * This gets details about a logical structure element
310
     *
311
     * @access protected
312
     *
313
     * @param \SimpleXMLElement $structure: The logical structure node
314
     * @param bool $recursive: Whether to include the child elements
315
     *
316
     * @return array Array of the element's id, label, type and physical page indexes/mptr link
317
     */
318
    protected function getLogicalStructureInfo(\SimpleXMLElement $structure, $recursive = false)
319
    {
320
        // Get attributes.
321
        foreach ($structure->attributes() as $attribute => $value) {
322
            $attributes[$attribute] = (string) $value;
323
        }
324
        // Load plugin configuration.
325
        $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
326
        // Extract identity information.
327
        $details = [];
328
        $details['id'] = $attributes['ID'];
329
        $details['dmdId'] = (isset($attributes['DMDID']) ? $attributes['DMDID'] : '');
330
        $details['admId'] = (isset($attributes['ADMID']) ? $attributes['ADMID'] : '');
331
        $details['order'] = (isset($attributes['ORDER']) ? $attributes['ORDER'] : '');
332
        $details['label'] = (isset($attributes['LABEL']) ? $attributes['LABEL'] : '');
333
        $details['orderlabel'] = (isset($attributes['ORDERLABEL']) ? $attributes['ORDERLABEL'] : '');
334
        $details['contentIds'] = (isset($attributes['CONTENTIDS']) ? $attributes['CONTENTIDS'] : '');
335
        $details['volume'] = '';
336
        // Set volume and year information only if no label is set and this is the toplevel structure element.
337
        if (
338
            empty($details['label'])
339
            && empty($details['orderlabel'])
340
        ) {
341
            $metadata = $this->getMetadata($details['id']);
342
            if (!empty($metadata['volume'][0])) {
343
                $details['volume'] = $metadata['volume'][0];
344
            }
345
            if (!empty($metadata['year'][0])) {
346
                $details['year'] = $metadata['year'][0];
347
            }
348
        }
349
        $details['pagination'] = '';
350
        $details['type'] = $attributes['TYPE'];
351
        // add description for 3D objects
352
        if ($details['type'] == 'object') {
353
            $metadata = $this->getMetadata($details['id']);
354
            $details['description'] = $metadata['description'][0] ?? '';
355
        }
356
        $details['thumbnailId'] = '';
357
        // Load smLinks.
358
        $this->_getSmLinks();
359
        // Load physical structure.
360
        $this->_getPhysicalStructure();
361
        // Get the physical page or external file this structure element is pointing at.
362
        $details['points'] = '';
363
        // Is there a mptr node?
364
        if (count($structure->children('http://www.loc.gov/METS/')->mptr)) {
365
            // Yes. Get the file reference.
366
            $details['points'] = (string) $structure->children('http://www.loc.gov/METS/')->mptr[0]->attributes('http://www.w3.org/1999/xlink')->href;
367
        } elseif (
368
            !empty($this->physicalStructure)
369
            && array_key_exists($details['id'], $this->smLinks['l2p'])
370
        ) {
371
            // Link logical structure to the first corresponding physical page/track.
372
            $details['points'] = max(intval(array_search($this->smLinks['l2p'][$details['id']][0], $this->physicalStructure, true)), 1);
373
            $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
374
            while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
375
                if (!empty($this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['files'][$fileGrpThumb])) {
376
                    $details['thumbnailId'] = $this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['files'][$fileGrpThumb];
377
                    break;
378
                }
379
            }
380
            // Get page/track number of the first page/track related to this structure element.
381
            $details['pagination'] = $this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['orderlabel'];
382
        } elseif ($details['id'] == $this->_getToplevelId()) {
383
            // Point to self if this is the toplevel structure.
384
            $details['points'] = 1;
385
            $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
386
            while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
387
                if (
388
                    !empty($this->physicalStructure)
389
                    && !empty($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb])
390
                ) {
391
                    $details['thumbnailId'] = $this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb];
392
                    break;
393
                }
394
            }
395
        }
396
        // Get the files this structure element is pointing at.
397
        $details['files'] = [];
398
        $fileUse = $this->_getFileGrps();
399
        // Get the file representations from fileSec node.
400
        foreach ($structure->children('http://www.loc.gov/METS/')->fptr as $fptr) {
401
            // Check if file has valid @USE attribute.
402
            if (!empty($fileUse[(string) $fptr->attributes()->FILEID])) {
0 ignored issues
show
Bug introduced by
The method attributes() 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

402
            if (!empty($fileUse[(string) $fptr->/** @scrutinizer ignore-call */ attributes()->FILEID])) {

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...
403
                $details['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
404
            }
405
        }
406
        // Keep for later usage.
407
        $this->logicalUnits[$details['id']] = $details;
408
        // Walk the structure recursively? And are there any children of the current element?
409
        if (
410
            $recursive
411
            && count($structure->children('http://www.loc.gov/METS/')->div)
412
        ) {
413
            $details['children'] = [];
414
            foreach ($structure->children('http://www.loc.gov/METS/')->div as $child) {
415
                // Repeat for all children.
416
                $details['children'][] = $this->getLogicalStructureInfo($child, true);
0 ignored issues
show
Bug introduced by
It seems like $child can also be of type null; however, parameter $structure of Kitodo\Dlf\Common\MetsDo...tLogicalStructureInfo() does only seem to accept SimpleXMLElement, 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

416
                $details['children'][] = $this->getLogicalStructureInfo(/** @scrutinizer ignore-type */ $child, true);
Loading history...
417
            }
418
        }
419
        return $details;
420
    }
421
422
    /**
423
     * @see AbstractDocument::getMetadata()
424
     */
425
    public function getMetadata($id, $cPid = 0)
426
    {
427
        // Make sure $cPid is a non-negative integer.
428
        $cPid = max(intval($cPid), 0);
429
        // If $cPid is not given, try to get it elsewhere.
430
        if (
431
            !$cPid
432
            && ($this->cPid || $this->pid)
433
        ) {
434
            // Retain current PID.
435
            $cPid = ($this->cPid ? $this->cPid : $this->pid);
436
        } elseif (!$cPid) {
437
            $this->logger->warning('Invalid PID ' . $cPid . ' for metadata definitions');
438
            return [];
439
        }
440
        // Get metadata from parsed metadata array if available.
441
        if (
442
            !empty($this->metadataArray[$id])
443
            && $this->metadataArray[0] == $cPid
444
        ) {
445
            return $this->metadataArray[$id];
446
        }
447
448
        $metadata = $this->initializeMetadata('METS');
449
450
        $mdIds = $this->getMetadataIds($id);
451
        if (empty($mdIds)) {
452
            // There is no metadata section for this structure node.
453
            return [];
454
        }
455
        // Associative array used as set of available section types (dmdSec, techMD, ...)
456
        $hasMetadataSection = [];
457
        // Load available metadata formats and metadata sections.
458
        $this->loadFormats();
459
        $this->_getMdSec();
460
        // Get the structure's type.
461
        if (!empty($this->logicalUnits[$id])) {
462
            $metadata['type'] = [$this->logicalUnits[$id]['type']];
463
        } else {
464
            $struct = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]/@TYPE');
465
            if (!empty($struct)) {
466
                $metadata['type'] = [(string) $struct[0]];
467
            }
468
        }
469
        foreach ($mdIds as $dmdId) {
470
            $mdSectionType = $this->mdSec[$dmdId]['section'];
471
472
            // To preserve behavior of previous Kitodo versions, extract metadata only from first supported dmdSec
473
            // However, we want to extract, for example, all techMD sections (VIDEOMD, AUDIOMD)
474
            if ($mdSectionType === 'dmdSec' && isset($hasMetadataSection['dmdSec'])) {
475
                continue;
476
            }
477
478
            // Is this metadata format supported?
479
            if (!empty($this->formats[$this->mdSec[$dmdId]['type']])) {
480
                if (!empty($this->formats[$this->mdSec[$dmdId]['type']]['class'])) {
481
                    $class = $this->formats[$this->mdSec[$dmdId]['type']]['class'];
482
                    // Get the metadata from class.
483
                    if (
484
                        class_exists($class)
485
                        && ($obj = GeneralUtility::makeInstance($class)) instanceof MetadataInterface
486
                    ) {
487
                        $obj->extractMetadata($this->mdSec[$dmdId]['xml'], $metadata);
488
                    } else {
489
                        $this->logger->warning('Invalid class/method "' . $class . '->extractMetadata()" for metadata format "' . $this->mdSec[$dmdId]['type'] . '"');
490
                    }
491
                }
492
            } else {
493
                $this->logger->notice('Unsupported metadata format "' . $this->mdSec[$dmdId]['type'] . '" in ' . $mdSectionType . ' with @ID "' . $dmdId . '"');
494
                // Continue searching for supported metadata with next @DMDID.
495
                continue;
496
            }
497
            // Get the additional metadata from database.
498
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
499
                ->getQueryBuilderForTable('tx_dlf_metadata');
500
            // Get hidden records, too.
501
            $queryBuilder
502
                ->getRestrictions()
503
                ->removeByType(HiddenRestriction::class);
504
            // Get all metadata with configured xpath and applicable format first.
505
            $resultWithFormat = $queryBuilder
506
                ->select(
507
                    'tx_dlf_metadata.index_name AS index_name',
508
                    'tx_dlf_metadataformat_joins.xpath AS xpath',
509
                    'tx_dlf_metadataformat_joins.xpath_sorting AS xpath_sorting',
510
                    'tx_dlf_metadata.is_sortable AS is_sortable',
511
                    'tx_dlf_metadata.default_value AS default_value',
512
                    'tx_dlf_metadata.format AS format'
513
                )
514
                ->from('tx_dlf_metadata')
515
                ->innerJoin(
516
                    'tx_dlf_metadata',
517
                    'tx_dlf_metadataformat',
518
                    'tx_dlf_metadataformat_joins',
519
                    $queryBuilder->expr()->eq(
520
                        'tx_dlf_metadataformat_joins.parent_id',
521
                        'tx_dlf_metadata.uid'
522
                    )
523
                )
524
                ->innerJoin(
525
                    'tx_dlf_metadataformat_joins',
526
                    'tx_dlf_formats',
527
                    'tx_dlf_formats_joins',
528
                    $queryBuilder->expr()->eq(
529
                        'tx_dlf_formats_joins.uid',
530
                        'tx_dlf_metadataformat_joins.encoded'
531
                    )
532
                )
533
                ->where(
534
                    $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($cPid)),
535
                    $queryBuilder->expr()->eq('tx_dlf_metadata.l18n_parent', 0),
536
                    $queryBuilder->expr()->eq('tx_dlf_metadataformat_joins.pid', intval($cPid)),
537
                    $queryBuilder->expr()->eq('tx_dlf_formats_joins.type', $queryBuilder->createNamedParameter($this->mdSec[$dmdId]['type']))
538
                )
539
                ->execute();
540
            // Get all metadata without a format, but with a default value next.
541
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
542
                ->getQueryBuilderForTable('tx_dlf_metadata');
543
            // Get hidden records, too.
544
            $queryBuilder
545
                ->getRestrictions()
546
                ->removeByType(HiddenRestriction::class);
547
            $resultWithoutFormat = $queryBuilder
548
                ->select(
549
                    'tx_dlf_metadata.index_name AS index_name',
550
                    'tx_dlf_metadata.is_sortable AS is_sortable',
551
                    'tx_dlf_metadata.default_value AS default_value',
552
                    'tx_dlf_metadata.format AS format'
553
                )
554
                ->from('tx_dlf_metadata')
555
                ->where(
556
                    $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($cPid)),
557
                    $queryBuilder->expr()->eq('tx_dlf_metadata.l18n_parent', 0),
558
                    $queryBuilder->expr()->eq('tx_dlf_metadata.format', 0),
559
                    $queryBuilder->expr()->neq('tx_dlf_metadata.default_value', $queryBuilder->createNamedParameter(''))
560
                )
561
                ->execute();
562
            // Merge both result sets.
563
            $allResults = array_merge($resultWithFormat->fetchAll(), $resultWithoutFormat->fetchAll());
564
            // We need a \DOMDocument here, because SimpleXML doesn't support XPath functions properly.
565
            $domNode = dom_import_simplexml($this->mdSec[$dmdId]['xml']);
566
            $domXPath = new \DOMXPath($domNode->ownerDocument);
0 ignored issues
show
Bug introduced by
It seems like $domNode->ownerDocument can also be of type null; however, parameter $document of DOMXPath::__construct() does only seem to accept DOMDocument, 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

566
            $domXPath = new \DOMXPath(/** @scrutinizer ignore-type */ $domNode->ownerDocument);
Loading history...
567
            $this->registerNamespaces($domXPath);
568
            // OK, now make the XPath queries.
569
            foreach ($allResults as $resArray) {
570
                // Set metadata field's value(s).
571
                if (
572
                    $resArray['format'] > 0
573
                    && !empty($resArray['xpath'])
574
                    && ($values = $domXPath->evaluate($resArray['xpath'], $domNode))
575
                ) {
576
                    if (
577
                        $values instanceof \DOMNodeList
578
                        && $values->length > 0
579
                    ) {
580
                        $metadata[$resArray['index_name']] = [];
581
                        foreach ($values as $value) {
582
                            $metadata[$resArray['index_name']][] = trim((string) $value->nodeValue);
583
                        }
584
                    } elseif (!($values instanceof \DOMNodeList)) {
585
                        $metadata[$resArray['index_name']] = [trim((string) $values)];
586
                    }
587
                }
588
                // Set default value if applicable.
589
                if (
590
                    empty($metadata[$resArray['index_name']][0])
591
                    && strlen($resArray['default_value']) > 0
592
                ) {
593
                    $metadata[$resArray['index_name']] = [$resArray['default_value']];
594
                }
595
                // Set sorting value if applicable.
596
                if (
597
                    !empty($metadata[$resArray['index_name']])
598
                    && $resArray['is_sortable']
599
                ) {
600
                    if (
601
                        $resArray['format'] > 0
602
                        && !empty($resArray['xpath_sorting'])
603
                        && ($values = $domXPath->evaluate($resArray['xpath_sorting'], $domNode))
604
                    ) {
605
                        if (
606
                            $values instanceof \DOMNodeList
607
                            && $values->length > 0
608
                        ) {
609
                            $metadata[$resArray['index_name'] . '_sorting'][0] = trim((string) $values->item(0)->nodeValue);
610
                        } elseif (!($values instanceof \DOMNodeList)) {
611
                            $metadata[$resArray['index_name'] . '_sorting'][0] = trim((string) $values);
612
                        }
613
                    }
614
                    if (empty($metadata[$resArray['index_name'] . '_sorting'][0])) {
615
                        $metadata[$resArray['index_name'] . '_sorting'][0] = $metadata[$resArray['index_name']][0];
616
                    }
617
                }
618
            }
619
620
            $hasMetadataSection[$mdSectionType] = true;
621
        }
622
        // Set title to empty string if not present.
623
        if (empty($metadata['title'][0])) {
624
            $metadata['title'][0] = '';
625
            $metadata['title_sorting'][0] = '';
626
        }
627
        // Set title_sorting to title as default.
628
        if (empty($metadata['title_sorting'][0])) {
629
            $metadata['title_sorting'][0] = $metadata['title'][0];
630
        }
631
        // Set date to empty string if not present.
632
        if (empty($metadata['date'][0])) {
633
            $metadata['date'][0] = '';
634
        }
635
636
        // Files are not expected to reference a dmdSec
637
        if (isset($this->fileInfos[$id]) || isset($hasMetadataSection['dmdSec'])) {
638
            return $metadata;
639
        } else {
640
            $this->logger->warning('No supported descriptive metadata found for logical structure with @ID "' . $id . '"');
641
            return [];
642
        }
643
    }
644
645
    /**
646
     * Get IDs of (descriptive and administrative) metadata sections
647
     * referenced by node of given $id. The $id may refer to either
648
     * a logical structure node or to a file.
649
     *
650
     * @access protected
651
     *
652
     * @param string $id: The "@ID" attribute of the file node
653
     *
654
     * @return array
655
     */
656
    protected function getMetadataIds($id)
657
    {
658
        // Load amdSecChildIds concordance
659
        $this->_getMdSec();
660
        $fileInfo = $this->getFileInfo($id);
661
662
        // Get DMDID and ADMID of logical structure node
663
        if (!empty($this->logicalUnits[$id])) {
664
            $dmdIds = $this->logicalUnits[$id]['dmdId'] ?? '';
665
            $admIds = $this->logicalUnits[$id]['admId'] ?? '';
666
        } else {
667
            $mdSec = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]')[0];
668
            if ($mdSec) {
0 ignored issues
show
introduced by
$mdSec is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
669
                $dmdIds = (string) $mdSec->attributes()->DMDID;
670
                $admIds = (string) $mdSec->attributes()->ADMID;
671
            } else if (isset($fileInfo)) {
672
                $dmdIds = $fileInfo['dmdId'];
673
                $admIds = $fileInfo['admId'];
674
            } else {
675
                $dmdIds = '';
676
                $admIds = '';
677
            }
678
        }
679
680
        // Handle multiple DMDIDs/ADMIDs
681
        $allMdIds = explode(' ', $dmdIds);
682
683
        foreach (explode(' ', $admIds) as $admId) {
684
            if (isset($this->mdSec[$admId])) {
685
                // $admId references an actual metadata section such as techMD
686
                $allMdIds[] = $admId;
687
            } elseif (isset($this->amdSecChildIds[$admId])) {
688
                // $admId references a <mets:amdSec> element. Resolve child elements.
689
                foreach ($this->amdSecChildIds[$admId] as $childId) {
690
                    $allMdIds[] = $childId;
691
                }
692
            }
693
        }
694
695
        return array_filter($allMdIds, function ($element) {
696
            return !empty($element);
697
        });
698
    }
699
700
    /**
701
     * @see AbstractDocument::getFullText()
702
     */
703
    public function getFullText($id)
704
    {
705
        $fullText = '';
706
707
        // Load fileGrps and check for full text files.
708
        $this->_getFileGrps();
709
        if ($this->hasFulltext) {
710
            $fullText = $this->getFullTextFromXml($id);
711
        }
712
        return $fullText;
713
    }
714
715
    /**
716
     * @see AbstractDocument::getStructureDepth()
717
     */
718
    public function getStructureDepth($logId)
719
    {
720
        $ancestors = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $logId . '"]/ancestor::*');
721
        if (!empty($ancestors)) {
722
            return count($ancestors);
723
        } else {
724
            return 0;
725
        }
726
    }
727
728
    /**
729
     * @see AbstractDocument::init()
730
     */
731
    protected function init($location)
732
    {
733
        $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(get_class($this));
734
        // Get METS node from XML file.
735
        $this->registerNamespaces($this->xml);
736
        $mets = $this->xml->xpath('//mets:mets');
737
        if (!empty($mets)) {
738
            $this->mets = $mets[0];
739
            // Register namespaces.
740
            $this->registerNamespaces($this->mets);
741
        } else {
742
            if (!empty($location)) {
743
                $this->logger->error('No METS part found in document with location "' . $location . '".');
744
            } else if (!empty($this->recordId)) {
745
                $this->logger->error('No METS part found in document with recordId "' . $this->recordId . '".');
746
            } else {
747
                $this->logger->error('No METS part found in current document.');
748
            }
749
        }
750
    }
751
752
    /**
753
     * @see AbstractDocument::loadLocation()
754
     */
755
    protected function loadLocation($location)
756
    {
757
        $fileResource = Helper::getUrl($location);
758
        if ($fileResource !== false) {
759
            $xml = Helper::getXmlFileAsString($fileResource);
760
            // Set some basic properties.
761
            if ($xml !== false) {
762
                $this->xml = $xml;
763
                return true;
764
            }
765
        }
766
        $this->logger->error('Could not load XML file from "' . $location . '"');
767
        return false;
768
    }
769
770
    /**
771
     * @see AbstractDocument::ensureHasFulltextIsSet()
772
     */
773
    protected function ensureHasFulltextIsSet()
774
    {
775
        // Are the fileGrps already loaded?
776
        if (!$this->fileGrpsLoaded) {
777
            $this->_getFileGrps();
778
        }
779
    }
780
781
    /**
782
     * @see AbstractDocument::setPreloadedDocument()
783
     */
784
    protected function setPreloadedDocument($preloadedDocument)
785
    {
786
787
        if ($preloadedDocument instanceof \SimpleXMLElement) {
788
            $this->xml = $preloadedDocument;
789
            return true;
790
        }
791
        return false;
792
    }
793
794
    /**
795
     * @see AbstractDocument::getDocument()
796
     */
797
    protected function getDocument()
798
    {
799
        return $this->mets;
800
    }
801
802
    /**
803
     * This builds an array of the document's metadata sections
804
     *
805
     * @access protected
806
     *
807
     * @return array Array of metadata sections with their IDs as array key
808
     */
809
    protected function _getMdSec()
810
    {
811
        if (!$this->mdSecLoaded) {
812
            $this->loadFormats();
813
814
            foreach ($this->mets->xpath('./mets:dmdSec') as $dmdSecTag) {
815
                $dmdSec = $this->processMdSec($dmdSecTag);
816
817
                if ($dmdSec !== null) {
818
                    $this->mdSec[$dmdSec['id']] = $dmdSec;
0 ignored issues
show
Bug introduced by
The property mdSec is declared read-only in Kitodo\Dlf\Common\MetsDocument.
Loading history...
819
                    $this->dmdSec[$dmdSec['id']] = $dmdSec;
820
                }
821
            }
822
823
            foreach ($this->mets->xpath('./mets:amdSec') as $amdSecTag) {
824
                $childIds = [];
825
826
                foreach ($amdSecTag->children('http://www.loc.gov/METS/') as $mdSecTag) {
827
                    if (!in_array($mdSecTag->getName(), self::ALLOWED_AMD_SEC)) {
828
                        continue;
829
                    }
830
831
                    // TODO: Should we check that the format may occur within this type (e.g., to ignore VIDEOMD within rightsMD)?
832
                    $mdSec = $this->processMdSec($mdSecTag);
833
834
                    if ($mdSec !== null) {
835
                        $this->mdSec[$mdSec['id']] = $mdSec;
836
837
                        $childIds[] = $mdSec['id'];
838
                    }
839
                }
840
841
                $amdSecId = (string) $amdSecTag->attributes()->ID;
842
                if (!empty($amdSecId)) {
843
                    $this->amdSecChildIds[$amdSecId] = $childIds;
844
                }
845
            }
846
847
            $this->mdSecLoaded = true;
848
        }
849
        return $this->mdSec;
850
    }
851
852
    protected function _getDmdSec()
853
    {
854
        $this->_getMdSec();
855
        return $this->dmdSec;
856
    }
857
858
    /**
859
     * Processes an element of METS `mdSecType`.
860
     *
861
     * @access protected
862
     *
863
     * @param \SimpleXMLElement $element
864
     *
865
     * @return array|null The processed metadata section
866
     */
867
    protected function processMdSec($element)
868
    {
869
        $mdId = (string) $element->attributes()->ID;
870
        if (empty($mdId)) {
871
            return null;
872
        }
873
874
        $this->registerNamespaces($element);
875
        if ($type = $element->xpath('./mets:mdWrap[not(@MDTYPE="OTHER")]/@MDTYPE')) {
876
            if (!empty($this->formats[(string) $type[0]])) {
877
                $type = (string) $type[0];
878
                $xml = $element->xpath('./mets:mdWrap[@MDTYPE="' . $type . '"]/mets:xmlData/' . strtolower($type) . ':' . $this->formats[$type]['rootElement']);
879
            }
880
        } elseif ($type = $element->xpath('./mets:mdWrap[@MDTYPE="OTHER"]/@OTHERMDTYPE')) {
881
            if (!empty($this->formats[(string) $type[0]])) {
882
                $type = (string) $type[0];
883
                $xml = $element->xpath('./mets:mdWrap[@MDTYPE="OTHER"][@OTHERMDTYPE="' . $type . '"]/mets:xmlData/' . strtolower($type) . ':' . $this->formats[$type]['rootElement']);
884
            }
885
        }
886
887
        if (empty($xml)) {
888
            return null;
889
        }
890
891
        $this->registerNamespaces($xml[0]);
892
893
        return [
894
            'id' => $mdId,
895
            'section' => $element->getName(),
896
            'type' => $type,
897
            'xml' => $xml[0],
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $xml does not seem to be defined for all execution paths leading up to this point.
Loading history...
898
        ];
899
    }
900
901
    /**
902
     * This builds the file ID -> USE concordance
903
     *
904
     * @access protected
905
     *
906
     * @return array Array of file use groups with file IDs
907
     */
908
    protected function _getFileGrps()
909
    {
910
        if (!$this->fileGrpsLoaded) {
911
            // Get configured USE attributes.
912
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
913
            $useGrps = GeneralUtility::trimExplode(',', $extConf['fileGrpImages']);
914
            if (!empty($extConf['fileGrpThumbs'])) {
915
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']));
916
            }
917
            if (!empty($extConf['fileGrpDownload'])) {
918
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpDownload']));
919
            }
920
            if (!empty($extConf['fileGrpFulltext'])) {
921
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpFulltext']));
922
            }
923
            if (!empty($extConf['fileGrpAudio'])) {
924
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpAudio']));
925
            }
926
            // Get all file groups.
927
            $fileGrps = $this->mets->xpath('./mets:fileSec/mets:fileGrp');
928
            if (!empty($fileGrps)) {
929
                // Build concordance for configured USE attributes.
930
                foreach ($fileGrps as $fileGrp) {
931
                    if (in_array((string) $fileGrp['USE'], $useGrps)) {
932
                        foreach ($fileGrp->children('http://www.loc.gov/METS/')->file as $file) {
933
                            $fileId = (string) $file->attributes()->ID;
0 ignored issues
show
Bug introduced by
The method attributes() 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

933
                            $fileId = (string) $file->/** @scrutinizer ignore-call */ attributes()->ID;

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...
934
                            $this->fileGrps[$fileId] = (string) $fileGrp['USE'];
935
                            $this->fileInfos[$fileId] = [
0 ignored issues
show
Bug introduced by
The property fileInfos is declared read-only in Kitodo\Dlf\Common\AbstractDocument.
Loading history...
936
                                'fileGrp' => (string) $fileGrp['USE'],
937
                                'admId' => (string) $file->attributes()->ADMID,
938
                                'dmdId' => (string) $file->attributes()->DMDID,
939
                            ];
940
                        }
941
                    }
942
                }
943
            }
944
            // Are there any fulltext files available?
945
            if (
946
                !empty($extConf['fileGrpFulltext'])
947
                && array_intersect(GeneralUtility::trimExplode(',', $extConf['fileGrpFulltext']), $this->fileGrps) !== []
948
            ) {
949
                $this->hasFulltext = true;
950
            }
951
            $this->fileGrpsLoaded = true;
952
        }
953
        return $this->fileGrps;
954
    }
955
956
    /**
957
     * @access protected
958
     * @return array
959
     */
960
    protected function _getFileInfos()
961
    {
962
        $this->_getFileGrps();
963
        return $this->fileInfos;
964
    }
965
966
    /**
967
     * @see AbstractDocument::prepareMetadataArray()
968
     */
969
    protected function prepareMetadataArray($cPid)
970
    {
971
        $ids = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID]/@ID');
972
        // Get all logical structure nodes with metadata.
973
        if (!empty($ids)) {
974
            foreach ($ids as $id) {
975
                $this->metadataArray[(string) $id] = $this->getMetadata((string) $id, $cPid);
976
            }
977
        }
978
        // Set current PID for metadata definitions.
979
    }
980
981
    /**
982
     * This returns $this->mets via __get()
983
     *
984
     * @access protected
985
     *
986
     * @return \SimpleXMLElement The XML's METS part as \SimpleXMLElement object
987
     */
988
    protected function _getMets()
989
    {
990
        return $this->mets;
991
    }
992
993
    /**
994
     * @see AbstractDocument::_getPhysicalStructure()
995
     */
996
    protected function _getPhysicalStructure()
997
    {
998
        // Is there no physical structure array yet?
999
        if (!$this->physicalStructureLoaded) {
1000
            // Does the document have a structMap node of type "PHYSICAL"?
1001
            $elementNodes = $this->mets->xpath('./mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div');
1002
            if (!empty($elementNodes)) {
1003
                // Get file groups.
1004
                $fileUse = $this->_getFileGrps();
1005
                // Get the physical sequence's metadata.
1006
                $physNode = $this->mets->xpath('./mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]');
1007
                $physSeq[0] = (string) $physNode[0]['ID'];
1008
                $this->physicalStructureInfo[$physSeq[0]]['id'] = (string) $physNode[0]['ID'];
1009
                $this->physicalStructureInfo[$physSeq[0]]['dmdId'] = (isset($physNode[0]['DMDID']) ? (string) $physNode[0]['DMDID'] : '');
1010
                $this->physicalStructureInfo[$physSeq[0]]['admId'] = (isset($physNode[0]['ADMID']) ? (string) $physNode[0]['ADMID'] : '');
1011
                $this->physicalStructureInfo[$physSeq[0]]['order'] = (isset($physNode[0]['ORDER']) ? (string) $physNode[0]['ORDER'] : '');
1012
                $this->physicalStructureInfo[$physSeq[0]]['label'] = (isset($physNode[0]['LABEL']) ? (string) $physNode[0]['LABEL'] : '');
1013
                $this->physicalStructureInfo[$physSeq[0]]['orderlabel'] = (isset($physNode[0]['ORDERLABEL']) ? (string) $physNode[0]['ORDERLABEL'] : '');
1014
                $this->physicalStructureInfo[$physSeq[0]]['type'] = (string) $physNode[0]['TYPE'];
1015
                $this->physicalStructureInfo[$physSeq[0]]['contentIds'] = (isset($physNode[0]['CONTENTIDS']) ? (string) $physNode[0]['CONTENTIDS'] : '');
1016
                // Get the file representations from fileSec node.
1017
                foreach ($physNode[0]->children('http://www.loc.gov/METS/')->fptr as $fptr) {
1018
                    // Check if file has valid @USE attribute.
1019
                    if (!empty($fileUse[(string) $fptr->attributes()->FILEID])) {
1020
                        $this->physicalStructureInfo[$physSeq[0]]['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
1021
                    }
1022
                }
1023
                // Build the physical elements' array from the physical structMap node.
1024
                foreach ($elementNodes as $elementNode) {
1025
                    $elements[(int) $elementNode['ORDER']] = (string) $elementNode['ID'];
1026
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['id'] = (string) $elementNode['ID'];
1027
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['dmdId'] = (isset($elementNode['DMDID']) ? (string) $elementNode['DMDID'] : '');
1028
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['admId'] = (isset($elementNode['ADMID']) ? (string) $elementNode['ADMID'] : '');
1029
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['order'] = (isset($elementNode['ORDER']) ? (string) $elementNode['ORDER'] : '');
1030
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['label'] = (isset($elementNode['LABEL']) ? (string) $elementNode['LABEL'] : '');
1031
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['orderlabel'] = (isset($elementNode['ORDERLABEL']) ? (string) $elementNode['ORDERLABEL'] : '');
1032
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['type'] = (string) $elementNode['TYPE'];
1033
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['contentIds'] = (isset($elementNode['CONTENTIDS']) ? (string) $elementNode['CONTENTIDS'] : '');
1034
                    // Get the file representations from fileSec node.
1035
                    foreach ($elementNode->children('http://www.loc.gov/METS/')->fptr as $fptr) {
1036
                        // Check if file has valid @USE attribute.
1037
                        if (!empty($fileUse[(string) $fptr->attributes()->FILEID])) {
1038
                            $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
1039
                        }
1040
                    }
1041
                }
1042
                // Sort array by keys (= @ORDER).
1043
                if (ksort($elements)) {
1044
                    // Set total number of pages/tracks.
1045
                    $this->numPages = count($elements);
1046
                    // Merge and re-index the array to get nice numeric indexes.
1047
                    $this->physicalStructure = array_merge($physSeq, $elements);
1048
                }
1049
            }
1050
            $this->physicalStructureLoaded = true;
1051
        }
1052
        return $this->physicalStructure;
1053
    }
1054
1055
    /**
1056
     * @see AbstractDocument::_getSmLinks()
1057
     */
1058
    protected function _getSmLinks()
1059
    {
1060
        if (!$this->smLinksLoaded) {
1061
            $smLinks = $this->mets->xpath('./mets:structLink/mets:smLink');
1062
            if (!empty($smLinks)) {
1063
                foreach ($smLinks as $smLink) {
1064
                    $this->smLinks['l2p'][(string) $smLink->attributes('http://www.w3.org/1999/xlink')->from][] = (string) $smLink->attributes('http://www.w3.org/1999/xlink')->to;
1065
                    $this->smLinks['p2l'][(string) $smLink->attributes('http://www.w3.org/1999/xlink')->to][] = (string) $smLink->attributes('http://www.w3.org/1999/xlink')->from;
1066
                }
1067
            }
1068
            $this->smLinksLoaded = true;
1069
        }
1070
        return $this->smLinks;
1071
    }
1072
1073
    /**
1074
     * @see AbstractDocument::_getThumbnail()
1075
     */
1076
    protected function _getThumbnail($forceReload = false)
1077
    {
1078
        if (
1079
            !$this->thumbnailLoaded
1080
            || $forceReload
1081
        ) {
1082
            // Retain current PID.
1083
            $cPid = ($this->cPid ? $this->cPid : $this->pid);
1084
            if (!$cPid) {
1085
                $this->logger->error('Invalid PID ' . $cPid . ' for structure definitions');
1086
                $this->thumbnailLoaded = true;
1087
                return $this->thumbnail;
1088
            }
1089
            // Load extension configuration.
1090
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
1091
            if (empty($extConf['fileGrpThumbs'])) {
1092
                $this->logger->warning('No fileGrp for thumbnails specified');
1093
                $this->thumbnailLoaded = true;
1094
                return $this->thumbnail;
1095
            }
1096
            $strctId = $this->_getToplevelId();
1097
            $metadata = $this->getTitledata($cPid);
1098
1099
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1100
                ->getQueryBuilderForTable('tx_dlf_structures');
1101
1102
            // Get structure element to get thumbnail from.
1103
            $result = $queryBuilder
1104
                ->select('tx_dlf_structures.thumbnail AS thumbnail')
1105
                ->from('tx_dlf_structures')
1106
                ->where(
1107
                    $queryBuilder->expr()->eq('tx_dlf_structures.pid', intval($cPid)),
1108
                    $queryBuilder->expr()->eq('tx_dlf_structures.index_name', $queryBuilder->expr()->literal($metadata['type'][0])),
1109
                    Helper::whereExpression('tx_dlf_structures')
1110
                )
1111
                ->setMaxResults(1)
1112
                ->execute();
1113
1114
            $allResults = $result->fetchAll();
1115
1116
            if (count($allResults) == 1) {
1117
                $resArray = $allResults[0];
1118
                // Get desired thumbnail structure if not the toplevel structure itself.
1119
                if (!empty($resArray['thumbnail'])) {
1120
                    $strctType = Helper::getIndexNameFromUid($resArray['thumbnail'], 'tx_dlf_structures', $cPid);
1121
                    // Check if this document has a structure element of the desired type.
1122
                    $strctIds = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@TYPE="' . $strctType . '"]/@ID');
1123
                    if (!empty($strctIds)) {
1124
                        $strctId = (string) $strctIds[0];
1125
                    }
1126
                }
1127
                // Load smLinks.
1128
                $this->_getSmLinks();
1129
                // Get thumbnail location.
1130
                $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
1131
                while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
1132
                    if (
1133
                        $this->_getPhysicalStructure()
1134
                        && !empty($this->smLinks['l2p'][$strctId])
1135
                        && !empty($this->physicalStructureInfo[$this->smLinks['l2p'][$strctId][0]]['files'][$fileGrpThumb])
1136
                    ) {
1137
                        $this->thumbnail = $this->getFileLocation($this->physicalStructureInfo[$this->smLinks['l2p'][$strctId][0]]['files'][$fileGrpThumb]);
1138
                        break;
1139
                    } elseif (!empty($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb])) {
1140
                        $this->thumbnail = $this->getFileLocation($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb]);
1141
                        break;
1142
                    }
1143
                }
1144
            } else {
1145
                $this->logger->error('No structure of type "' . $metadata['type'][0] . '" found in database');
1146
            }
1147
            $this->thumbnailLoaded = true;
1148
        }
1149
        return $this->thumbnail;
1150
    }
1151
1152
    /**
1153
     * @see AbstractDocument::_getToplevelId()
1154
     */
1155
    protected function _getToplevelId()
1156
    {
1157
        if (empty($this->toplevelId)) {
1158
            // Get all logical structure nodes with metadata, but without associated METS-Pointers.
1159
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID and not(./mets:mptr)]');
1160
            if (!empty($divs)) {
1161
                // Load smLinks.
1162
                $this->_getSmLinks();
1163
                foreach ($divs as $div) {
1164
                    $id = (string) $div['ID'];
1165
                    // Are there physical structure nodes for this logical structure?
1166
                    if (array_key_exists($id, $this->smLinks['l2p'])) {
1167
                        // Yes. That's what we're looking for.
1168
                        $this->toplevelId = $id;
1169
                        break;
1170
                    } elseif (empty($this->toplevelId)) {
1171
                        // No. Remember this anyway, but keep looking for a better one.
1172
                        $this->toplevelId = $id;
1173
                    }
1174
                }
1175
            }
1176
        }
1177
        return $this->toplevelId;
1178
    }
1179
1180
    /**
1181
     * Try to determine URL of parent document.
1182
     *
1183
     * @return string
1184
     */
1185
    public function _getParentHref()
1186
    {
1187
        if ($this->parentHref === null) {
1188
            $this->parentHref = '';
0 ignored issues
show
Bug introduced by
The property parentHref is declared read-only in Kitodo\Dlf\Common\MetsDocument.
Loading history...
1189
1190
            // Get the closest ancestor of the current document which has a MPTR child.
1191
            $parentMptr = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $this->toplevelId . '"]/ancestor::mets:div[./mets:mptr][1]/mets:mptr');
1192
            if (!empty($parentMptr)) {
1193
                $this->parentHref = (string) $parentMptr[0]->attributes('http://www.w3.org/1999/xlink')->href;
1194
            }
1195
        }
1196
1197
        return $this->parentHref;
1198
    }
1199
1200
    /**
1201
     * This magic method is executed prior to any serialization of the object
1202
     * @see __wakeup()
1203
     *
1204
     * @access public
1205
     *
1206
     * @return array Properties to be serialized
1207
     */
1208
    public function __sleep()
1209
    {
1210
        // \SimpleXMLElement objects can't be serialized, thus save the XML as string for serialization
1211
        $this->asXML = $this->xml->asXML();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->xml->asXML() can also be of type true. However, the property $asXML is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1212
        return ['uid', 'pid', 'recordId', 'parentId', 'asXML'];
1213
    }
1214
1215
    /**
1216
     * This magic method is used for setting a string value for the object
1217
     *
1218
     * @access public
1219
     *
1220
     * @return string String representing the METS object
1221
     */
1222
    public function __toString()
1223
    {
1224
        $xml = new \DOMDocument('1.0', 'utf-8');
1225
        $xml->appendChild($xml->importNode(dom_import_simplexml($this->mets), true));
1226
        $xml->formatOutput = true;
1227
        return $xml->saveXML();
1228
    }
1229
1230
    /**
1231
     * This magic method is executed after the object is deserialized
1232
     * @see __sleep()
1233
     *
1234
     * @access public
1235
     *
1236
     * @return void
1237
     */
1238
    public function __wakeup()
1239
    {
1240
        $xml = Helper::getXmlFileAsString($this->asXML);
1241
        if ($xml !== false) {
1242
            $this->asXML = '';
1243
            $this->xml = $xml;
1244
            // Rebuild the unserializable properties.
1245
            $this->init('');
1246
        } else {
1247
            $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(static::class);
1248
            $this->logger->error('Could not load XML after deserialization');
1249
        }
1250
    }
1251
}
1252