Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#878)
by Beatrycze
03:05
created

MetsDocument::getAllFiles()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 20
c 1
b 0
f 0
nc 11
nop 0
dl 0
loc 34
rs 8.6666
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\Utility\GeneralUtility;
19
use Ubl\Iiif\Tools\IiifHelper;
20
use Ubl\Iiif\Services\AbstractImageService;
21
use TYPO3\CMS\Core\Log\LogManager;
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 array $fileInfos Additional information about files (e.g., ADMID), indexed by ID.
36
 * @property-read bool $hasFulltext Are there any fulltext files available?
37
 * @property-read array $metadataArray This holds the documents' parsed metadata array
38
 * @property-read \SimpleXMLElement $mets This holds the XML file's METS part as \SimpleXMLElement object
39
 * @property-read int $numPages The holds the total number of pages
40
 * @property-read int $parentId This holds the UID of the parent document or zero if not multi-volumed
41
 * @property-read array $physicalStructure This holds the physical structure
42
 * @property-read array $physicalStructureInfo This holds the physical structure metadata
43
 * @property-read int $pid This holds the PID of the document or zero if not in database
44
 * @property-read bool $ready Is the document instantiated successfully?
45
 * @property-read string $recordId The METS file's / IIIF manifest's record identifier
46
 * @property-read int $rootId This holds the UID of the root document or zero if not multi-volumed
47
 * @property-read array $smLinks This holds the smLinks between logical and physical structMap
48
 * @property-read array $tableOfContents This holds the logical structure
49
 * @property-read string $thumbnail This holds the document's thumbnail location
50
 * @property-read string $toplevelId This holds the toplevel structure's @ID (METS) or the manifest's @id (IIIF)
51
 * @property-read string $parentHref URL of the parent document (determined via mptr element), or empty string if none is available
52
 */
