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 (#650)
by
unknown
03:04
created

Document::save()   F

Complexity

Conditions 37
Paths > 20000

Size

Total Lines 306
Code Lines 218

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 218
dl 0
loc 306
rs 0
c 0
b 0
f 0
cc 37
nc 4534282
nop 3

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
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\Document;
14
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\Indexer;
17
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
18
use TYPO3\CMS\Core\Database\ConnectionPool;
19
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
20
use TYPO3\CMS\Core\Log\LogManager;
21
use TYPO3\CMS\Core\Utility\GeneralUtility;
22
use TYPO3\CMS\Core\Utility\MathUtility;
23
use Ubl\Iiif\Presentation\Common\Model\Resources\IiifResourceInterface;
24
use Ubl\Iiif\Tools\IiifHelper;
25
26
/**
27
 * Document class for the 'dlf' extension
28
 *
29
 * @author Sebastian Meyer <[email protected]>
30
 * @author Henrik Lochmann <[email protected]>
31
 * @package TYPO3
32
 * @subpackage dlf
33
 * @access public
34
 * @property int $cPid This holds the PID for the configuration
35
 * @property-read string $location This holds the documents location
36
 * @property-read array $metadataArray This holds the documents' parsed metadata array
37
 * @property-read int $numPages The holds the total number of pages
38
 * @property-read int $parentId This holds the UID of the parent document or zero if not multi-volumed
39
 * @property-read array $physicalStructure This holds the physical structure
40
 * @property-read array $physicalStructureInfo This holds the physical structure metadata
41
 * @property-read int $pid This holds the PID of the document or zero if not in database
42
 * @property-read bool $ready Is the document instantiated successfully?
43
 * @property-read string $recordId The METS file's / IIIF manifest's record identifier
44
 * @property-read int $rootId This holds the UID of the root document or zero if not multi-volumed
45
 * @property-read array $smLinks This holds the smLinks between logical and physical structMap
46
 * @property-read array $tableOfContents This holds the logical structure
47
 * @property-read string $thumbnail This holds the document's thumbnail location
48
 * @property-read string $toplevelId This holds the toplevel structure's @ID (METS) or the manifest's @id (IIIF)
49
 * @property-read mixed $uid This holds the UID or the URL of the document
50
 * @abstract
51
 */
52
abstract class Document
53
{
54
    /**
55
     * This holds the logger
56
     *
57
     * @var LogManager
58
     * @access protected
59
     */
60
    protected $logger;
61
62
    /**
63
     * This holds the PID for the configuration
64
     *
65
     * @var int
66
     * @access protected
67
     */
68
    protected $cPid = 0;
69
70
    /**
71
     * The extension key
72
     *
73
     * @var string
74
     * @access public
75
     */
76
    public static $extKey = 'dlf';
77
78
    /**
79
     * This holds the configuration for all supported metadata encodings
80
     * @see loadFormats()
81
     *
82
     * @var array
83
     * @access protected
84
     */
85
    protected $formats = [
86
        'OAI' => [
87
            'rootElement' => 'OAI-PMH',
88
            'namespaceURI' => 'http://www.openarchives.org/OAI/2.0/',
89
        ],
90
        'METS' => [
91
            'rootElement' => 'mets',
92
            'namespaceURI' => 'http://www.loc.gov/METS/',
93
        ],
94
        'XLINK' => [
95
            'rootElement' => 'xlink',
96
            'namespaceURI' => 'http://www.w3.org/1999/xlink',
97
        ]
98
    ];
99
100
    /**
101
     * Are the available metadata formats loaded?
102
     * @see $formats
103
     *
104
     * @var bool
105
     * @access protected
106
     */
107
    protected $formatsLoaded = false;
108
109
    /**
110
     * Last searched logical and physical page
111
     *
112
     * @var array
113
     * @access protected
114
     */
115
    protected $lastSearchedPhysicalPage = ['logicalPage' => null, 'physicalPage' => null];
116
117
    /**
118
     * This holds the documents location
119
     *
120
     * @var string
121
     * @access protected
122
     */
123
    protected $location = '';
124
125
    /**
126
     * This holds the logical units
127
     *
128
     * @var array
129
     * @access protected
130
     */
131
    protected $logicalUnits = [];
132
133
    /**
134
     * This holds the documents' parsed metadata array with their corresponding
135
     * structMap//div's ID (METS) or Range / Manifest / Sequence ID (IIIF) as array key
136
     *
137
     * @var array
138
     * @access protected
139
     */
140
    protected $metadataArray = [];
141
142
    /**
143
     * Is the metadata array loaded?
144
     * @see $metadataArray
145
     *
146
     * @var bool
147
     * @access protected
148
     */
149
    protected $metadataArrayLoaded = false;
150
151
    /**
152
     * The holds the total number of pages
153
     *
154
     * @var int
155
     * @access protected
156
     */
157
    protected $numPages = 0;
158
159
    /**
160
     * This holds the UID of the parent document or zero if not multi-volumed
161
     *
162
     * @var int
163
     * @access protected
164
     */
165
    protected $parentId = 0;
166
167
    /**
168
     * This holds the physical structure
169
     *
170
     * @var array
171
     * @access protected
172
     */
173
    protected $physicalStructure = [];
174
175
    /**
176
     * This holds the physical structure metadata
177
     *
178
     * @var array
179
     * @access protected
180
     */
181
    protected $physicalStructureInfo = [];
182
183
    /**
184
     * Is the physical structure loaded?
185
     * @see $physicalStructure
186
     *
187
     * @var bool
188
     * @access protected
189
     */
190
    protected $physicalStructureLoaded = false;
191
192
    /**
193
     * This holds the PID of the document or zero if not in database
194
     *
195
     * @var int
196
     * @access protected
197
     */
198
    protected $pid = 0;
199
200
    /**
201
     * Is the document instantiated successfully?
202
     *
203
     * @var bool
204
     * @access protected
205
     */
206
    protected $ready = false;
207
208
    /**
209
     * The METS file's / IIIF manifest's record identifier
210
     *
211
     * @var string
212
     * @access protected
213
     */
214
    protected $recordId;
215
216
    /**
217
     * This holds the singleton object of the document
218
     *
219
     * @var array (\Kitodo\Dlf\Common\Document\Document)
220
     * @static
221
     * @access protected
222
     */
223
    protected static $registry = [];
224
225
    /**
226
     * This holds the UID of the root document or zero if not multi-volumed
227
     *
228
     * @var int
229
     * @access protected
230
     */
231
    protected $rootId = 0;
232
233
    /**
234
     * Is the root id loaded?
235
     * @see $rootId
236
     *
237
     * @var bool
238
     * @access protected
239
     */
240
    protected $rootIdLoaded = false;
241
242
    /**
243
     * This holds the smLinks between logical and physical structMap
244
     *
245
     * @var array
246
     * @access protected
247
     */
248
    protected $smLinks = ['l2p' => [], 'p2l' => []];
249
250
    /**
251
     * Are the smLinks loaded?
252
     * @see $smLinks
253
     *
254
     * @var bool
255
     * @access protected
256
     */
257
    protected $smLinksLoaded = false;
258
259
    /**
260
     * This holds the logical structure
261
     *
262
     * @var array
263
     * @access protected
264
     */
265
    protected $tableOfContents = [];
266
267
    /**
268
     * Is the table of contents loaded?
269
     * @see $tableOfContents
270
     *
271
     * @var bool
272
     * @access protected
273
     */
274
    protected $tableOfContentsLoaded = false;
275
276
    /**
277
     * This holds the document's thumbnail location
278
     *
279
     * @var string
280
     * @access protected
281
     */
282
    protected $thumbnail = '';
283
284
    /**
285
     * Is the document's thumbnail location loaded?
286
     * @see $thumbnail
287
     *
288
     * @var bool
289
     * @access protected
290
     */
291
    protected $thumbnailLoaded = false;
292
293
    /**
294
     * This holds the toplevel structure's @ID (METS) or the manifest's @id (IIIF)
295
     *
296
     * @var string
297
     * @access protected
298
     */
299
    protected $toplevelId = '';
300
301
    /**
302
     * This holds the UID or the URL of the document
303
     *
304
     * @var mixed
305
     * @access protected
306
     */
307
    protected $uid = 0;
308
309
    /**
310
     * This holds the whole XML file as \SimpleXMLElement object
311
     *
312
     * @var \SimpleXMLElement
313
     * @access protected
314
     */
315
    protected $xml;
316
317
    /**
318
     * This clears the static registry to prevent memory exhaustion
319
     *
320
     * @access public
321
     *
322
     * @static
323
     *
324
     * @return void
325
     */
326
    public static function clearRegistry()
327
    {
328
        // Reset registry array.
329
        self::$registry = [];
330
    }
331
332
    /**
333
     * This is a singleton class, thus an instance must be created by this method
334
     *
335
     * @access public
336
     *
337
     * @static
338
     *
339
     * @param mixed $uid: The unique identifier of the document to parse, the URL of XML file or the IRI of the IIIF resource
340
     * @param int $pid: If > 0, then only document with this PID gets loaded
341
     * @param bool $forceReload: Force reloading the document instead of returning the cached instance
342
     *
343
     * @return \Kitodo\Dlf\Common\Document\Document Instance of this class, either MetsDocument or IiifManifest
344
     */
345
    public static function &getInstance($uid, $pid = 0, $forceReload = false)
346
    {
347
        // Sanitize input.
348
        $pid = max(intval($pid), 0);
349
        if (!$forceReload) {
350
            $regObj = Helper::digest($uid);
351
            if (
352
                is_object(self::$registry[$regObj])
353
                && self::$registry[$regObj] instanceof self
354
            ) {
355
                // Check if instance has given PID.
356
                if (
357
                    !$pid
358
                    || !self::$registry[$regObj]->pid
359
                    || $pid == self::$registry[$regObj]->pid
360
                ) {
361
                    // Return singleton instance if available.
362
                    return self::$registry[$regObj];
363
                }
364
            } else {
365
                // Check the user's session...
366
                $sessionData = Helper::loadFromSession(get_called_class());
367
                if (
368
                    is_object($sessionData[$regObj])
369
                    && $sessionData[$regObj] instanceof self
370
                ) {
371
                    // Check if instance has given PID.
372
                    if (
373
                        !$pid
374
                        || !$sessionData[$regObj]->pid
375
                        || $pid == $sessionData[$regObj]->pid
376
                    ) {
377
                        // ...and restore registry.
378
                        self::$registry[$regObj] = $sessionData[$regObj];
379
                        return self::$registry[$regObj];
380
                    }
381
                }
382
            }
383
        }
384
        // Create new instance depending on format (METS or IIIF) ...
385
        $instance = null;
386
        $documentFormat = null;
387
        $xml = null;
388
        $iiif = null;
389
        // Try to get document format from database
390
        if (MathUtility::canBeInterpretedAsInteger($uid)) {
391
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
392
                ->getQueryBuilderForTable('tx_dlf_documents');
393
394
            $queryBuilder
395
                ->select(
396
                    'tx_dlf_documents.location AS location',
397
                    'tx_dlf_documents.document_format AS document_format'
398
                )
399
                ->from('tx_dlf_documents');
400
401
            // Get UID of document with given record identifier.
402
            if ($pid) {
403
                $queryBuilder
404
                    ->where(
405
                        $queryBuilder->expr()->eq('tx_dlf_documents.uid', intval($uid)),
406
                        $queryBuilder->expr()->eq('tx_dlf_documents.pid', intval($pid)),
407
                        Helper::whereExpression('tx_dlf_documents')
408
                    );
409
            } else {
410
                $queryBuilder
411
                    ->where(
412
                        $queryBuilder->expr()->eq('tx_dlf_documents.uid', intval($uid)),
413
                        Helper::whereExpression('tx_dlf_documents')
414
                    );
415
            }
416
417
            $result = $queryBuilder
418
                ->setMaxResults(1)
419
                ->execute();
420
421
            if ($resArray = $result->fetch()) {
422
                $documentFormat = $resArray['document_format'];
423
            }
424
        } else {
425
            // Get document format from content of remote document
426
            // Cast to string for safety reasons.
427
            $location = (string) $uid;
428
            // Try to load a file from the url
429
            if (GeneralUtility::isValidUrl($location)) {
430
                // Load extension configuration
431
                $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
432
                // Set user-agent to identify self when fetching XML data.
433
                if (!empty($extConf['useragent'])) {
434
                    @ini_set('user_agent', $extConf['useragent']);
435
                }
436
                $content = GeneralUtility::getUrl($location);
437
                if ($content !== false) {
438
                    $xml = Helper::getXmlFileAsString($content);
439
                    if ($xml !== false) {
440
                        /* @var $xml \SimpleXMLElement */
441
                        $xml->registerXPathNamespace('mets', 'http://www.loc.gov/METS/');
442
                        $xpathResult = $xml->xpath('//mets:mets');
443
                        $documentFormat = !empty($xpathResult) ? 'METS' : null;
444
                    } else {
445
                        // Try to load file as IIIF resource instead.
446
                        $contentAsJsonArray = json_decode($content, true);
447
                        if ($contentAsJsonArray !== null) {
448
                            // Load plugin configuration.
449
                            $conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
450
                            IiifHelper::setUrlReader(IiifUrlReader::getInstance());
0 ignored issues
show
Bug introduced by
The type Kitodo\Dlf\Common\Document\IiifUrlReader was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
451
                            IiifHelper::setMaxThumbnailHeight($conf['iiifThumbnailHeight']);
452
                            IiifHelper::setMaxThumbnailWidth($conf['iiifThumbnailWidth']);
453
                            $iiif = IiifHelper::loadIiifResource($contentAsJsonArray);
454
                            if ($iiif instanceof IiifResourceInterface) {
455
                                $documentFormat = 'IIIF';
456
                            }
457
                        }
458
                    }
459
                }
460
            }
461
        }
462
        // Sanitize input.
463
        $pid = max(intval($pid), 0);
464
        if ($documentFormat == 'METS') {
465
            $instance = new MetsDocument($uid, $pid, $xml);
466
        } elseif ($documentFormat == 'IIIF') {
467
            $instance = new IiifManifest($uid, $pid, $iiif);
468
        }
469
        // Save instance to registry.
470
        if (
471
            $instance instanceof self
472
            && $instance->ready) {
473
            self::$registry[Helper::digest($instance->uid)] = $instance;
474
            if ($instance->uid != $instance->location) {
475
                self::$registry[Helper::digest($instance->location)] = $instance;
476
            }
477
            // Load extension configuration
478
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
479
            // Save registry to session if caching is enabled.
480
            if (!empty($extConf['caching'])) {
481
                Helper::saveToSession(self::$registry, get_class($instance));
482
            }
483
            $instance->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(get_class($instance));
484
        }
485
        // Return new instance.
486
        return $instance;
487
    }
488
489
    /**
490
     * Source document PHP object which is represented by a Document instance
491
     *
492
     * @access protected
493
     *
494
     * @abstract
495
     *
496
     * @return \SimpleXMLElement|IiifResourceInterface An PHP object representation of
497
     * the current document. SimpleXMLElement for METS, IiifResourceInterface for IIIF
498
     */
499
    protected abstract function getDocument();
500
501
    /**
502
     * This extracts all the metadata for a logical structure node
503
     *
504
     * @access public
505
     *
506
     * @abstract
507
     *
508
     * @param string $id: The @ID attribute of the logical structure node (METS) or the @id property
509
     * of the Manifest / Range (IIIF)
510
     * @param int $cPid: The PID for the metadata definitions
511
     *                       (defaults to $this->cPid or $this->pid)
512
     *
513
     * @return array The logical structure node's / the IIIF resource's parsed metadata array
514
     */
515
    public abstract function getMetadata($id, $cPid = 0);
516
517
    /**
518
     * This gets the location of a downloadable file for a physical page or track
519
     *
520
     * @access public
521
     *
522
     * @abstract
523
     *
524
     * @param string $id: The @ID attribute of the file node (METS) or the @id property of the IIIF resource
525
     *
526
     * @return string    The file's location as URL
527
     */
528
    public abstract function getDownloadLocation($id);
529
530
    /**
531
     * This gets the location of a file representing a physical page or track
532
     *
533
     * @access public
534
     *
535
     * @abstract
536
     *
537
     * @param string $id: The @ID attribute of the file node (METS) or the @id property of the IIIF resource
538
     *
539
     * @return string The file's location as URL
540
     */
541
    public abstract function getFileLocation($id);
542
543
    /**
544
     * This gets the MIME type of a file representing a physical page or track
545
     *
546
     * @access public
547
     *
548
     * @abstract
549
     *
550
     * @param string $id: The @ID attribute of the file node
551
     *
552
     * @return string The file's MIME type
553
     */
554
    public abstract function getFileMimeType($id);
555
556
    /**
557
     * This gets details about a logical structure element
558
     *
559
     * @access public
560
     *
561
     * @abstract
562
     *
563
     * @param string $id: The @ID attribute of the logical structure node (METS) or
564
     * the @id property of the Manifest / Range (IIIF)
565
     * @param bool $recursive: Whether to include the child elements / resources
566
     *
567
     * @return array Array of the element's id, label, type and physical page indexes/mptr link
568
     */
569
    public abstract function getLogicalStructure($id, $recursive = false);
570
571
    /**
572
     * This returns the first corresponding physical page number of a given logical page label
573
     *
574
     * @access public
575
     *
576
     * @param string $logicalPage: The label (or a part of the label) of the logical page
577
     *
578
     * @return int The physical page number
579
     */
580
    public function getPhysicalPage($logicalPage)
581
    {
582
        if (
583
            !empty($this->lastSearchedPhysicalPage['logicalPage'])
584
            && $this->lastSearchedPhysicalPage['logicalPage'] == $logicalPage
585
        ) {
586
            return $this->lastSearchedPhysicalPage['physicalPage'];
587
        } else {
588
            $physicalPage = 0;
589
            foreach ($this->physicalStructureInfo as $page) {
590
                if (strpos($page['orderlabel'], $logicalPage) !== false) {
591
                    $this->lastSearchedPhysicalPage['logicalPage'] = $logicalPage;
592
                    $this->lastSearchedPhysicalPage['physicalPage'] = $physicalPage;
593
                    return $physicalPage;
594
                }
595
                $physicalPage++;
596
            }
597
        }
598
        return 1;
599
    }
600
601
    /**
602
     * This determines a title for the given document
603
     *
604
     * @access public
605
     *
606
     * @static
607
     *
608
     * @param int $uid: The UID of the document
609
     * @param bool $recursive: Search superior documents for a title, too?
610
     *
611
     * @return string The title of the document itself or a parent document
612
     */
613
    public static function getTitle($uid, $recursive = false)
614
    {
615
        $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
616
617
        $title = '';
618
        // Sanitize input.
619
        $uid = max(intval($uid), 0);
620
        if ($uid) {
621
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
622
                ->getQueryBuilderForTable('tx_dlf_documents');
623
624
            $result = $queryBuilder
625
                ->select(
626
                    'tx_dlf_documents.title',
627
                    'tx_dlf_documents.partof'
628
                )
629
                ->from('tx_dlf_documents')
630
                ->where(
631
                    $queryBuilder->expr()->eq('tx_dlf_documents.uid', $uid),
632
                    Helper::whereExpression('tx_dlf_documents')
633
                )
634
                ->setMaxResults(1)
635
                ->execute();
636
637
            if ($resArray = $result->fetch()) {
638
                // Get title information.
639
                $title = $resArray['title'];
640
                $partof = $resArray['partof'];
641
                // Search parent documents recursively for a title?
642
                if (
643
                    $recursive
644
                    && empty($title)
645
                    && intval($partof)
646
                    && $partof != $uid
647
                ) {
648
                    $title = self::getTitle($partof, true);
649
                }
650
            } else {
651
                $logger->warning('No document with UID ' . $uid . ' found or document not accessible');
652
            }
653
        } else {
654
            $logger->error('Invalid UID ' . $uid . ' for document');
655
        }
656
        return $title;
657
    }
658
659
    /**
660
     * This extracts all the metadata for the toplevel logical structure node / resource
661
     *
662
     * @access public
663
     *
664
     * @param int $cPid: The PID for the metadata definitions
665
     *
666
     * @return array The logical structure node's / resource's parsed metadata array
667
     */
668
    public function getTitleData($cPid = 0)
669
    {
670
        $titledata = $this->getMetadata($this->_getToplevelId(), $cPid);
671
        // Add information from METS structural map to titledata array.
672
        if ($this instanceof MetsDocument) {
673
            $this->addMetadataFromMets($titledata, $this->_getToplevelId());
674
        }
675
        // Set record identifier for METS file / IIIF manifest if not present.
676
        if (
677
            is_array($titledata)
678
            && array_key_exists('record_id', $titledata)
679
        ) {
680
            if (
681
                !empty($this->recordId)
682
                && !in_array($this->recordId, $titledata['record_id'])
683
            ) {
684
                array_unshift($titledata['record_id'], $this->recordId);
685
            }
686
        }
687
        return $titledata;
688
    }
689
690
    /**
691
     * Get the tree depth of a logical structure element within the table of content
692
     *
693
     * @access public
694
     *
695
     * @param string $logId: The id of the logical structure element whose depth is requested
696
     * @return int|bool tree depth as integer or false if no element with $logId exists within the TOC.
697
     */
698
    public function getStructureDepth($logId)
699
    {
700
        return $this->getTreeDepth($this->_getTableOfContents(), 1, $logId);
701
    }
702
703
    /**
704
     * Register all available namespaces for a \SimpleXMLElement object
705
     *
706
     * @access public
707
     *
708
     * @param \SimpleXMLElement|\DOMXPath &$obj: \SimpleXMLElement or \DOMXPath object
709
     *
710
     * @return void
711
     */
712
    public function registerNamespaces(&$obj)
713
    {
714
        // TODO Check usage. XML specific method does not seem to be used anywhere outside this class within the project, but it is public and may be used by extensions.
715
        $this->loadFormats();
716
        // Do we have a \SimpleXMLElement or \DOMXPath object?
717
        if ($obj instanceof \SimpleXMLElement) {
718
            $method = 'registerXPathNamespace';
719
        } elseif ($obj instanceof \DOMXPath) {
720
            $method = 'registerNamespace';
721
        } else {
722
            $this->logger->error('Given object is neither a SimpleXMLElement nor a DOMXPath instance');
1 ignored issue
show
Bug introduced by
The method error() does not exist on TYPO3\CMS\Core\Log\LogManager. ( Ignorable by Annotation )

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

722
            $this->logger->/** @scrutinizer ignore-call */ 
723
                           error('Given object is neither a SimpleXMLElement nor a DOMXPath instance');

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...
723
            return;
724
        }
725
        // Register metadata format's namespaces.
726
        foreach ($this->formats as $enc => $conf) {
727
            $obj->$method(strtolower($enc), $conf['namespaceURI']);
728
        }
729
    }
730
731
    /**
732
     * This saves the document to the database and index
733
     *
734
     * @access public
735
     *
736
     * @param int $pid: The PID of the saved record
737
     * @param int $core: The UID of the Solr core for indexing
738
     * @param int|string $owner: UID or index_name of owner to set while indexing
739
     *
740
     * @return bool true on success or false on failure
741
     */
742
    public function save($pid = 0, $core = 0, $owner = null)
743
    {
744
        if (\TYPO3_MODE !== 'BE') {
745
            $this->logger->error('Saving a document is only allowed in the backend');
746
            return false;
747
        }
748
        // Make sure $pid is a non-negative integer.
749
        $pid = max(intval($pid), 0);
750
        // Make sure $core is a non-negative integer.
751
        $core = max(intval($core), 0);
752
        // If $pid is not given, try to get it elsewhere.
753
        if (
754
            !$pid
755
            && $this->pid
756
        ) {
757
            // Retain current PID.
758
            $pid = $this->pid;
759
        } elseif (!$pid) {
760
            $this->logger->error('Invalid PID ' . $pid . ' for document saving');
761
            return false;
762
        }
763
        // Set PID for metadata definitions.
764
        $this->cPid = $pid;
765
        // Set UID placeholder if not updating existing record.
766
        if ($pid != $this->pid) {
767
            $this->uid = uniqid('NEW');
0 ignored issues
show
Bug introduced by
The property uid is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
768
        }
769
        // Get metadata array.
770
        $metadata = $this->getTitleData($pid);
771
        // Check for record identifier.
772
        if (empty($metadata['record_id'][0])) {
773
            $this->logger->error('No record identifier found to avoid duplication');
774
            return false;
775
        }
776
        // Load plugin configuration.
777
        $conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
778
779
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
780
            ->getQueryBuilderForTable('tx_dlf_structures');
781
782
        // Get UID for structure type.
783
        $result = $queryBuilder
784
            ->select('tx_dlf_structures.uid AS uid')
785
            ->from('tx_dlf_structures')
786
            ->where(
787
                $queryBuilder->expr()->eq('tx_dlf_structures.pid', intval($pid)),
788
                $queryBuilder->expr()->eq('tx_dlf_structures.index_name', $queryBuilder->expr()->literal($metadata['type'][0])),
789
                Helper::whereExpression('tx_dlf_structures')
790
            )
791
            ->setMaxResults(1)
792
            ->execute();
793
794
        if ($resArray = $result->fetch()) {
795
            $structure = $resArray['uid'];
796
        } else {
797
            $this->logger->error('Could not identify document/structure type "' . $queryBuilder->expr()->literal($metadata['type'][0]) . '"');
798
            return false;
799
        }
800
        $metadata['type'][0] = $structure;
801
802
        // Remove appended "valueURI" from authors' names for storing in database.
803
        foreach ($metadata['author'] as $i => $author) {
804
            $splitName = explode(chr(31), $author);
805
            $metadata['author'][$i] = $splitName[0];
806
        }
807
808
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
809
            ->getQueryBuilderForTable('tx_dlf_collections');
810
        // Get hidden records, too.
811
        $queryBuilder
812
            ->getRestrictions()
813
            ->removeByType(HiddenRestriction::class);
814
815
        // Get UIDs for collections.
816
        $result = $queryBuilder
817
            ->select(
818
                'tx_dlf_collections.index_name AS index_name',
819
                'tx_dlf_collections.uid AS uid'
820
            )
821
            ->from('tx_dlf_collections')
822
            ->where(
823
                $queryBuilder->expr()->eq('tx_dlf_collections.pid', intval($pid)),
824
                $queryBuilder->expr()->in('tx_dlf_collections.sys_language_uid', [-1, 0])
825
            )
826
            ->execute();
827
828
        $collUid = [];
829
        while ($resArray = $result->fetch()) {
830
            $collUid[$resArray['index_name']] = $resArray['uid'];
831
        }
832
        $collections = [];
833
        foreach ($metadata['collection'] as $collection) {
834
            if (!empty($collUid[$collection])) {
835
                // Add existing collection's UID.
836
                $collections[] = $collUid[$collection];
837
            } else {
838
                // Insert new collection.
839
                $collNewUid = uniqid('NEW');
840
                $collData['tx_dlf_collections'][$collNewUid] = [
841
                    'pid' => $pid,
842
                    'label' => $collection,
843
                    'index_name' => $collection,
844
                    'oai_name' => (!empty($conf['publishNewCollections']) ? Helper::getCleanString($collection) : ''),
845
                    'description' => '',
846
                    'documents' => 0,
847
                    'owner' => 0,
848
                    'status' => 0,
849
                ];
850
                $substUid = Helper::processDBasAdmin($collData);
851
                // Prevent double insertion.
852
                unset($collData);
853
                // Add new collection's UID.
854
                $collections[] = $substUid[$collNewUid];
855
                if (!(\TYPO3_REQUESTTYPE & \TYPO3_REQUESTTYPE_CLI)) {
856
                    Helper::addMessage(
857
                        htmlspecialchars(sprintf(Helper::getMessage('flash.newCollection'), $collection, $substUid[$collNewUid])),
858
                        Helper::getMessage('flash.attention', true),
859
                        \TYPO3\CMS\Core\Messaging\FlashMessage::INFO,
860
                        true
861
                    );
862
                }
863
            }
864
        }
865
        $metadata['collection'] = $collections;
866
867
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
868
            ->getQueryBuilderForTable('tx_dlf_libraries');
869
870
        // Get UID for owner.
871
        if (empty($owner)) {
872
            $owner = empty($metadata['owner'][0]) ? $metadata['owner'][0] : 'default';
873
        }
874
        if (!MathUtility::canBeInterpretedAsInteger($owner)) {
875
            $result = $queryBuilder
876
                ->select('tx_dlf_libraries.uid AS uid')
877
                ->from('tx_dlf_libraries')
878
                ->where(
879
                    $queryBuilder->expr()->eq('tx_dlf_libraries.pid', intval($pid)),
880
                    $queryBuilder->expr()->eq('tx_dlf_libraries.index_name', $queryBuilder->expr()->literal($owner)),
881
                    Helper::whereExpression('tx_dlf_libraries')
882
                )
883
                ->setMaxResults(1)
884
                ->execute();
885
886
            if ($resArray = $result->fetch()) {
887
                $ownerUid = $resArray['uid'];
888
            } else {
889
                // Insert new library.
890
                $libNewUid = uniqid('NEW');
891
                $libData['tx_dlf_libraries'][$libNewUid] = [
892
                    'pid' => $pid,
893
                    'label' => $owner,
894
                    'index_name' => $owner,
895
                    'website' => '',
896
                    'contact' => '',
897
                    'image' => '',
898
                    'oai_label' => '',
899
                    'oai_base' => '',
900
                    'opac_label' => '',
901
                    'opac_base' => '',
902
                    'union_label' => '',
903
                    'union_base' => '',
904
                ];
905
                $substUid = Helper::processDBasAdmin($libData);
906
                // Add new library's UID.
907
                $ownerUid = $substUid[$libNewUid];
908
                if (!(\TYPO3_REQUESTTYPE & \TYPO3_REQUESTTYPE_CLI)) {
909
                    Helper::addMessage(
910
                        htmlspecialchars(sprintf(Helper::getMessage('flash.newLibrary'), $owner, $ownerUid)),
911
                        Helper::getMessage('flash.attention', true),
912
                        \TYPO3\CMS\Core\Messaging\FlashMessage::INFO,
913
                        true
914
                    );
915
                }
916
            }
917
            $owner = $ownerUid;
918
        }
919
        $metadata['owner'][0] = $owner;
920
        // Get UID of parent document.
921
        $partof = $this->getParentDocumentUidForSaving($pid, $core, $owner);
922
        // Use the date of publication or title as alternative sorting metric for parts of multi-part works.
923
        if (!empty($partof)) {
924
            if (
925
                empty($metadata['volume'][0])
926
                && !empty($metadata['year'][0])
927
            ) {
928
                $metadata['volume'] = $metadata['year'];
929
            }
930
            if (empty($metadata['volume_sorting'][0])) {
931
                // If METS @ORDER is given it is preferred over year_sorting and year.
932
                if (!empty($metadata['mets_order'][0])) {
933
                    $metadata['volume_sorting'][0] = $metadata['mets_order'][0];
934
                } elseif (!empty($metadata['year_sorting'][0])) {
935
                    $metadata['volume_sorting'][0] = $metadata['year_sorting'][0];
936
                } elseif (!empty($metadata['year'][0])) {
937
                    $metadata['volume_sorting'][0] = $metadata['year'][0];
938
                }
939
            }
940
            // If volume_sorting is still empty, try to use title_sorting or METS @ORDERLABEL finally (workaround for newspapers)
941
            if (empty($metadata['volume_sorting'][0])) {
942
                if (!empty($metadata['title_sorting'][0])) {
943
                    $metadata['volume_sorting'][0] = $metadata['title_sorting'][0];
944
                } elseif (!empty($metadata['mets_orderlabel'][0])) {
945
                    $metadata['volume_sorting'][0] = $metadata['mets_orderlabel'][0];
946
                }
947
            }
948
        }
949
950
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
951
            ->getQueryBuilderForTable('tx_dlf_metadata');
952
953
        // Get metadata for lists and sorting.
954
        $result = $queryBuilder
955
            ->select(
956
                'tx_dlf_metadata.index_name AS index_name',
957
                'tx_dlf_metadata.is_listed AS is_listed',
958
                'tx_dlf_metadata.is_sortable AS is_sortable'
959
            )
960
            ->from('tx_dlf_metadata')
961
            ->where(
962
                $queryBuilder->expr()->orX(
963
                    $queryBuilder->expr()->eq('tx_dlf_metadata.is_listed', 1),
964
                    $queryBuilder->expr()->eq('tx_dlf_metadata.is_sortable', 1)
965
                ),
966
                $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($pid)),
967
                Helper::whereExpression('tx_dlf_metadata')
968
            )
969
            ->execute();
970
971
        $listed = [];
972
        $sortable = [];
973
974
        while ($resArray = $result->fetch()) {
975
            if (!empty($metadata[$resArray['index_name']])) {
976
                if ($resArray['is_listed']) {
977
                    $listed[$resArray['index_name']] = $metadata[$resArray['index_name']];
978
                }
979
                if ($resArray['is_sortable']) {
980
                    $sortable[$resArray['index_name']] = $metadata[$resArray['index_name']][0];
981
                }
982
            }
983
        }
984
        // Fill data array.
985
        $data['tx_dlf_documents'][$this->uid] = [
986
            'pid' => $pid,
987
            $GLOBALS['TCA']['tx_dlf_documents']['ctrl']['enablecolumns']['starttime'] => 0,
988
            $GLOBALS['TCA']['tx_dlf_documents']['ctrl']['enablecolumns']['endtime'] => 0,
989
            'prod_id' => $metadata['prod_id'][0],
990
            'location' => $this->location,
991
            'record_id' => $metadata['record_id'][0],
992
            'opac_id' => $metadata['opac_id'][0],
993
            'union_id' => $metadata['union_id'][0],
994
            'urn' => $metadata['urn'][0],
995
            'purl' => $metadata['purl'][0],
996
            'title' => $metadata['title'][0],
997
            'title_sorting' => $metadata['title_sorting'][0],
998
            'author' => implode('; ', $metadata['author']),
999
            'year' => implode('; ', $metadata['year']),
1000
            'place' => implode('; ', $metadata['place']),
1001
            'thumbnail' => $this->_getThumbnail(true),
1002
            'metadata' => serialize($listed),
1003
            'metadata_sorting' => serialize($sortable),
1004
            'structure' => $metadata['type'][0],
1005
            'partof' => $partof,
1006
            'volume' => $metadata['volume'][0],
1007
            'volume_sorting' => $metadata['volume_sorting'][0],
1008
            'license' => $metadata['license'][0],
1009
            'terms' => $metadata['terms'][0],
1010
            'restrictions' => $metadata['restrictions'][0],
1011
            'out_of_print' => $metadata['out_of_print'][0],
1012
            'rights_info' => $metadata['rights_info'][0],
1013
            'collections' => $metadata['collection'],
1014
            'mets_label' => $metadata['mets_label'][0],
1015
            'mets_orderlabel' => $metadata['mets_orderlabel'][0],
1016
            'mets_order' => $metadata['mets_order'][0],
1017
            'owner' => $metadata['owner'][0],
1018
            'solrcore' => $core,
1019
            'status' => 0,
1020
            'document_format' => $metadata['document_format'][0],
1021
        ];
1022
        // Unhide hidden documents.
1023
        if (!empty($conf['unhideOnIndex'])) {
1024
            $data['tx_dlf_documents'][$this->uid][$GLOBALS['TCA']['tx_dlf_documents']['ctrl']['enablecolumns']['disabled']] = 0;
1025
        }
1026
        // Process data.
1027
        $newIds = Helper::processDBasAdmin($data);
1028
        // Replace placeholder with actual UID.
1029
        if (strpos($this->uid, 'NEW') === 0) {
1030
            $this->uid = $newIds[$this->uid];
1031
            $this->pid = $pid;
0 ignored issues
show
Bug introduced by
The property pid is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1032
            $this->parentId = $partof;
0 ignored issues
show
Bug introduced by
The property parentId is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1033
        }
1034
        if (!(\TYPO3_REQUESTTYPE & \TYPO3_REQUESTTYPE_CLI)) {
1035
            Helper::addMessage(
1036
                htmlspecialchars(sprintf(Helper::getMessage('flash.documentSaved'), $metadata['title'][0], $this->uid)),
1037
                Helper::getMessage('flash.done', true),
1038
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
1039
                true
1040
            );
1041
        }
1042
        // Add document to index.
1043
        if ($core) {
1044
            return Indexer::add($this, $core);
1045
        } else {
1046
            $this->logger->notice('Invalid UID "' . $core . '" for Solr core');
1 ignored issue
show
Bug introduced by
The method notice() does not exist on TYPO3\CMS\Core\Log\LogManager. ( Ignorable by Annotation )

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

1046
            $this->logger->/** @scrutinizer ignore-call */ 
1047
                           notice('Invalid UID "' . $core . '" for Solr core');

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...
1047
            return false;
1048
        }
1049
    }
1050
1051
    /**
1052
     * This ensures that the recordId, if existent, is retrieved from the document
1053
     *
1054
     * @access protected
1055
     *
1056
     * @abstract
1057
     *
1058
     * @param int $pid: ID of the configuration page with the recordId config
1059
     *
1060
     */
1061
    protected abstract function establishRecordId($pid);
1062
1063
    /**
1064
     * Get the ID of the parent document if the current document has one. Also save a parent document
1065
     * to the database and the Solr index if their $pid and the current $pid differ.
1066
     * Currently only applies to METS documents.
1067
     *
1068
     * @access protected
1069
     *
1070
     * @abstract
1071
     *
1072
     * @return int The parent document's id.
1073
     */
1074
    protected abstract function getParentDocumentUidForSaving($pid, $core, $owner);
1075
1076
    /**
1077
     * This sets some basic class properties
1078
     *
1079
     * @access protected
1080
     *
1081
     * @abstract
1082
     *
1083
     * @return void
1084
     */
1085
    protected abstract function init();
1086
1087
    /**
1088
     * METS/IIIF specific part of loading a location
1089
     *
1090
     * @access protected
1091
     *
1092
     * @abstract
1093
     *
1094
     * @param string $location: The URL of the file to load
1095
     *
1096
     * @return bool true on success or false on failure
1097
     */
1098
    protected abstract function loadLocation($location);
1099
1100
    /**
1101
     * Reuse any document object that might have been already loaded to determine wether document is METS or IIIF
1102
     *
1103
     * @access protected
1104
     *
1105
     * @abstract
1106
     *
1107
     * @param \SimpleXMLElement|IiifResourceInterface $preloadedDocument: any instance that has already been loaded
1108
     *
1109
     * @return bool true if $preloadedDocument can actually be reused, false if it has to be loaded again
1110
     */
1111
    protected abstract function setPreloadedDocument($preloadedDocument);
1112
1113
    /**
1114
     * Load XML file / IIIF resource from URL
1115
     *
1116
     * @access protected
1117
     *
1118
     * @param string $location: The URL of the file to load
1119
     *
1120
     * @return bool true on success or false on failure
1121
     */
1122
    protected function load($location)
1123
    {
1124
        // Load XML / JSON-LD file.
1125
        if (GeneralUtility::isValidUrl($location)) {
1126
            // Load extension configuration
1127
            $extConf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
1128
            // Set user-agent to identify self when fetching XML / JSON-LD data.
1129
            if (!empty($extConf['useragent'])) {
1130
                @ini_set('user_agent', $extConf['useragent']);
1131
            }
1132
            // the actual loading is format specific
1133
            return $this->loadLocation($location);
1134
        } else {
1135
            $this->logger->error('Invalid file location "' . $location . '" for document loading');
1136
        }
1137
        return false;
1138
    }
1139
1140
    /**
1141
     * Register all available data formats
1142
     *
1143
     * @access protected
1144
     *
1145
     * @return void
1146
     */
1147
    protected function loadFormats()
1148
    {
1149
        if (!$this->formatsLoaded) {
1150
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1151
                ->getQueryBuilderForTable('tx_dlf_formats');
1152
1153
            // Get available data formats from database.
1154
            $result = $queryBuilder
1155
                ->select(
1156
                    'tx_dlf_formats.type AS type',
1157
                    'tx_dlf_formats.root AS root',
1158
                    'tx_dlf_formats.namespace AS namespace',
1159
                    'tx_dlf_formats.class AS class'
1160
                )
1161
                ->from('tx_dlf_formats')
1162
                ->where(
1163
                    $queryBuilder->expr()->eq('tx_dlf_formats.pid', 0)
1164
                )
1165
                ->execute();
1166
1167
            while ($resArray = $result->fetch()) {
1168
                // Update format registry.
1169
                $this->formats[$resArray['type']] = [
1170
                    'rootElement' => $resArray['root'],
1171
                    'namespaceURI' => $resArray['namespace'],
1172
                    'class' => $resArray['class']
1173
                ];
1174
            }
1175
            $this->formatsLoaded = true;
1176
        }
1177
    }
1178
1179
    /**
1180
     * Traverse a logical (sub-) structure tree to find the structure with the requested logical id and return it's depth.
1181
     *
1182
     * @access protected
1183
     *
1184
     * @param array $structure: logical structure array
1185
     * @param int $depth: current tree depth
1186
     * @param string $logId: ID of the logical structure whose depth is requested
1187
     *
1188
     * @return int|bool: false if structure with $logId is not a child of this substructure,
1189
     * or the actual depth.
1190
     */
1191
    protected function getTreeDepth($structure, $depth, $logId)
1192
    {
1193
        foreach ($structure as $element) {
1194
            if ($element['id'] == $logId) {
1195
                return $depth;
1196
            } elseif (array_key_exists('children', $element)) {
1197
                $foundInChildren = $this->getTreeDepth($element['children'], $depth + 1, $logId);
1198
                if ($foundInChildren !== false) {
1199
                    return $foundInChildren;
1200
                }
1201
            }
1202
        }
1203
        return false;
1204
    }
1205
1206
    /**
1207
     * This returns $this->cPid via __get()
1208
     *
1209
     * @access protected
1210
     *
1211
     * @return int The PID of the metadata definitions
1212
     */
1213
    protected function _getCPid()
1214
    {
1215
        return $this->cPid;
1216
    }
1217
1218
    /**
1219
     * This returns $this->location via __get()
1220
     *
1221
     * @access protected
1222
     *
1223
     * @return string The location of the document
1224
     */
1225
    protected function _getLocation()
1226
    {
1227
        return $this->location;
1228
    }
1229
1230
    /**
1231
     * Format specific part of building the document's metadata array
1232
     *
1233
     * @access protected
1234
     *
1235
     * @abstract
1236
     *
1237
     * @param int $cPid
1238
     */
1239
    protected abstract function prepareMetadataArray($cPid);
1240
1241
    /**
1242
     * This builds an array of the document's metadata
1243
     *
1244
     * @access protected
1245
     *
1246
     * @return array Array of metadata with their corresponding logical structure node ID as key
1247
     */
1248
    protected function _getMetadataArray()
1249
    {
1250
        // Set metadata definitions' PID.
1251
        $cPid = ($this->cPid ? $this->cPid : $this->pid);
1252
        if (!$cPid) {
1253
            $this->logger->error('Invalid PID ' . $cPid . ' for metadata definitions');
1254
            return [];
1255
        }
1256
        if (
1257
            !$this->metadataArrayLoaded
1258
            || $this->metadataArray[0] != $cPid
1259
        ) {
1260
            $this->prepareMetadataArray($cPid);
1261
            $this->metadataArray[0] = $cPid;
0 ignored issues
show
Bug introduced by
The property metadataArray is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1262
            $this->metadataArrayLoaded = true;
1263
        }
1264
        return $this->metadataArray;
1265
    }
1266
1267
    /**
1268
     * This returns $this->numPages via __get()
1269
     *
1270
     * @access protected
1271
     *
1272
     * @return int The total number of pages and/or tracks
1273
     */
1274
    protected function _getNumPages()
1275
    {
1276
        $this->_getPhysicalStructure();
1277
        return $this->numPages;
1278
    }
1279
1280
    /**
1281
     * This returns $this->parentId via __get()
1282
     *
1283
     * @access protected
1284
     *
1285
     * @return int The UID of the parent document or zero if not applicable
1286
     */
1287
    protected function _getParentId()
1288
    {
1289
        return $this->parentId;
1290
    }
1291
1292
    /**
1293
     * This builds an array of the document's physical structure
1294
     *
1295
     * @access protected
1296
     *
1297
     * @abstract
1298
     *
1299
     * @return array Array of physical elements' id, type, label and file representations ordered
1300
     * by @ORDER attribute / IIIF Sequence's Canvases
1301
     */
1302
    protected abstract function _getPhysicalStructure();
1303
1304
    /**
1305
     * This gives an array of the document's physical structure metadata
1306
     *
1307
     * @access protected
1308
     *
1309
     * @return array Array of elements' type, label and file representations ordered by @ID attribute / Canvas order
1310
     */
1311
    protected function _getPhysicalStructureInfo()
1312
    {
1313
        // Is there no physical structure array yet?
1314
        if (!$this->physicalStructureLoaded) {
1315
            // Build physical structure array.
1316
            $this->_getPhysicalStructure();
1317
        }
1318
        return $this->physicalStructureInfo;
1319
    }
1320
1321
    /**
1322
     * This returns $this->pid via __get()
1323
     *
1324
     * @access protected
1325
     *
1326
     * @return int The PID of the document or zero if not in database
1327
     */
1328
    protected function _getPid()
1329
    {
1330
        return $this->pid;
1331
    }
1332
1333
    /**
1334
     * This returns $this->ready via __get()
1335
     *
1336
     * @access protected
1337
     *
1338
     * @return bool Is the document instantiated successfully?
1339
     */
1340
    protected function _getReady()
1341
    {
1342
        return $this->ready;
1343
    }
1344
1345
    /**
1346
     * This returns $this->recordId via __get()
1347
     *
1348
     * @access protected
1349
     *
1350
     * @return mixed The METS file's / IIIF manifest's record identifier
1351
     */
1352
    protected function _getRecordId()
1353
    {
1354
        return $this->recordId;
1355
    }
1356
1357
    /**
1358
     * This returns $this->rootId via __get()
1359
     *
1360
     * @access protected
1361
     *
1362
     * @return int The UID of the root document or zero if not applicable
1363
     */
1364
    protected function _getRootId()
1365
    {
1366
        if (!$this->rootIdLoaded) {
1367
            if ($this->parentId) {
1368
                $parent = self::getInstance($this->parentId, $this->pid);
1369
                $this->rootId = $parent->rootId;
0 ignored issues
show
Bug introduced by
The property rootId is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1370
            }
1371
            $this->rootIdLoaded = true;
1372
        }
1373
        return $this->rootId;
1374
    }
1375
1376
    /**
1377
     * This returns the smLinks between logical and physical structMap (METS) and models the
1378
     * relation between IIIF Canvases and Manifests / Ranges in the same way
1379
     *
1380
     * @access protected
1381
     *
1382
     * @abstract
1383
     *
1384
     * @return array The links between logical and physical nodes / Range, Manifest and Canvas
1385
     */
1386
    protected abstract function _getSmLinks();
1387
1388
    /**
1389
     * This builds an array of the document's logical structure
1390
     *
1391
     * @access protected
1392
     *
1393
     * @return array Array of structure nodes' id, label, type and physical page indexes/mptr / Canvas link with original hierarchy preserved
1394
     */
1395
    protected function _getTableOfContents()
1396
    {
1397
        // Is there no logical structure array yet?
1398
        if (!$this->tableOfContentsLoaded) {
1399
            // Get all logical structures.
1400
            $this->getLogicalStructure('', true);
1401
            $this->tableOfContentsLoaded = true;
1402
        }
1403
        return $this->tableOfContents;
1404
    }
1405
1406
    /**
1407
     * This returns the document's thumbnail location
1408
     *
1409
     * @access protected
1410
     *
1411
     * @abstract
1412
     *
1413
     * @param bool $forceReload: Force reloading the thumbnail instead of returning the cached value
1414
     *
1415
     * @return string The document's thumbnail location
1416
     */
1417
    protected abstract function _getThumbnail($forceReload = false);
1418
1419
    /**
1420
     * This returns the ID of the toplevel logical structure node
1421
     *
1422
     * @access protected
1423
     *
1424
     * @abstract
1425
     *
1426
     * @return string The logical structure node's ID
1427
     */
1428
    protected abstract function _getToplevelId();
1429
1430
    /**
1431
     * This returns $this->uid via __get()
1432
     *
1433
     * @access protected
1434
     *
1435
     * @return mixed The UID or the URL of the document
1436
     */
1437
    protected function _getUid()
1438
    {
1439
        return $this->uid;
1440
    }
1441
1442
    /**
1443
     * This sets $this->cPid via __set()
1444
     *
1445
     * @access protected
1446
     *
1447
     * @param int $value: The new PID for the metadata definitions
1448
     *
1449
     * @return void
1450
     */
1451
    protected function _setCPid($value)
1452
    {
1453
        $this->cPid = max(intval($value), 0);
1454
    }
1455
1456
    /**
1457
     * This magic method is invoked each time a clone is called on the object variable
1458
     *
1459
     * @access protected
1460
     *
1461
     * @return void
1462
     */
1463
    protected function __clone()
1464
    {
1465
        // This method is defined as protected because singleton objects should not be cloned.
1466
    }
1467
1468
    /**
1469
     * This is a singleton class, thus the constructor should be private/protected
1470
     * (Get an instance of this class by calling \Kitodo\Dlf\Common\Document\Document::getInstance())
1471
     *
1472
     * @access protected
1473
     *
1474
     * @param int $uid: The UID of the document to parse or URL to XML file
1475
     * @param int $pid: If > 0, then only document with this PID gets loaded
1476
     * @param \SimpleXMLElement|IiifResourceInterface $preloadedDocument: Either null or the \SimpleXMLElement
1477
     * or IiifResourceInterface that has been loaded to determine the basic document format.
1478
     *
1479
     * @return void
1480
     */
1481
    protected function __construct($uid, $pid, $preloadedDocument)
1482
    {
1483
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1484
            ->getQueryBuilderForTable('tx_dlf_documents');
1485
        $location = '';
1486
        // Prepare to check database for the requested document.
1487
        if (MathUtility::canBeInterpretedAsInteger($uid)) {
1488
            $whereClause = $queryBuilder->expr()->andX(
1489
                $queryBuilder->expr()->eq('tx_dlf_documents.uid', intval($uid)),
1490
                Helper::whereExpression('tx_dlf_documents')
1491
            );
1492
        } else {
1493
            // Try to load METS file / IIIF manifest.
1494
            if ($this->setPreloadedDocument($preloadedDocument) || (GeneralUtility::isValidUrl($uid)
1495
                && $this->load($uid))) {
1496
                // Initialize core METS object.
1497
                $this->init();
1498
                if ($this->getDocument() !== null) {
1499
                    // Cast to string for safety reasons.
1500
                    $location = (string) $uid;
1501
                    $this->establishRecordId($pid);
1502
                } else {
1503
                    // No METS / IIIF part found.
1504
                    return;
1505
                }
1506
            } else {
1507
                // Loading failed.
1508
                return;
1509
            }
1510
            if (
1511
                !empty($location)
1512
                && !empty($this->recordId)
1513
            ) {
1514
                // Try to match record identifier or location (both should be unique).
1515
                $whereClause = $queryBuilder->expr()->andX(
1516
                    $queryBuilder->expr()->orX(
1517
                        $queryBuilder->expr()->eq('tx_dlf_documents.location', $queryBuilder->expr()->literal($location)),
1518
                        $queryBuilder->expr()->eq('tx_dlf_documents.record_id', $queryBuilder->expr()->literal($this->recordId))
1519
                    ),
1520
                    Helper::whereExpression('tx_dlf_documents')
1521
                );
1522
            } else {
1523
                // Can't persistently identify document, don't try to match at all.
1524
                $whereClause = '1=-1';
1525
            }
1526
        }
1527
        // Check for PID if needed.
1528
        if ($pid) {
1529
            $whereClause = $queryBuilder->expr()->andX(
1530
                $whereClause,
1531
                $queryBuilder->expr()->eq('tx_dlf_documents.pid', intval($pid))
1532
            );
1533
        }
1534
        // Get document PID and location from database.
1535
        $result = $queryBuilder
1536
            ->select(
1537
                'tx_dlf_documents.uid AS uid',
1538
                'tx_dlf_documents.pid AS pid',
1539
                'tx_dlf_documents.record_id AS record_id',
1540
                'tx_dlf_documents.partof AS partof',
1541
                'tx_dlf_documents.thumbnail AS thumbnail',
1542
                'tx_dlf_documents.location AS location'
1543
            )
1544
            ->from('tx_dlf_documents')
1545
            ->where($whereClause)
1546
            ->setMaxResults(1)
1547
            ->execute();
1548
1549
        if ($resArray = $result->fetch()) {
1550
            $this->uid = $resArray['uid'];
0 ignored issues
show
Bug introduced by
The property uid is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1551
            $this->pid = $resArray['pid'];
0 ignored issues
show
Bug introduced by
The property pid is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1552
            $this->recordId = $resArray['record_id'];
0 ignored issues
show
Bug introduced by
The property recordId is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1553
            $this->parentId = $resArray['partof'];
0 ignored issues
show
Bug introduced by
The property parentId is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1554
            $this->thumbnail = $resArray['thumbnail'];
0 ignored issues
show
Bug introduced by
The property thumbnail is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1555
            $this->location = $resArray['location'];
0 ignored issues
show
Bug introduced by
The property location is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1556
            $this->thumbnailLoaded = true;
1557
            // Load XML file if necessary...
1558
            if (
1559
                $this->getDocument() === null
1560
                && $this->load($this->location)
1561
            ) {
1562
                // ...and set some basic properties.
1563
                $this->init();
1564
            }
1565
            // Do we have a METS / IIIF object now?
1566
            if ($this->getDocument() !== null) {
1567
                // Set new location if necessary.
1568
                if (!empty($location)) {
1569
                    $this->location = $location;
1570
                }
1571
                // Document ready!
1572
                $this->ready = true;
0 ignored issues
show
Bug introduced by
The property ready is declared read-only in Kitodo\Dlf\Common\Document\Document.
Loading history...
1573
            }
1574
        } elseif ($this->getDocument() !== null) {
1575
            // Set location as UID for documents not in database.
1576
            $this->uid = $location;
1577
            $this->location = $location;
1578
            // Document ready!
1579
            $this->ready = true;
1580
        } else {
1581
            $this->logger->error('No document with UID ' . $uid . ' found or document not accessible');
1582
        }
1583
    }
1584
1585
    /**
1586
     * This magic method is called each time an invisible property is referenced from the object
1587
     *
1588
     * @access public
1589
     *
1590
     * @param string $var: Name of variable to get
1591
     *
1592
     * @return mixed Value of $this->$var
1593
     */
1594
    public function __get($var)
1595
    {
1596
        $method = '_get' . ucfirst($var);
1597
        if (
1598
            !property_exists($this, $var)
1599
            || !method_exists($this, $method)
1600
        ) {
1601
            $this->logger->warning('There is no getter function for property "' . $var . '"');
1 ignored issue
show
Bug introduced by
The method warning() does not exist on TYPO3\CMS\Core\Log\LogManager. ( Ignorable by Annotation )

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

1601
            $this->logger->/** @scrutinizer ignore-call */ 
1602
                           warning('There is no getter function for property "' . $var . '"');

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...
1602
            return;
1603
        } else {
1604
            return $this->$method();
1605
        }
1606
    }
1607
1608
    /**
1609
     * This magic method is called each time an invisible property is checked for isset() or empty()
1610
     *
1611
     * @access public
1612
     *
1613
     * @param string $var: Name of variable to check
1614
     *
1615
     * @return bool true if variable is set and not empty, false otherwise
1616
     */
1617
    public function __isset($var)
1618
    {
1619
        return !empty($this->__get($var));
1620
    }
1621
1622
    /**
1623
     * This magic method is called each time an invisible property is referenced from the object
1624
     *
1625
     * @access public
1626
     *
1627
     * @param string $var: Name of variable to set
1628
     * @param mixed $value: New value of variable
1629
     *
1630
     * @return void
1631
     */
1632
    public function __set($var, $value)
1633
    {
1634
        $method = '_set' . ucfirst($var);
1635
        if (
1636
            !property_exists($this, $var)
1637
            || !method_exists($this, $method)
1638
        ) {
1639
            $this->logger->warning('There is no setter function for property "' . $var . '"');
1640
        } else {
1641
            $this->$method($value);
1642
        }
1643
    }
1644
}
1645