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
02:45
created

Document::_getLocation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
namespace Kitodo\Dlf\Common\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
        $title = '';
616
        // Sanitize input.
617
        $uid = max(intval($uid), 0);
618
        if ($uid) {
619
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
620
                ->getQueryBuilderForTable('tx_dlf_documents');
621
622
            $result = $queryBuilder
623
                ->select(
624
                    'tx_dlf_documents.title',
625
                    'tx_dlf_documents.partof'
626
                )
627
                ->from('tx_dlf_documents')
628
                ->where(
629
                    $queryBuilder->expr()->eq('tx_dlf_documents.uid', $uid),
630
                    Helper::whereExpression('tx_dlf_documents')
631
                )
632
                ->setMaxResults(1)
633
                ->execute();
634
635
            if ($resArray = $result->fetch()) {
636
                // Get title information.
637
                $title = $resArray['title'];
638
                $partof = $resArray['partof'];
639
                // Search parent documents recursively for a title?
640
                if (
641
                    $recursive
642
                    && empty($title)
643
                    && intval($partof)
644
                    && $partof != $uid
645
                ) {
646
                    $title = self::getTitle($partof, true);
647
                }
648
            } else {
649
                Helper::log('No document with UID ' . $uid . ' found or document not accessible', LOG_SEVERITY_WARNING);
650
            }
651
        } else {
652
            Helper::log('Invalid UID ' . $uid . ' for document', LOG_SEVERITY_ERROR);
653
        }
654
        return $title;
655
    }
656
657
    /**
658
     * This extracts all the metadata for the toplevel logical structure node / resource
659
     *
660
     * @access public
661
     *
662
     * @param int $cPid: The PID for the metadata definitions
663
     *
664
     * @return array The logical structure node's / resource's parsed metadata array
665
     */
666
    public function getTitleData($cPid = 0)
667
    {
668
        $titledata = $this->getMetadata($this->_getToplevelId(), $cPid);
669
        // Add information from METS structural map to titledata array.
670
        if ($this instanceof MetsDocument) {
671
            $this->addMetadataFromMets($titledata, $this->_getToplevelId());
672
        }
673
        // Set record identifier for METS file / IIIF manifest if not present.
674
        if (
675
            is_array($titledata)
676
            && array_key_exists('record_id', $titledata)
677
        ) {
678
            if (
679
                !empty($this->recordId)
680
                && !in_array($this->recordId, $titledata['record_id'])
681
            ) {
682
                array_unshift($titledata['record_id'], $this->recordId);
683
            }
684
        }
685
        return $titledata;
686
    }
687
688
    /**
689
     * Get the tree depth of a logical structure element within the table of content
690
     *
691
     * @access public
692
     *
693
     * @param string $logId: The id of the logical structure element whose depth is requested
694
     * @return int|bool tree depth as integer or false if no element with $logId exists within the TOC.
695
     */
696
    public function getStructureDepth($logId)
697
    {
698
        return $this->getTreeDepth($this->_getTableOfContents(), 1, $logId);
699
    }
700
701
    /**
702
     * Register all available namespaces for a \SimpleXMLElement object
703
     *
704
     * @access public
705
     *
706
     * @param \SimpleXMLElement|\DOMXPath &$obj: \SimpleXMLElement or \DOMXPath object
707
     *
708
     * @return void
709
     */
710
    public function registerNamespaces(&$obj)
711
    {
712
        // 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.
713
        $this->loadFormats();
714
        // Do we have a \SimpleXMLElement or \DOMXPath object?
715
        if ($obj instanceof \SimpleXMLElement) {
716
            $method = 'registerXPathNamespace';
717
        } elseif ($obj instanceof \DOMXPath) {
718
            $method = 'registerNamespace';
719
        } else {
720
            $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

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

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

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