53
final class MetsDocument extends Doc
54
{
55
    /**
56
     * Subsections / tags that may occur within `<mets:amdSec>`.
57
     *
58
     * @link https://www.loc.gov/standards/mets/docs/mets.v1-9.html#amdSec
59
     * @link https://www.loc.gov/standards/mets/docs/mets.v1-9.html#mdSecType
60
     *
61
     * @var string[]
62
     */
63
    protected const ALLOWED_AMD_SEC = ['techMD', 'rightsMD', 'sourceMD', 'digiprovMD'];
64
65
    /**
66
     * This holds the whole XML file as string for serialization purposes
67
     * @see __sleep() / __wakeup()
68
     *
69
     * @var string
70
     * @access protected
71
     */
72
    protected $asXML = '';
73
74
    /**
75
     * This maps the ID of each amdSec to the IDs of its children (techMD etc.).
76
     * When an ADMID references an amdSec instead of techMD etc., this is used to iterate the child elements.
77
     *
78
     * @var string[]
79
     * @access protected
80
     */
81
    protected $amdSecChildIds = [];
82
83
    /**
84
     * Associative array of METS metadata sections indexed by their IDs.
85
     *
86
     * @var array
87
     * @access protected
88
     */
89
    protected $mdSec = [];
90
91
    /**
92
     * Are the METS file's metadata sections loaded?
93
     * @see MetsDocument::$mdSec
94
     *
95
     * @var bool
96
     * @access protected
97
     */
98
    protected $mdSecLoaded = false;
99
100
    /**
101
     * Subset of $mdSec storing only the dmdSec entries; kept for compatibility.
102
     *
103
     * @var array
104
     * @access protected
105
     */
106
    protected $dmdSec = [];
107
108
    /**
109
     * The extension key
110
     *
111
     * @var	string
112
     * @access public
113
     */
114
    public static $extKey = 'dlf';
115
116
    /**
117
     * This holds the file ID -> USE concordance
118
     * @see _getFileGrps()
119
     *
120
     * @var array
121
     * @access protected
122
     */
123
    protected $fileGrps = [];
124
125
    /**
126
     * Are the image file groups loaded?
127
     * @see $fileGrps
128
     *
129
     * @var bool
130
     * @access protected
131
     */
132
    protected $fileGrpsLoaded = false;
133
134
    /**
135
     * Additional information about files (e.g., ADMID), indexed by ID.
136
     * TODO: Consider using this for `getFileMimeType()` and `getFileLocation()`.
137
     * @see _getFileInfos()
138
     *
139
     * @var array
140
     * @access protected
141
     */
142
    protected $fileInfos = [];
143
144
    /**
145
     * This holds the XML file's METS part as \SimpleXMLElement object
146
     *
147
     * @var \SimpleXMLElement
148
     * @access protected
149
     */
150
    protected $mets;
151
152
    /**
153
     * This holds the whole XML file as \SimpleXMLElement object
154
     *
155
     * @var \SimpleXMLElement
156
     * @access protected
157
     */
158
    protected $xml;
159
160
    /**
161
     * URL of the parent document (determined via mptr element),
162
     * or empty string if none is available
163
     *
164
     * @var string|null
165
     * @access protected
166
     */
167
    protected $parentHref;
168
169
    /**
170
     * This adds metadata from METS structural map to metadata array.
171
     *
172
     * @access	public
173
     *
174
     * @param	array	&$metadata: The metadata array to extend
175
     * @param	string	$id: The "@ID" attribute of the logical structure node
176
     *
177
     * @return  void
178
     */
179
    public function addMetadataFromMets(&$metadata, $id)
180
    {
181
        $details = $this->getLogicalStructure($id);
182
        if (!empty($details)) {
183
            $metadata['mets_order'][0] = $details['order'];
184
            $metadata['mets_label'][0] = $details['label'];
185
            $metadata['mets_orderlabel'][0] = $details['orderlabel'];
186
        }
187
    }
188
189
    /**
190
     *
191
     * {@inheritDoc}
192
     * @see \Kitodo\Dlf\Common\Doc::establishRecordId()
193
     */
194
    protected function establishRecordId($pid)
195
    {
196
        // Check for METS object @ID.
197
        if (!empty($this->mets['OBJID'])) {
198
            $this->recordId = (string) $this->mets['OBJID'];
199
        }
200
        // Get hook objects.
201
        $hookObjects = Helper::getHookObjects('Classes/Common/MetsDocument.php');
202
        // Apply hooks.
203
        foreach ($hookObjects as $hookObj) {
204
            if (method_exists($hookObj, 'construct_postProcessRecordId')) {
205
                $hookObj->construct_postProcessRecordId($this->xml, $this->recordId);
206
            }
207
        }
208
    }
209
210
    /**
211
     *
212
     * {@inheritDoc}
213
     * @see \Kitodo\Dlf\Common\Doc::getDownloadLocation()
214
     */
215
    public function getDownloadLocation($id)
216
    {
217
        $fileMimeType = $this->getFileMimeType($id);
218
        $fileLocation = $this->getFileLocation($id);
219
        if ($fileMimeType === 'application/vnd.kitodo.iiif') {
220
            $fileLocation = (strrpos($fileLocation, 'info.json') === strlen($fileLocation) - 9) ? $fileLocation : (strrpos($fileLocation, '/') === strlen($fileLocation) ? $fileLocation . 'info.json' : $fileLocation . '/info.json');
221
            $conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
222
            IiifHelper::setUrlReader(IiifUrlReader::getInstance());
223
            IiifHelper::setMaxThumbnailHeight($conf['iiifThumbnailHeight']);
224
            IiifHelper::setMaxThumbnailWidth($conf['iiifThumbnailWidth']);
225
            $service = IiifHelper::loadIiifResource($fileLocation);
226
            if ($service !== null && $service instanceof AbstractImageService) {
227
                return $service->getImageUrl();
228
            }
229
        } elseif ($fileMimeType === 'application/vnd.netfpx') {
230
            $baseURL = $fileLocation . (strpos($fileLocation, '?') === false ? '?' : '');
231
            // TODO CVT is an optional IIP server capability; in theory, capabilities should be determined in the object request with '&obj=IIP-server'
232
            return $baseURL . '&CVT=jpeg';
233
        }
234
        return $fileLocation;
235
    }
236
237
    /**
238
     * {@inheritDoc}
239
     * @see \Kitodo\Dlf\Common\Doc::getFileLocation()
240
     */
241
    public function getFileLocation($id)
242
    {
243
        $location = $this->mets->xpath('./mets:fileSec/mets:fileGrp/mets:file[@ID="' . $id . '"]/mets:FLocat[@LOCTYPE="URL"]');
244
        if (
245
            !empty($id)
246
            && !empty($location)
247
        ) {
248
            return (string) $location[0]->attributes('http://www.w3.org/1999/xlink')->href;
249
        } else {
250
            $this->logger->warning('There is no file node with @ID "' . $id . '"');
251
            return '';
252
        }
253
    }
254
255
    /**
256
     * {@inheritDoc}
257
     * @see \Kitodo\Dlf\Common\Doc::getFileMimeType()
258
     */
259
    public function getFileMimeType($id)
260
    {
261
        $mimetype = $this->mets->xpath('./mets:fileSec/mets:fileGrp/mets:file[@ID="' . $id . '"]/@MIMETYPE');
262
        if (
263
            !empty($id)
264
            && !empty($mimetype)
265
        ) {
266
            return (string) $mimetype[0];
267
        } else {
268
            $this->logger->warning('There is no file node with @ID "' . $id . '" or no MIME type specified');
269
            return '';
270
        }
271
    }
272
273
    /**
274
     * {@inheritDoc}
275
     * @see \Kitodo\Dlf\Common\Doc::getAllFiles()
276
     */
277
    public function getAllFiles()
278
    {
279
        $files = [];
280
        $fileNodes = $this->mets->xpath('./mets:fileSec/mets:fileGrp/mets:file');
281
        foreach ($fileNodes as $fileNode) {
282
            $fileId = (string) $fileNode->attributes()->ID;
283
            if (empty($fileId)) {
284
                continue;
285
            }
286
287
            $url = null;
288
            foreach ($fileNode->children('http://www.loc.gov/METS/')->FLocat as $locator) {
289
                if ((string) $locator->attributes()['LOCTYPE'] === 'URL') {
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

289
                if ((string) $locator->/** @scrutinizer ignore-call */ attributes()['LOCTYPE'] === 'URL') {

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...
290
                    $url = (string) $locator->attributes('http://www.w3.org/1999/xlink')->href;
291
                    break;
292
                }
293
            }
294
295
            if ($url === null) {
296
                continue;
297
            }
298
299
            $mimetype = (string) $fileNode->attributes()['MIMETYPE'];
300
            if (empty($mimetype)) {
301
                continue;
302
            }
303
304
            $files[$fileId] = [
305
                'url' => $url,
306
                'mimetype' => $mimetype,
307
            ];
308
309
        }
310
        return $files;
311
    }
312
313
    /**
314
     * {@inheritDoc}
315
     * @see \Kitodo\Dlf\Common\Doc::getLogicalStructure()
316
     */
317
    public function getLogicalStructure($id, $recursive = false)
318
    {
319
        $details = [];
320
        // Is the requested logical unit already loaded?
321
        if (
322
            !$recursive
323
            && !empty($this->logicalUnits[$id])
324
        ) {
325
            // Yes. Return it.
326
            return $this->logicalUnits[$id];
327
        } elseif (!empty($id)) {
328
            // Get specified logical unit.
329
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]');
330
        } else {
331
            // Get all logical units at top level.
332
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]/mets:div');
333
        }
334
        if (!empty($divs)) {
335
            if (!$recursive) {
336
                // Get the details for the first xpath hit.
337
                $details = $this->getLogicalStructureInfo($divs[0]);
338
            } else {
339
                // Walk the logical structure recursively and fill the whole table of contents.
340
                foreach ($divs as $div) {
341
                    $this->tableOfContents[] = $this->getLogicalStructureInfo($div, $recursive);
342
                }
343
            }
344
        }
345
        return $details;
346
    }
347
348
    /**
349
     * This gets details about a logical structure element
350
     *
351
     * @access protected
352
     *
353
     * @param \SimpleXMLElement $structure: The logical structure node
354
     * @param bool $recursive: Whether to include the child elements
355
     *
356
     * @return array Array of the element's id, label, type and physical page indexes/mptr link
357
     */
358
    protected function getLogicalStructureInfo(\SimpleXMLElement $structure, $recursive = false)
359
    {
360
        // Get attributes.
361
        foreach ($structure->attributes() as $attribute => $value) {
362
            $attributes[$attribute] = (string) $value;
363
        }
364
        // Load plugin configuration.
365
        $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
366
        // Extract identity information.
367
        $details = [];
368
        $details['id'] = $attributes['ID'];
369
        $details['dmdId'] = (isset($attributes['DMDID']) ? $attributes['DMDID'] : '');
370
        $details['admId'] = (isset($attributes['ADMID']) ? $attributes['ADMID'] : '');
371
        $details['order'] = (isset($attributes['ORDER']) ? $attributes['ORDER'] : '');
372
        $details['label'] = (isset($attributes['LABEL']) ? $attributes['LABEL'] : '');
373
        $details['orderlabel'] = (isset($attributes['ORDERLABEL']) ? $attributes['ORDERLABEL'] : '');
374
        $details['contentIds'] = (isset($attributes['CONTENTIDS']) ? $attributes['CONTENTIDS'] : '');
375
        $details['volume'] = '';
376
        // Set volume information only if no label is set and this is the toplevel structure element.
377
        if (
378
            empty($details['label'])
379
            && $details['id'] == $this->_getToplevelId()
380
        ) {
381
            $metadata = $this->getMetadata($details['id']);
382
            if (!empty($metadata['volume'][0])) {
383
                $details['volume'] = $metadata['volume'][0];
384
            }
385
        }
386
        $details['pagination'] = '';
387
        $details['type'] = $attributes['TYPE'];
388
        // add description for 3D objects
389
        if ($details['type'] == 'object') {
390
            $metadata = $this->getMetadata($details['id']);
391
            $details['description'] = $metadata['description'][0] ?? '';
392
        }
393
        $details['thumbnailId'] = '';
394
        // Structure depth is determined and cached on demand
395
        $details['structureDepth'] = null;
396
        // Load smLinks.
397
        $this->_getSmLinks();
398
        // Load physical structure.
399
        $this->_getPhysicalStructure();
400
        // Get the physical page or external file this structure element is pointing at.
401
        $details['points'] = '';
402
        // Is there a mptr node?
403
        if (count($structure->children('http://www.loc.gov/METS/')->mptr)) {
404
            // Yes. Get the file reference.
405
            $details['points'] = (string) $structure->children('http://www.loc.gov/METS/')->mptr[0]->attributes('http://www.w3.org/1999/xlink')->href;
406
        } elseif (
407
            !empty($this->physicalStructure)
408
            && array_key_exists($details['id'], $this->smLinks['l2p'])
409
        ) {
410
            // Link logical structure to the first corresponding physical page/track.
411
            $details['points'] = max(intval(array_search($this->smLinks['l2p'][$details['id']][0], $this->physicalStructure, true)), 1);
412
            $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
413
            while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
414
                if (!empty($this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['files'][$fileGrpThumb])) {
415
                    $details['thumbnailId'] = $this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['files'][$fileGrpThumb];
416
                    break;
417
                }
418
            }
419
            // Get page/track number of the first page/track related to this structure element.
420
            $details['pagination'] = $this->physicalStructureInfo[$this->smLinks['l2p'][$details['id']][0]]['orderlabel'];
421
        } elseif ($details['id'] == $this->_getToplevelId()) {
422
            // Point to self if this is the toplevel structure.
423
            $details['points'] = 1;
424
            $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
425
            while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
426
                if (
427
                    !empty($this->physicalStructure)
428
                    && !empty($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb])
429
                ) {
430
                    $details['thumbnailId'] = $this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb];
431
                    break;
432
                }
433
            }
434
        }
435
        // Get the files this structure element is pointing at.
436
        $details['files'] = [];
437
        $fileUse = $this->_getFileGrps();
438
        // Get the file representations from fileSec node.
439
        foreach ($structure->children('http://www.loc.gov/METS/')->fptr as $fptr) {
440
            // Check if file has valid @USE attribute.
441
            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

441
            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...
442
                $details['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
443
            }
444
        }
445
        // Keep for later usage.
446
        $this->logicalUnits[$details['id']] = $details;
447
        // Walk the structure recursively? And are there any children of the current element?
448
        if (
449
            $recursive
450
            && count($structure->children('http://www.loc.gov/METS/')->div)
451
        ) {
452
            $details['children'] = [];
453
            foreach ($structure->children('http://www.loc.gov/METS/')->div as $child) {
454
                // Repeat for all children.
455
                $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

455
                $details['children'][] = $this->getLogicalStructureInfo(/** @scrutinizer ignore-type */ $child, true);
Loading history...
456
            }
457
        }
458
        return $details;
459
    }
460
461
    /**
462
     * {@inheritDoc}
463
     * @see \Kitodo\Dlf\Common\Doc::getMetadata()
464
     */
465
    public function getMetadata($id, $cPid = 0)
466
    {
467
        // Make sure $cPid is a non-negative integer.
468
        $cPid = max(intval($cPid), 0);
469
        // If $cPid is not given, try to get it elsewhere.
470
        if (
471
            !$cPid
472
            && ($this->cPid || $this->pid)
473
        ) {
474
            // Retain current PID.
475
            $cPid = ($this->cPid ? $this->cPid : $this->pid);
476
        } elseif (!$cPid) {
477
            $this->logger->warning('Invalid PID ' . $cPid . ' for metadata definitions');
478
            return [];
479
        }
480
        // Get metadata from parsed metadata array if available.
481
        if (
482
            !empty($this->metadataArray[$id])
483
            && $this->metadataArray[0] == $cPid
484
        ) {
485
            return $this->metadataArray[$id];
486
        }
487
        // Initialize metadata array with empty values.
488
        $metadata = [
489
            'title' => [],
490
            'title_sorting' => [],
491
            'description' => [],
492
            'author' => [],
493
            'place' => [],
494
            'year' => [],
495
            'prod_id' => [],
496
            'record_id' => [],
497
            'opac_id' => [],
498
            'union_id' => [],
499
            'urn' => [],
500
            'purl' => [],
501
            'type' => [],
502
            'volume' => [],
503
            'volume_sorting' => [],
504
            'license' => [],
505
            'terms' => [],
506
            'restrictions' => [],
507
            'out_of_print' => [],
508
            'rights_info' => [],
509
            'collection' => [],
510
            'owner' => [],
511
            'mets_label' => [],
512
            'mets_orderlabel' => [],
513
            'document_format' => ['METS'],
514
        ];
515
        $mdIds = $this->getMetadataIds($id);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $mdIds is correct as $this->getMetadataIds($id) targeting Kitodo\Dlf\Common\MetsDocument::getMetadataIds() seems to always return null.

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

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

}

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

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

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

Loading history...
516
        if (empty($mdIds)) {
517
            // There is no metadata section for this structure node.
518
            return [];
519
        }
520
        // Associative array used as set of available section types (dmdSec, techMD, ...)
521
        $hasMetadataSection = [];
522
        // Load available metadata formats and metadata sections.
523
        $this->loadFormats();
524
        $this->_getMdSec();
525
        // Get the structure's type.
526
        if (!empty($this->logicalUnits[$id])) {
527
            $metadata['type'] = [$this->logicalUnits[$id]['type']];
528
        } else {
529
            $struct = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]/@TYPE');
530
            if (!empty($struct)) {
531
                $metadata['type'] = [(string) $struct[0]];
532
            }
533
        }
534
        foreach ($mdIds as $dmdId) {
0 ignored issues
show
Bug introduced by
The expression $mdIds of type void is not traversable.
Loading history...
535
            $mdSectionType = $this->mdSec[$dmdId]['section'];
536
537
            // To preserve behavior of previous Kitodo versions, extract metadata only from first supported dmdSec
538
            // However, we want to extract, for example, all techMD sections (VIDEOMD, AUDIOMD)
539
            if ($mdSectionType === 'dmdSec' && isset($hasMetadataSection['dmdSec'])) {
540
                continue;
541
            }
542
543
            // Is this metadata format supported?
544
            if (!empty($this->formats[$this->mdSec[$dmdId]['type']])) {
545
                if (!empty($this->formats[$this->mdSec[$dmdId]['type']]['class'])) {
546
                    $class = $this->formats[$this->mdSec[$dmdId]['type']]['class'];
547
                    // Get the metadata from class.
548
                    if (
549
                        class_exists($class)
550
                        && ($obj = GeneralUtility::makeInstance($class)) instanceof MetadataInterface
551
                    ) {
552
                        $obj->extractMetadata($this->mdSec[$dmdId]['xml'], $metadata);
553
                    } else {
554
                        $this->logger->warning('Invalid class/method "' . $class . '->extractMetadata()" for metadata format "' . $this->mdSec[$dmdId]['type'] . '"');
555
                    }
556
                }
557
            } else {
558
                $this->logger->notice('Unsupported metadata format "' . $this->mdSec[$dmdId]['type'] . '" in ' . $mdSectionType . ' with @ID "' . $dmdId . '"');
559
                // Continue searching for supported metadata with next @DMDID.
560
                continue;
561
            }
562
            // Get the additional metadata from database.
563
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
564
                ->getQueryBuilderForTable('tx_dlf_metadata');
565
            // Get hidden records, too.
566
            $queryBuilder
567
                ->getRestrictions()
568
                ->removeByType(HiddenRestriction::class);
569
            // Get all metadata with configured xpath and applicable format first.
570
            $resultWithFormat = $queryBuilder
571
                ->select(
572
                    'tx_dlf_metadata.index_name AS index_name',
573
                    'tx_dlf_metadataformat_joins.xpath AS xpath',
574
                    'tx_dlf_metadataformat_joins.xpath_sorting AS xpath_sorting',
575
                    'tx_dlf_metadata.is_sortable AS is_sortable',
576
                    'tx_dlf_metadata.default_value AS default_value',
577
                    'tx_dlf_metadata.format AS format'
578
                )
579
                ->from('tx_dlf_metadata')
580
                ->innerJoin(
581
                    'tx_dlf_metadata',
582
                    'tx_dlf_metadataformat',
583
                    'tx_dlf_metadataformat_joins',
584
                    $queryBuilder->expr()->eq(
585
                        'tx_dlf_metadataformat_joins.parent_id',
586
                        'tx_dlf_metadata.uid'
587
                    )
588
                )
589
                ->innerJoin(
590
                    'tx_dlf_metadataformat_joins',
591
                    'tx_dlf_formats',
592
                    'tx_dlf_formats_joins',
593
                    $queryBuilder->expr()->eq(
594
                        'tx_dlf_formats_joins.uid',
595
                        'tx_dlf_metadataformat_joins.encoded'
596
                    )
597
                )
598
                ->where(
599
                    $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($cPid)),
600
                    $queryBuilder->expr()->eq('tx_dlf_metadata.l18n_parent', 0),
601
                    $queryBuilder->expr()->eq('tx_dlf_metadataformat_joins.pid', intval($cPid)),
602
                    $queryBuilder->expr()->eq('tx_dlf_formats_joins.type', $queryBuilder->createNamedParameter($this->mdSec[$dmdId]['type']))
603
                )
604
                ->execute();
605
            // Get all metadata without a format, but with a default value next.
606
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
607
                ->getQueryBuilderForTable('tx_dlf_metadata');
608
            // Get hidden records, too.
609
            $queryBuilder
610
                ->getRestrictions()
611
                ->removeByType(HiddenRestriction::class);
612
            $resultWithoutFormat = $queryBuilder
613
                ->select(
614
                    'tx_dlf_metadata.index_name AS index_name',
615
                    'tx_dlf_metadata.is_sortable AS is_sortable',
616
                    'tx_dlf_metadata.default_value AS default_value',
617
                    'tx_dlf_metadata.format AS format'
618
                )
619
                ->from('tx_dlf_metadata')
620
                ->where(
621
                    $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($cPid)),
622
                    $queryBuilder->expr()->eq('tx_dlf_metadata.l18n_parent', 0),
623
                    $queryBuilder->expr()->eq('tx_dlf_metadata.format', 0),
624
                    $queryBuilder->expr()->neq('tx_dlf_metadata.default_value', $queryBuilder->createNamedParameter(''))
625
                )
626
                ->execute();
627
            // Merge both result sets.
628
            $allResults = array_merge($resultWithFormat->fetchAll(), $resultWithoutFormat->fetchAll());
629
            // We need a \DOMDocument here, because SimpleXML doesn't support XPath functions properly.
630
            $domNode = dom_import_simplexml($this->mdSec[$dmdId]['xml']);
631
            $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

631
            $domXPath = new \DOMXPath(/** @scrutinizer ignore-type */ $domNode->ownerDocument);
Loading history...
632
            $this->registerNamespaces($domXPath);
633
            // OK, now make the XPath queries.
634
            foreach ($allResults as $resArray) {
635
                // Set metadata field's value(s).
636
                if (
637
                    $resArray['format'] > 0
638
                    && !empty($resArray['xpath'])
639
                    && ($values = $domXPath->evaluate($resArray['xpath'], $domNode))
640
                ) {
641
                    if (
642
                        $values instanceof \DOMNodeList
643
                        && $values->length > 0
644
                    ) {
645
                        $metadata[$resArray['index_name']] = [];
646
                        foreach ($values as $value) {
647
                            $metadata[$resArray['index_name']][] = trim((string) $value->nodeValue);
648
                        }
649
                    } elseif (!($values instanceof \DOMNodeList)) {
650
                        $metadata[$resArray['index_name']] = [trim((string) $values)];
651
                    }
652
                }
653
                // Set default value if applicable.
654
                if (
655
                    empty($metadata[$resArray['index_name']][0])
656
                    && strlen($resArray['default_value']) > 0
657
                ) {
658
                    $metadata[$resArray['index_name']] = [$resArray['default_value']];
659
                }
660
                // Set sorting value if applicable.
661
                if (
662
                    !empty($metadata[$resArray['index_name']])
663
                    && $resArray['is_sortable']
664
                ) {
665
                    if (
666
                        $resArray['format'] > 0
667
                        && !empty($resArray['xpath_sorting'])
668
                        && ($values = $domXPath->evaluate($resArray['xpath_sorting'], $domNode))
669
                    ) {
670
                        if (
671
                            $values instanceof \DOMNodeList
672
                            && $values->length > 0
673
                        ) {
674
                            $metadata[$resArray['index_name'] . '_sorting'][0] = trim((string) $values->item(0)->nodeValue);
675
                        } elseif (!($values instanceof \DOMNodeList)) {
676
                            $metadata[$resArray['index_name'] . '_sorting'][0] = trim((string) $values);
677
                        }
678
                    }
679
                    if (empty($metadata[$resArray['index_name'] . '_sorting'][0])) {
680
                        $metadata[$resArray['index_name'] . '_sorting'][0] = $metadata[$resArray['index_name']][0];
681
                    }
682
                }
683
            }
684
685
            $hasMetadataSection[$mdSectionType] = true;
686
        }
687
        // Set title to empty string if not present.
688
        if (empty($metadata['title'][0])) {
689
            $metadata['title'][0] = '';
690
            $metadata['title_sorting'][0] = '';
691
        }
692
        // Files are not expected to reference a dmdSec
693
        if (isset($this->fileInfos[$id]) || isset($hasMetadataSection['dmdSec'])) {
694
            return $metadata;
695
        } else {
696
            $this->logger->warning('No supported descriptive metadata found for logical structure with @ID "' . $id . '"');
697
            return [];
698
        }
699
    }
700
701
    /**
702
     * Get IDs of (descriptive and administrative) metadata sections
703
     * referenced by node of given $id. The $id may refer to either
704
     * a logical structure node or to a file.
705
     *
706
     * @access protected
707
     * @param string $id: The "@ID" attribute of the file node
708
     * @return void
709
     */
710
    protected function getMetadataIds($id)
711
    {
712
        // ­Load amdSecChildIds concordance
713
        $this->_getMdSec();
714
        $this->_getFileInfos();
715
716
        // Get DMDID and ADMID of logical structure node
717
        if (!empty($this->logicalUnits[$id])) {
718
            $dmdIds = $this->logicalUnits[$id]['dmdId'] ?? '';
719
            $admIds = $this->logicalUnits[$id]['admId'] ?? '';
720
        } else {
721
            $mdSec = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $id . '"]')[0];
722
            if ($mdSec) {
0 ignored issues
show
introduced by
$mdSec is of type SimpleXMLElement, thus it always evaluated to true.
Loading history...
723
                $dmdIds = (string) $mdSec->attributes()->DMDID;
724
                $admIds = (string) $mdSec->attributes()->ADMID;
725
            } else if (isset($this->fileInfos[$id])) {
726
                $dmdIds = $this->fileInfos[$id]['dmdId'];
727
                $admIds = $this->fileInfos[$id]['admId'];
728
            } else {
729
                $dmdIds = '';
730
                $admIds = '';
731
            }
732
        }
733
734
        // Handle multiple DMDIDs/ADMIDs
735
        $allMdIds = explode(' ', $dmdIds);
736
737
        foreach (explode(' ', $admIds) as $admId) {
738
            if (isset($this->mdSec[$admId])) {
739
                // $admId references an actual metadata section such as techMD
740
                $allMdIds[] = $admId;
741
            } elseif (isset($this->amdSecChildIds[$admId])) {
742
                // $admId references a <mets:amdSec> element. Resolve child elements.
743
                foreach ($this->amdSecChildIds[$admId] as $childId) {
0 ignored issues
show
Bug introduced by
The expression $this->amdSecChildIds[$admId] of type string is not traversable.
Loading history...
744
                    $allMdIds[] = $childId;
745
                }
746
            }
747
        }
748
749
        return array_filter($allMdIds, function ($element) {
0 ignored issues
show
Bug Best Practice introduced by
The expression return array_filter($all...ion(...) { /* ... */ }) returns the type array which is incompatible with the documented return type void.
Loading history...
750
            return !empty($element);
751
        });
752
    }
753
754
    /**
755
     * {@inheritDoc}
756
     * @see \Kitodo\Dlf\Common\Doc::getFullText()
757
     */
758
    public function getFullText($id)
759
    {
760
        $fullText = '';
761
762
        // Load fileGrps and check for full text files.
763
        $this->_getFileGrps();
764
        if ($this->hasFulltext) {
765
            $fullText = $this->getFullTextFromXml($id);
766
        }
767
        return $fullText;
768
    }
769
770
    /**
771
     * {@inheritDoc}
772
     * @see Doc::getStructureDepth()
773
     */
774
    public function getStructureDepth($logId)
775
    {
776
        if (isset($this->logicalUnits[$logId]['structureDepth'])) {
777
            return $this->logicalUnits[$logId]['structureDepth'];
778
        }
779
780
        $ancestors = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $logId . '"]/ancestor::*');
781
        if (!empty($ancestors)) {
782
            $structureDepth = count($ancestors);
783
        } else {
784
            $structureDepth = 0;
785
        }
786
787
        // NOTE: Don't just set $this->logicalUnits[$logId] here, because it may not yet be loaded
788
        if (isset($this->logicalUnits[$logId])) {
789
            $this->logicalUnits[$logId]['structureDepth'] = $structureDepth;
790
        }
791
792
        return $structureDepth;
793
    }
794
795
    /**
796
     * {@inheritDoc}
797
     * @see \Kitodo\Dlf\Common\Doc::init()
798
     */
799
    protected function init($location)
800
    {
801
        $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(get_class($this));
802
        // Get METS node from XML file.
803
        $this->registerNamespaces($this->xml);
804
        $mets = $this->xml->xpath('//mets:mets');
805
        if (!empty($mets)) {
806
            $this->mets = $mets[0];
807
            // Register namespaces.
808
            $this->registerNamespaces($this->mets);
809
        } else {
810
            if (!empty($location)) {
811
                $this->logger->error('No METS part found in document with location "' . $location . '".');
812
            } else if (!empty($this->recordId)) {
813
                $this->logger->error('No METS part found in document with recordId "' . $this->recordId . '".');
814
            } else {
815
                $this->logger->error('No METS part found in current document.');
816
            }
817
        }
818
    }
819
820
    /**
821
     * {@inheritDoc}
822
     * @see \Kitodo\Dlf\Common\Doc::loadLocation()
823
     */
824
    protected function loadLocation($location)
825
    {
826
        $fileResource = Helper::getUrl($location);
827
        if ($fileResource !== false) {
828
            $xml = Helper::getXmlFileAsString($fileResource);
829
            // Set some basic properties.
830
            if ($xml !== false) {
831
                $this->xml = $xml;
832
                return true;
833
            }
834
        }
835
        $this->logger->error('Could not load XML file from "' . $location . '"');
836
        return false;
837
    }
838
839
    /**
840
     * {@inheritDoc}
841
     * @see \Kitodo\Dlf\Common\Doc::ensureHasFulltextIsSet()
842
     */
843
    protected function ensureHasFulltextIsSet()
844
    {
845
        // Are the fileGrps already loaded?
846
        if (!$this->fileGrpsLoaded) {
847
            $this->_getFileGrps();
848
        }
849
    }
850
851
    /**
852
     * {@inheritDoc}
853
     * @see Doc::setPreloadedDocument()
854
     */
855
    protected function setPreloadedDocument($preloadedDocument)
856
    {
857
858
        if ($preloadedDocument instanceof \SimpleXMLElement) {
859
            $this->xml = $preloadedDocument;
860
            return true;
861
        }
862
        return false;
863
    }
864
865
    /**
866
     * {@inheritDoc}
867
     * @see Doc::getDocument()
868
     */
869
    protected function getDocument()
870
    {
871
        return $this->mets;
872
    }
873
874
    /**
875
     * This builds an array of the document's metadata sections
876
     *
877
     * @access protected
878
     *
879
     * @return array Array of metadata sections with their IDs as array key
880
     */
881
    protected function _getMdSec()
882
    {
883
        if (!$this->mdSecLoaded) {
884
            $this->loadFormats();
885
886
            foreach ($this->mets->xpath('./mets:dmdSec') as $dmdSecTag) {
887
                $dmdSec = $this->processMdSec($dmdSecTag);
888
889
                if ($dmdSec !== null) {
890
                    $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...
891
                    $this->dmdSec[$dmdSec['id']] = $dmdSec;
892
                }
893
            }
894
895
            foreach ($this->mets->xpath('./mets:amdSec') as $amdSecTag) {
896
                $childIds = [];
897
898
                foreach ($amdSecTag->children('http://www.loc.gov/METS/') as $mdSecTag) {
899
                    if (!in_array($mdSecTag->getName(), self::ALLOWED_AMD_SEC)) {
900
                        continue;
901
                    }
902
903
                    // TODO: Should we check that the format may occur within this type (e.g., to ignore VIDEOMD within rightsMD)?
904
                    $mdSec = $this->processMdSec($mdSecTag);
905
906
                    if ($mdSec !== null) {
907
                        $this->mdSec[$mdSec['id']] = $mdSec;
908
909
                        $childIds[] = $mdSec['id'];
910
                    }
911
                }
912
913
                $amdSecId = (string) $amdSecTag->attributes()->ID;
914
                if (!empty($amdSecId)) {
915
                    $this->amdSecChildIds[$amdSecId] = $childIds;
916
                }
917
            }
918
919
            $this->mdSecLoaded = true;
920
        }
921
        return $this->mdSec;
922
    }
923
924
    protected function _getDmdSec()
925
    {
926
        $this->_getMdSec();
927
        return $this->dmdSec;
928
    }
929
930
    /**
931
     * Processes an element of METS `mdSecType`.
932
     *
933
     * @access protected
934
     *
935
     * @param \SimpleXMLElement $element
936
     *
937
     * @return array|null The processed metadata section
938
     */
939
    protected function processMdSec($element)
940
    {
941
        $mdId = (string) $element->attributes()->ID;
942
        if (empty($mdId)) {
943
            return null;
944
        }
945
946
        $this->registerNamespaces($element);
947
        if ($type = $element->xpath('./mets:mdWrap[not(@MDTYPE="OTHER")]/@MDTYPE')) {
948
            if (!empty($this->formats[(string) $type[0]])) {
949
                $type = (string) $type[0];
950
                $xml = $element->xpath('./mets:mdWrap[@MDTYPE="' . $type . '"]/mets:xmlData/' . strtolower($type) . ':' . $this->formats[$type]['rootElement']);
951
            }
952
        } elseif ($type = $element->xpath('./mets:mdWrap[@MDTYPE="OTHER"]/@OTHERMDTYPE')) {
953
            if (!empty($this->formats[(string) $type[0]])) {
954
                $type = (string) $type[0];
955
                $xml = $element->xpath('./mets:mdWrap[@MDTYPE="OTHER"][@OTHERMDTYPE="' . $type . '"]/mets:xmlData/' . strtolower($type) . ':' . $this->formats[$type]['rootElement']);
956
            }
957
        }
958
959
        if (empty($xml)) {
960
            return null;
961
        }
962
963
        $this->registerNamespaces($xml[0]);
964
965
        return [
966
            'id' => $mdId,
967
            'section' => $element->getName(),
968
            'type' => $type,
969
            '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...
970
        ];
971
    }
972
973
    /**
974
     * This builds the file ID -> USE concordance
975
     *
976
     * @access protected
977
     *
978
     * @return array Array of file use groups with file IDs
979
     */
980
    protected function _getFileGrps()
981
    {
982
        if (!$this->fileGrpsLoaded) {
983
            // Get configured USE attributes.
984
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
985
            $useGrps = GeneralUtility::trimExplode(',', $extConf['fileGrpImages']);
986
            if (!empty($extConf['fileGrpThumbs'])) {
987
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']));
988
            }
989
            if (!empty($extConf['fileGrpDownload'])) {
990
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpDownload']));
991
            }
992
            if (!empty($extConf['fileGrpFulltext'])) {
993
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpFulltext']));
994
            }
995
            if (!empty($extConf['fileGrpAudio'])) {
996
                $useGrps = array_merge($useGrps, GeneralUtility::trimExplode(',', $extConf['fileGrpAudio']));
997
            }
998
            // Get all file groups.
999
            $fileGrps = $this->mets->xpath('./mets:fileSec/mets:fileGrp');
1000
            if (!empty($fileGrps)) {
1001
                // Build concordance for configured USE attributes.
1002
                foreach ($fileGrps as $fileGrp) {
1003
                    if (in_array((string) $fileGrp['USE'], $useGrps)) {
1004
                        foreach ($fileGrp->children('http://www.loc.gov/METS/')->file as $file) {
1005
                            $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

1005
                            $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...
1006
                            $this->fileGrps[$fileId] = (string) $fileGrp['USE'];
1007
                            $this->fileInfos[$fileId] = [
0 ignored issues
show
Bug introduced by
The property fileInfos is declared read-only in Kitodo\Dlf\Common\MetsDocument.
Loading history...
1008
                                'fileGrp' => (string) $fileGrp['USE'],
1009
                                'admId' => (string) $file->attributes()->ADMID,
1010
                                'dmdId' => (string) $file->attributes()->DMDID,
1011
                            ];
1012
                        }
1013
                    }
1014
                }
1015
            }
1016
            // Are there any fulltext files available?
1017
            if (
1018
                !empty($extConf['fileGrpFulltext'])
1019
                && array_intersect(GeneralUtility::trimExplode(',', $extConf['fileGrpFulltext']), $this->fileGrps) !== []
1020
            ) {
1021
                $this->hasFulltext = true;
1022
            }
1023
            $this->fileGrpsLoaded = true;
1024
        }
1025
        return $this->fileGrps;
1026
    }
1027
1028
    /**
1029
     *
1030
     * @access protected
1031
     * @return array
1032
     */
1033
    protected function _getFileInfos()
1034
    {
1035
        $this->_getFileGrps();
1036
        return $this->fileInfos;
1037
    }
1038
1039
    /**
1040
     * {@inheritDoc}
1041
     * @see \Kitodo\Dlf\Common\Doc::prepareMetadataArray()
1042
     */
1043
    protected function prepareMetadataArray($cPid)
1044
    {
1045
        $ids = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID]/@ID');
1046
        // Get all logical structure nodes with metadata.
1047
        if (!empty($ids)) {
1048
            foreach ($ids as $id) {
1049
                $this->metadataArray[(string) $id] = $this->getMetadata((string) $id, $cPid);
1050
            }
1051
        }
1052
        // Set current PID for metadata definitions.
1053
    }
1054
1055
    /**
1056
     * This returns $this->mets via __get()
1057
     *
1058
     * @access protected
1059
     *
1060
     * @return \SimpleXMLElement The XML's METS part as \SimpleXMLElement object
1061
     */
1062
    protected function _getMets()
1063
    {
1064
        return $this->mets;
1065
    }
1066
1067
    /**
1068
     * {@inheritDoc}
1069
     * @see \Kitodo\Dlf\Common\Doc::_getPhysicalStructure()
1070
     */
1071
    protected function _getPhysicalStructure()
1072
    {
1073
        // Is there no physical structure array yet?
1074
        if (!$this->physicalStructureLoaded) {
1075
            // Does the document have a structMap node of type "PHYSICAL"?
1076
            $elementNodes = $this->mets->xpath('./mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div');
1077
            if (!empty($elementNodes)) {
1078
                // Get file groups.
1079
                $fileUse = $this->_getFileGrps();
1080
                // Get the physical sequence's metadata.
1081
                $physNode = $this->mets->xpath('./mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]');
1082
                $physSeq[0] = (string) $physNode[0]['ID'];
1083
                $this->physicalStructureInfo[$physSeq[0]]['id'] = (string) $physNode[0]['ID'];
1084
                $this->physicalStructureInfo[$physSeq[0]]['dmdId'] = (isset($physNode[0]['DMDID']) ? (string) $physNode[0]['DMDID'] : '');
1085
                $this->physicalStructureInfo[$physSeq[0]]['admId'] = (isset($physNode[0]['ADMID']) ? (string) $physNode[0]['ADMID'] : '');
1086
                $this->physicalStructureInfo[$physSeq[0]]['order'] = (isset($physNode[0]['ORDER']) ? (string) $physNode[0]['ORDER'] : '');
1087
                $this->physicalStructureInfo[$physSeq[0]]['label'] = (isset($physNode[0]['LABEL']) ? (string) $physNode[0]['LABEL'] : '');
1088
                $this->physicalStructureInfo[$physSeq[0]]['orderlabel'] = (isset($physNode[0]['ORDERLABEL']) ? (string) $physNode[0]['ORDERLABEL'] : '');
1089
                $this->physicalStructureInfo[$physSeq[0]]['type'] = (string) $physNode[0]['TYPE'];
1090
                $this->physicalStructureInfo[$physSeq[0]]['contentIds'] = (isset($physNode[0]['CONTENTIDS']) ? (string) $physNode[0]['CONTENTIDS'] : '');
1091
                // Get the file representations from fileSec node.
1092
                foreach ($physNode[0]->children('http://www.loc.gov/METS/')->fptr as $fptr) {
1093
                    // Check if file has valid @USE attribute.
1094
                    if (!empty($fileUse[(string) $fptr->attributes()->FILEID])) {
1095
                        $this->physicalStructureInfo[$physSeq[0]]['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
1096
                    }
1097
                }
1098
                // Build the physical elements' array from the physical structMap node.
1099
                foreach ($elementNodes as $elementNode) {
1100
                    $elements[(int) $elementNode['ORDER']] = (string) $elementNode['ID'];
1101
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['id'] = (string) $elementNode['ID'];
1102
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['dmdId'] = (isset($elementNode['DMDID']) ? (string) $elementNode['DMDID'] : '');
1103
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['admId'] = (isset($elementNode['ADMID']) ? (string) $elementNode['ADMID'] : '');
1104
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['order'] = (isset($elementNode['ORDER']) ? (string) $elementNode['ORDER'] : '');
1105
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['label'] = (isset($elementNode['LABEL']) ? (string) $elementNode['LABEL'] : '');
1106
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['orderlabel'] = (isset($elementNode['ORDERLABEL']) ? (string) $elementNode['ORDERLABEL'] : '');
1107
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['type'] = (string) $elementNode['TYPE'];
1108
                    $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['contentIds'] = (isset($elementNode['CONTENTIDS']) ? (string) $elementNode['CONTENTIDS'] : '');
1109
                    // Get the file representations from fileSec node.
1110
                    foreach ($elementNode->children('http://www.loc.gov/METS/')->fptr as $fptr) {
1111
                        // Check if file has valid @USE attribute.
1112
                        if (!empty($fileUse[(string) $fptr->attributes()->FILEID])) {
1113
                            $this->physicalStructureInfo[$elements[(int) $elementNode['ORDER']]]['files'][$fileUse[(string) $fptr->attributes()->FILEID]] = (string) $fptr->attributes()->FILEID;
1114
                        }
1115
                    }
1116
                }
1117
                // Sort array by keys (= @ORDER).
1118
                if (ksort($elements)) {
1119
                    // Set total number of pages/tracks.
1120
                    $this->numPages = count($elements);
1121
                    // Merge and re-index the array to get nice numeric indexes.
1122
                    $this->physicalStructure = array_merge($physSeq, $elements);
1123
                }
1124
            }
1125
            $this->physicalStructureLoaded = true;
1126
        }
1127
        return $this->physicalStructure;
1128
    }
1129
1130
    /**
1131
     * {@inheritDoc}
1132
     * @see \Kitodo\Dlf\Common\Doc::_getSmLinks()
1133
     */
1134
    protected function _getSmLinks()
1135
    {
1136
        if (!$this->smLinksLoaded) {
1137
            $smLinks = $this->mets->xpath('./mets:structLink/mets:smLink');
1138
            if (!empty($smLinks)) {
1139
                foreach ($smLinks as $smLink) {
1140
                    $this->smLinks['l2p'][(string) $smLink->attributes('http://www.w3.org/1999/xlink')->from][] = (string) $smLink->attributes('http://www.w3.org/1999/xlink')->to;
1141
                    $this->smLinks['p2l'][(string) $smLink->attributes('http://www.w3.org/1999/xlink')->to][] = (string) $smLink->attributes('http://www.w3.org/1999/xlink')->from;
1142
                }
1143
            }
1144
            $this->smLinksLoaded = true;
1145
        }
1146
        return $this->smLinks;
1147
    }
1148
1149
    /**
1150
     * {@inheritDoc}
1151
     * @see \Kitodo\Dlf\Common\Doc::_getThumbnail()
1152
     */
1153
    protected function _getThumbnail($forceReload = false)
1154
    {
1155
        if (
1156
            !$this->thumbnailLoaded
1157
            || $forceReload
1158
        ) {
1159
            // Retain current PID.
1160
            $cPid = ($this->cPid ? $this->cPid : $this->pid);
1161
            if (!$cPid) {
1162
                $this->logger->error('Invalid PID ' . $cPid . ' for structure definitions');
1163
                $this->thumbnailLoaded = true;
1164
                return $this->thumbnail;
1165
            }
1166
            // Load extension configuration.
1167
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
1168
            if (empty($extConf['fileGrpThumbs'])) {
1169
                $this->logger->warning('No fileGrp for thumbnails specified');
1170
                $this->thumbnailLoaded = true;
1171
                return $this->thumbnail;
1172
            }
1173
            $strctId = $this->_getToplevelId();
1174
            $metadata = $this->getTitledata($cPid);
1175
1176
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1177
                ->getQueryBuilderForTable('tx_dlf_structures');
1178
1179
            // Get structure element to get thumbnail from.
1180
            $result = $queryBuilder
1181
                ->select('tx_dlf_structures.thumbnail AS thumbnail')
1182
                ->from('tx_dlf_structures')
1183
                ->where(
1184
                    $queryBuilder->expr()->eq('tx_dlf_structures.pid', intval($cPid)),
1185
                    $queryBuilder->expr()->eq('tx_dlf_structures.index_name', $queryBuilder->expr()->literal($metadata['type'][0])),
1186
                    Helper::whereExpression('tx_dlf_structures')
1187
                )
1188
                ->setMaxResults(1)
1189
                ->execute();
1190
1191
            $allResults = $result->fetchAll();
1192
1193
            if (count($allResults) == 1) {
1194
                $resArray = $allResults[0];
1195
                // Get desired thumbnail structure if not the toplevel structure itself.
1196
                if (!empty($resArray['thumbnail'])) {
1197
                    $strctType = Helper::getIndexNameFromUid($resArray['thumbnail'], 'tx_dlf_structures', $cPid);
1198
                    // Check if this document has a structure element of the desired type.
1199
                    $strctIds = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@TYPE="' . $strctType . '"]/@ID');
1200
                    if (!empty($strctIds)) {
1201
                        $strctId = (string) $strctIds[0];
1202
                    }
1203
                }
1204
                // Load smLinks.
1205
                $this->_getSmLinks();
1206
                // Get thumbnail location.
1207
                $fileGrpsThumb = GeneralUtility::trimExplode(',', $extConf['fileGrpThumbs']);
1208
                while ($fileGrpThumb = array_shift($fileGrpsThumb)) {
1209
                    if (
1210
                        $this->_getPhysicalStructure()
1211
                        && !empty($this->smLinks['l2p'][$strctId])
1212
                        && !empty($this->physicalStructureInfo[$this->smLinks['l2p'][$strctId][0]]['files'][$fileGrpThumb])
1213
                    ) {
1214
                        $this->thumbnail = $this->getFileLocation($this->physicalStructureInfo[$this->smLinks['l2p'][$strctId][0]]['files'][$fileGrpThumb]);
1215
                        break;
1216
                    } elseif (!empty($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb])) {
1217
                        $this->thumbnail = $this->getFileLocation($this->physicalStructureInfo[$this->physicalStructure[1]]['files'][$fileGrpThumb]);
1218
                        break;
1219
                    }
1220
                }
1221
            } else {
1222
                $this->logger->error('No structure of type "' . $metadata['type'][0] . '" found in database');
1223
            }
1224
            $this->thumbnailLoaded = true;
1225
        }
1226
        return $this->thumbnail;
1227
    }
1228
1229
    /**
1230
     * {@inheritDoc}
1231
     * @see \Kitodo\Dlf\Common\Doc::_getToplevelId()
1232
     */
1233
    protected function _getToplevelId()
1234
    {
1235
        if (empty($this->toplevelId)) {
1236
            // Get all logical structure nodes with metadata, but without associated METS-Pointers.
1237
            $divs = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID and not(./mets:mptr)]');
1238
            if (!empty($divs)) {
1239
                // Load smLinks.
1240
                $this->_getSmLinks();
1241
                foreach ($divs as $div) {
1242
                    $id = (string) $div['ID'];
1243
                    // Are there physical structure nodes for this logical structure?
1244
                    if (array_key_exists($id, $this->smLinks['l2p'])) {
1245
                        // Yes. That's what we're looking for.
1246
                        $this->toplevelId = $id;
1247
                        break;
1248
                    } elseif (empty($this->toplevelId)) {
1249
                        // No. Remember this anyway, but keep looking for a better one.
1250
                        $this->toplevelId = $id;
1251
                    }
1252
                }
1253
            }
1254
        }
1255
        return $this->toplevelId;
1256
    }
1257
1258
    /**
1259
     * Try to determine URL of parent document.
1260
     *
1261
     * @return string|null
1262
     */
1263
    public function _getParentHref()
1264
    {
1265
        if ($this->parentHref === null) {
1266
            $this->parentHref = '';
0 ignored issues
show
Bug introduced by
The property parentHref is declared read-only in Kitodo\Dlf\Common\MetsDocument.
Loading history...
1267
1268
            // Get the closest ancestor of the current document which has a MPTR child.
1269
            $parentMptr = $this->mets->xpath('./mets:structMap[@TYPE="LOGICAL"]//mets:div[@ID="' . $this->toplevelId . '"]/ancestor::mets:div[./mets:mptr][1]/mets:mptr');
1270
            if (!empty($parentMptr)) {
1271
                $this->parentHref = (string) $parentMptr[0]->attributes('http://www.w3.org/1999/xlink')->href;
1272
            }
1273
        }
1274
1275
        return $this->parentHref;
1276
    }
1277
1278
    /**
1279
     * This magic method is executed prior to any serialization of the object
1280
     * @see __wakeup()
1281
     *
1282
     * @access public
1283
     *
1284
     * @return array Properties to be serialized
1285
     */
1286
    public function __sleep()
1287
    {
1288
        // \SimpleXMLElement objects can't be serialized, thus save the XML as string for serialization
1289
        $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...
1290
        return ['uid', 'pid', 'recordId', 'parentId', 'asXML'];
1291
    }
1292
1293
    /**
1294
     * This magic method is used for setting a string value for the object
1295
     *
1296
     * @access public
1297
     *
1298
     * @return string String representing the METS object
1299
     */
1300
    public function __toString()
1301
    {
1302
        $xml = new \DOMDocument('1.0', 'utf-8');
1303
        $xml->appendChild($xml->importNode(dom_import_simplexml($this->mets), true));
1304
        $xml->formatOutput = true;
1305
        return $xml->saveXML();
1306
    }
1307
1308
    /**
1309
     * This magic method is executed after the object is deserialized
1310
     * @see __sleep()
1311
     *
1312
     * @access public
1313
     *
1314
     * @return void
1315
     */
1316
    public function __wakeup()
1317
    {
1318
        $xml = Helper::getXmlFileAsString($this->asXML);
1319
        if ($xml !== false) {
1320
            $this->asXML = '';
1321
            $this->xml = $xml;
1322
            // Rebuild the unserializable properties.
1323
            $this->init('');
1324
        } else {
1325
            $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(static::class);
1326
            $this->logger->error('Could not load XML after deserialization');
1327
        }
1328
    }
1329
}
1330