Passed
Push — master ( c7cd38...937d5f )
by Mark
25:05 queued 14:37
created

Xlsx::canRead()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 1
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 3
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
6
use PhpOffice\PhpSpreadsheet\Cell\DataType;
7
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
8
use PhpOffice\PhpSpreadsheet\DefinedName;
9
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
10
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\AutoFilter;
11
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart;
12
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ColumnAndRowAttributes;
13
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ConditionalStyles;
14
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\DataValidations;
15
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Hyperlinks;
16
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
17
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\PageSetup;
18
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Properties as PropertyReader;
19
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SharedFormula;
20
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViewOptions;
21
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViews;
22
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles;
23
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\TableReader;
24
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Theme;
25
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\WorkbookView;
26
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
27
use PhpOffice\PhpSpreadsheet\RichText\RichText;
28
use PhpOffice\PhpSpreadsheet\Settings;
29
use PhpOffice\PhpSpreadsheet\Shared\Date;
30
use PhpOffice\PhpSpreadsheet\Shared\Drawing;
31
use PhpOffice\PhpSpreadsheet\Shared\File;
32
use PhpOffice\PhpSpreadsheet\Shared\Font;
33
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
34
use PhpOffice\PhpSpreadsheet\Spreadsheet;
35
use PhpOffice\PhpSpreadsheet\Style\Color;
36
use PhpOffice\PhpSpreadsheet\Style\Font as StyleFont;
37
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
38
use PhpOffice\PhpSpreadsheet\Style\Style;
39
use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing;
40
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
41
use SimpleXMLElement;
42
use Throwable;
43
use XMLReader;
44
use ZipArchive;
45
46
class Xlsx extends BaseReader
47
{
48
    const INITIAL_FILE = '_rels/.rels';
49
50
    /**
51
     * ReferenceHelper instance.
52
     *
53
     * @var ReferenceHelper
54
     */
55
    private $referenceHelper;
56
57
    /**
58
     * @var ZipArchive
59
     */
60
    private $zip;
61
62
    /** @var Styles */
63
    private $styleReader;
64
65
    /**
66
     * @var array
67
     */
68
    private $sharedFormulae = [];
69
70
    /**
71
     * Create a new Xlsx Reader instance.
72
     */
73 554
    public function __construct()
74
    {
75 554
        parent::__construct();
76 554
        $this->referenceHelper = ReferenceHelper::getInstance();
77 554
        $this->securityScanner = XmlScanner::getInstance($this);
78
    }
79
80
    /**
81
     * Can the current IReader read the file?
82
     */
83 24
    public function canRead(string $filename): bool
84
    {
85 24
        if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) {
86 7
            return false;
87
        }
88
89 17
        $result = false;
90 17
        $this->zip = $zip = new ZipArchive();
91
92 17
        if ($zip->open($filename) === true) {
93 17
            [$workbookBasename] = $this->getWorkbookBaseName();
94 17
            $result = !empty($workbookBasename);
95
96 17
            $zip->close();
97
        }
98
99 17
        return $result;
100
    }
101
102
    /**
103
     * @param mixed $value
104
     */
105 538
    public static function testSimpleXml($value): SimpleXMLElement
106
    {
107 538
        return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
108
    }
109
110 534
    public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement
111
    {
112 534
        return self::testSimpleXml($value === null ? $value : $value->attributes($ns));
113
    }
114
115
    // Phpstan thinks, correctly, that xpath can return false.
116
    // Scrutinizer thinks it can't.
117
    // Sigh.
118 509
    private static function xpathNoFalse(SimpleXmlElement $sxml, string $path): array
119
    {
120 509
        return self::falseToArray($sxml->xpath($path));
121
    }
122
123
    /**
124
     * @param mixed $value
125
     */
126 509
    public static function falseToArray($value): array
127
    {
128 509
        return is_array($value) ? $value : [];
129
    }
130
131 534
    private function loadZip(string $filename, string $ns = '', bool $replaceUnclosedBr = false): SimpleXMLElement
132
    {
133 534
        $contents = $this->getFromZipArchive($this->zip, $filename);
134 534
        if ($replaceUnclosedBr) {
135 23
            $contents = str_replace('<br>', '<br/>', $contents);
136
        }
137 534
        $rels = simplexml_load_string(
138 534
            $this->getSecurityScannerOrThrow()->scan($contents),
139 534
            'SimpleXMLElement',
140 534
            Settings::getLibXmlLoaderOptions(),
141 534
            $ns
142 534
        );
143
144 534
        return self::testSimpleXml($rels);
145
    }
146
147
    // This function is just to identify cases where I'm not sure
148
    // why empty namespace is required.
149 509
    private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElement
150
    {
151 509
        $contents = $this->getFromZipArchive($this->zip, $filename);
152 509
        $rels = simplexml_load_string(
153 509
            $this->getSecurityScannerOrThrow()->scan($contents),
154 509
            'SimpleXMLElement',
155 509
            Settings::getLibXmlLoaderOptions(),
156 509
            ($ns === '' ? $ns : '')
157 509
        );
158
159 509
        return self::testSimpleXml($rels);
160
    }
161
162
    private const REL_TO_MAIN = [
163
        Namespaces::PURL_OFFICE_DOCUMENT => Namespaces::PURL_MAIN,
164
        Namespaces::THUMBNAIL => '',
165
    ];
166
167
    private const REL_TO_DRAWING = [
168
        Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING,
169
    ];
170
171
    private const REL_TO_CHART = [
172
        Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_CHART,
173
    ];
174
175
    /**
176
     * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
177
     *
178
     * @param string $filename
179
     *
180
     * @return array
181
     */
182 15
    public function listWorksheetNames($filename)
183
    {
184 15
        File::assertFile($filename, self::INITIAL_FILE);
185
186 12
        $worksheetNames = [];
187
188 12
        $this->zip = $zip = new ZipArchive();
189 12
        $zip->open($filename);
190
191
        //    The files we're looking at here are small enough that simpleXML is more efficient than XMLReader
192 12
        $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
193 12
        foreach ($rels->Relationship as $relx) {
194 12
            $rel = self::getAttributes($relx);
195 12
            $relType = (string) $rel['Type'];
196 12
            $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
197 12
            if ($mainNS !== '') {
198 12
                $xmlWorkbook = $this->loadZip((string) $rel['Target'], $mainNS);
199
200 12
                if ($xmlWorkbook->sheets) {
201 12
                    foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
202
                        // Check if sheet should be skipped
203 12
                        $worksheetNames[] = (string) self::getAttributes($eleSheet)['name'];
204
                    }
205
                }
206
            }
207
        }
208
209 12
        $zip->close();
210
211 12
        return $worksheetNames;
212
    }
213
214
    /**
215
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
216
     *
217
     * @param string $filename
218
     *
219
     * @return array
220
     */
221 16
    public function listWorksheetInfo($filename)
222
    {
223 16
        File::assertFile($filename, self::INITIAL_FILE);
224
225 13
        $worksheetInfo = [];
226
227 13
        $this->zip = $zip = new ZipArchive();
228 13
        $zip->open($filename);
229
230 13
        $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
231 13
        foreach ($rels->Relationship as $relx) {
232 13
            $rel = self::getAttributes($relx);
233 13
            $relType = (string) $rel['Type'];
234 13
            $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
235 13
            if ($mainNS !== '') {
236 13
                $relTarget = (string) $rel['Target'];
237 13
                $dir = dirname($relTarget);
238 13
                $namespace = dirname($relType);
239 13
                $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', '');
240
241 13
                $worksheets = [];
242 13
                foreach ($relsWorkbook->Relationship as $elex) {
243 13
                    $ele = self::getAttributes($elex);
244
                    if (
245 13
                        ((string) $ele['Type'] === "$namespace/worksheet") ||
246 13
                        ((string) $ele['Type'] === "$namespace/chartsheet")
247
                    ) {
248 13
                        $worksheets[(string) $ele['Id']] = $ele['Target'];
249
                    }
250
                }
251
252 13
                $xmlWorkbook = $this->loadZip($relTarget, $mainNS);
253 13
                if ($xmlWorkbook->sheets) {
254 13
                    $dir = dirname($relTarget);
255
256
                    /** @var SimpleXMLElement $eleSheet */
257 13
                    foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
258 13
                        $tmpInfo = [
259 13
                            'worksheetName' => (string) self::getAttributes($eleSheet)['name'],
260 13
                            'lastColumnLetter' => 'A',
261 13
                            'lastColumnIndex' => 0,
262 13
                            'totalRows' => 0,
263 13
                            'totalColumns' => 0,
264 13
                        ];
265
266 13
                        $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $namespace), 'id')];
267 13
                        $fileWorksheetPath = strpos($fileWorksheet, '/') === 0 ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet";
268
269 13
                        $xml = new XMLReader();
270 13
                        $xml->xml(
271 13
                            $this->getSecurityScannerOrThrow()->scan(
272 13
                                $this->getFromZipArchive($this->zip, $fileWorksheetPath)
273 13
                            ),
274 13
                            null,
275 13
                            Settings::getLibXmlLoaderOptions()
276 13
                        );
277 13
                        $xml->setParserProperty(2, true);
278
279 13
                        $currCells = 0;
280 13
                        while ($xml->read()) {
281 13
                            if ($xml->localName == 'row' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) {
282 13
                                $row = $xml->getAttribute('r');
283 13
                                $tmpInfo['totalRows'] = $row;
284 13
                                $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
285 13
                                $currCells = 0;
286 13
                            } elseif ($xml->localName == 'c' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) {
287 13
                                $cell = $xml->getAttribute('r');
288 13
                                $currCells = $cell ? max($currCells, Coordinate::indexesFromString($cell)[0]) : ($currCells + 1);
289
                            }
290
                        }
291 13
                        $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
292 13
                        $xml->close();
293
294 13
                        $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
295 13
                        $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
296
297 13
                        $worksheetInfo[] = $tmpInfo;
298
                    }
299
                }
300
            }
301
        }
302
303 13
        $zip->close();
304
305 13
        return $worksheetInfo;
306
    }
307
308 17
    private static function castToBoolean(SimpleXMLElement $c): bool
309
    {
310 17
        $value = isset($c->v) ? (string) $c->v : null;
311 17
        if ($value == '0') {
312 12
            return false;
313 15
        } elseif ($value == '1') {
314 15
            return true;
315
        }
316
317
        return (bool) $c->v;
318
    }
319
320 182
    private static function castToError(?SimpleXMLElement $c): ?string
321
    {
322 182
        return isset($c, $c->v) ? (string) $c->v : null;
323
    }
324
325 441
    private static function castToString(?SimpleXMLElement $c): ?string
326
    {
327 441
        return isset($c, $c->v) ? (string) $c->v : null;
328
    }
329
330
    /**
331
     * @param mixed $value
332
     * @param mixed $calculatedValue
333
     */
334 308
    private function castToFormula(?SimpleXMLElement $c, string $r, string &$cellDataType, &$value, &$calculatedValue, string $castBaseType, bool $updateSharedCells = true): void
335
    {
336 308
        if ($c === null) {
337
            return;
338
        }
339 308
        $attr = $c->f->attributes();
340 308
        $cellDataType = DataType::TYPE_FORMULA;
341 308
        $value = "={$c->f}";
342 308
        $calculatedValue = self::$castBaseType($c);
343
344
        // Shared formula?
345 308
        if (isset($attr['t']) && strtolower((string) $attr['t']) == 'shared') {
346 203
            $instance = (string) $attr['si'];
347
348 203
            if (!isset($this->sharedFormulae[(string) $attr['si']])) {
349 203
                $this->sharedFormulae[$instance] = new SharedFormula($r, $value);
350 202
            } elseif ($updateSharedCells === true) {
351
                // It's only worth the overhead of adjusting the shared formula for this cell if we're actually loading
352
                //     the cell, which may not be the case if we're using a read filter.
353 202
                $master = Coordinate::indexesFromString($this->sharedFormulae[$instance]->master());
354 202
                $current = Coordinate::indexesFromString($r);
355
356 202
                $difference = [0, 0];
357 202
                $difference[0] = $current[0] - $master[0];
358 202
                $difference[1] = $current[1] - $master[1];
359
360 202
                $value = $this->referenceHelper->updateFormulaReferences($this->sharedFormulae[$instance]->formula(), 'A1', $difference[0], $difference[1]);
361
            }
362
        }
363
    }
364
365
    /**
366
     * @param string $fileName
367
     */
368 22
    private function fileExistsInArchive(ZipArchive $archive, $fileName = ''): bool
369
    {
370
        // Root-relative paths
371 22
        if (strpos($fileName, '//') !== false) {
372
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
373
        }
374 22
        $fileName = File::realpath($fileName);
375
376
        // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
377
        //    so we need to load case-insensitively from the zip file
378
379
        // Apache POI fixes
380 22
        $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE);
381 22
        if ($contents === false) {
382
            $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE);
383
        }
384
385 22
        return $contents !== false;
386
    }
387
388
    /**
389
     * @param string $fileName
390
     *
391
     * @return string
392
     */
393 534
    private function getFromZipArchive(ZipArchive $archive, $fileName = '')
394
    {
395
        // Root-relative paths
396 534
        if (strpos($fileName, '//') !== false) {
397 10
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
398
        }
399
        // Relative paths generated by dirname($filename) when $filename
400
        // has no path (i.e.files in root of the zip archive)
401 534
        $fileName = (string) preg_replace('/^\.\//', '', $fileName);
402 534
        $fileName = File::realpath($fileName);
403
404
        // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
405
        //    so we need to load case-insensitively from the zip file
406
407 534
        $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
408
409
        // Apache POI fixes
410 534
        if ($contents === false) {
411 38
            $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
412
        }
413
414
        // Has the file been saved with Windoze directory separators rather than unix?
415 534
        if ($contents === false) {
416 28
            $contents = $archive->getFromName(str_replace('/', '\\', $fileName), 0, ZipArchive::FL_NOCASE);
417
        }
418
419 534
        return ($contents === false) ? '' : $contents;
420
    }
421
422
    /**
423
     * Loads Spreadsheet from file.
424
     */
425 512
    protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
426
    {
427 512
        File::assertFile($filename, self::INITIAL_FILE);
428
429
        // Initialisations
430 509
        $excel = new Spreadsheet();
431 509
        $excel->removeSheetByIndex(0);
432 509
        $addingFirstCellStyleXf = true;
433 509
        $addingFirstCellXf = true;
434
435 509
        $unparsedLoadedData = [];
436
437 509
        $this->zip = $zip = new ZipArchive();
438 509
        $zip->open($filename);
439
440
        //    Read the theme first, because we need the colour scheme when reading the styles
441 509
        [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName();
442 509
        $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML;
443 509
        $chartNS = self::REL_TO_CHART[$xmlNamespaceBase] ?? Namespaces::CHART;
444 509
        $wbRels = $this->loadZip("xl/_rels/{$workbookBasename}.rels", Namespaces::RELATIONSHIPS);
445 509
        $theme = null;
446 509
        $this->styleReader = new Styles();
447 509
        foreach ($wbRels->Relationship as $relx) {
448 508
            $rel = self::getAttributes($relx);
449 508
            $relTarget = (string) $rel['Target'];
450 508
            if (substr($relTarget, 0, 4) === '/xl/') {
451 9
                $relTarget = substr($relTarget, 4);
452
            }
453 508
            switch ($rel['Type']) {
454 508
                case "$xmlNamespaceBase/theme":
455 501
                    $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
456 501
                    $themeOrderAdditional = count($themeOrderArray);
457
458 501
                    $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS);
459 501
                    $xmlThemeName = self::getAttributes($xmlTheme);
460 501
                    $xmlTheme = $xmlTheme->children($drawingNS);
461 501
                    $themeName = (string) $xmlThemeName['name'];
462
463 501
                    $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme);
464 501
                    $colourSchemeName = (string) $colourScheme['name'];
465 501
                    $excel->getTheme()->setThemeColorName($colourSchemeName);
466 501
                    $colourScheme = $xmlTheme->themeElements->clrScheme->children($drawingNS);
467
468 501
                    $themeColours = [];
469 501
                    foreach ($colourScheme as $k => $xmlColour) {
470 501
                        $themePos = array_search($k, $themeOrderArray);
471 501
                        if ($themePos === false) {
472 501
                            $themePos = $themeOrderAdditional++;
473
                        }
474 501
                        if (isset($xmlColour->sysClr)) {
475 496
                            $xmlColourData = self::getAttributes($xmlColour->sysClr);
476 496
                            $themeColours[$themePos] = (string) $xmlColourData['lastClr'];
477 496
                            $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['lastClr']);
478 501
                        } elseif (isset($xmlColour->srgbClr)) {
479 501
                            $xmlColourData = self::getAttributes($xmlColour->srgbClr);
480 501
                            $themeColours[$themePos] = (string) $xmlColourData['val'];
481 501
                            $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['val']);
482
                        }
483
                    }
484 501
                    $theme = new Theme($themeName, $colourSchemeName, $themeColours);
485 501
                    $this->styleReader->setTheme($theme);
486
487 501
                    $fontScheme = self::getAttributes($xmlTheme->themeElements->fontScheme);
488 501
                    $fontSchemeName = (string) $fontScheme['name'];
489 501
                    $excel->getTheme()->setThemeFontName($fontSchemeName);
490 501
                    $majorFonts = [];
491 501
                    $minorFonts = [];
492 501
                    $fontScheme = $xmlTheme->themeElements->fontScheme->children($drawingNS);
493 501
                    $majorLatin = self::getAttributes($fontScheme->majorFont->latin)['typeface'] ?? '';
494 501
                    $majorEastAsian = self::getAttributes($fontScheme->majorFont->ea)['typeface'] ?? '';
495 501
                    $majorComplexScript = self::getAttributes($fontScheme->majorFont->cs)['typeface'] ?? '';
496 501
                    $minorLatin = self::getAttributes($fontScheme->minorFont->latin)['typeface'] ?? '';
497 501
                    $minorEastAsian = self::getAttributes($fontScheme->minorFont->ea)['typeface'] ?? '';
498 501
                    $minorComplexScript = self::getAttributes($fontScheme->minorFont->cs)['typeface'] ?? '';
499
500 501
                    foreach ($fontScheme->majorFont->font as $xmlFont) {
501 495
                        $fontAttributes = self::getAttributes($xmlFont);
502 495
                        $script = (string) ($fontAttributes['script'] ?? '');
503 495
                        if (!empty($script)) {
504 495
                            $majorFonts[$script] = (string) ($fontAttributes['typeface'] ?? '');
505
                        }
506
                    }
507 501
                    foreach ($fontScheme->minorFont->font as $xmlFont) {
508 495
                        $fontAttributes = self::getAttributes($xmlFont);
509 495
                        $script = (string) ($fontAttributes['script'] ?? '');
510 495
                        if (!empty($script)) {
511 495
                            $minorFonts[$script] = (string) ($fontAttributes['typeface'] ?? '');
512
                        }
513
                    }
514 501
                    $excel->getTheme()->setMajorFontValues($majorLatin, $majorEastAsian, $majorComplexScript, $majorFonts);
515 501
                    $excel->getTheme()->setMinorFontValues($minorLatin, $minorEastAsian, $minorComplexScript, $minorFonts);
516
517 501
                    break;
518
            }
519
        }
520
521 509
        $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
522
523 509
        $propertyReader = new PropertyReader($this->getSecurityScannerOrThrow(), $excel->getProperties());
524 509
        $chartDetails = [];
525 509
        foreach ($rels->Relationship as $relx) {
526 509
            $rel = self::getAttributes($relx);
527 509
            $relTarget = (string) $rel['Target'];
528 509
            $relType = (string) $rel['Type'];
529 509
            $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
530
            switch ($relType) {
531 14
                case Namespaces::CORE_PROPERTIES:
532 503
                    $propertyReader->readCoreProperties($this->getFromZipArchive($zip, $relTarget));
533
534 503
                    break;
535 509
                case "$xmlNamespaceBase/extended-properties":
536 501
                    $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget));
537
538 501
                    break;
539 509
                case "$xmlNamespaceBase/custom-properties":
540 36
                    $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget));
541
542 36
                    break;
543
                    //Ribbon
544 509
                case Namespaces::EXTENSIBILITY:
545 2
                    $customUI = $relTarget;
546 2
                    if ($customUI) {
547 2
                        $this->readRibbon($excel, $customUI, $zip);
548
                    }
549
550 2
                    break;
551 509
                case "$xmlNamespaceBase/officeDocument":
552 509
                    $dir = dirname($relTarget);
553
554
                    // Do not specify namespace in next stmt - do it in Xpath
555 509
                    $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', '');
556 509
                    $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS);
557
558 509
                    $worksheets = [];
559 509
                    $macros = $customUI = null;
560 509
                    foreach ($relsWorkbook->Relationship as $elex) {
561 509
                        $ele = self::getAttributes($elex);
562 509
                        switch ($ele['Type']) {
563 14
                            case Namespaces::WORKSHEET:
564 14
                            case Namespaces::PURL_WORKSHEET:
565 509
                                $worksheets[(string) $ele['Id']] = $ele['Target'];
566
567 509
                                break;
568 14
                            case Namespaces::CHARTSHEET:
569 2
                                if ($this->includeCharts === true) {
570 1
                                    $worksheets[(string) $ele['Id']] = $ele['Target'];
571
                                }
572
573 2
                                break;
574
                                // a vbaProject ? (: some macros)
575 14
                            case Namespaces::VBA:
576 3
                                $macros = $ele['Target'];
577
578 3
                                break;
579
                        }
580
                    }
581
582 509
                    if ($macros !== null) {
583 3
                        $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin
584 3
                        if ($macrosCode !== false) {
585 3
                            $excel->setMacrosCode($macrosCode);
586 3
                            $excel->setHasMacros(true);
587
                            //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir
588 3
                            $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin');
589 3
                            if ($Certificate !== false) {
590 3
                                $excel->setMacrosCertificate($Certificate);
591
                            }
592
                        }
593
                    }
594
595 509
                    $relType = "rel:Relationship[@Type='"
596 509
                        . "$xmlNamespaceBase/styles"
597 509
                        . "']";
598 509
                    $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType));
599
600 509
                    if ($xpath === null) {
601 1
                        $xmlStyles = self::testSimpleXml(null);
602
                    } else {
603 509
                        $xmlStyles = $this->loadZip("$dir/$xpath[Target]", $mainNS);
604
                    }
605
606 509
                    $palette = self::extractPalette($xmlStyles);
607 509
                    $this->styleReader->setWorkbookPalette($palette);
608 509
                    $fills = self::extractStyles($xmlStyles, 'fills', 'fill');
609 509
                    $fonts = self::extractStyles($xmlStyles, 'fonts', 'font');
610 509
                    $borders = self::extractStyles($xmlStyles, 'borders', 'border');
611 509
                    $xfTags = self::extractStyles($xmlStyles, 'cellXfs', 'xf');
612 509
                    $cellXfTags = self::extractStyles($xmlStyles, 'cellStyleXfs', 'xf');
613
614 509
                    $styles = [];
615 509
                    $cellStyles = [];
616 509
                    $numFmts = null;
617 509
                    if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) {
618 218
                        $numFmts = $xmlStyles->numFmts[0];
619
                    }
620 509
                    if (isset($numFmts) && ($numFmts !== null)) {
621 218
                        $numFmts->registerXPathNamespace('sml', $mainNS);
622
                    }
623 509
                    $this->styleReader->setNamespace($mainNS);
624 509
                    if (!$this->readDataOnly/* && $xmlStyles*/) {
625 509
                        foreach ($xfTags as $xfTag) {
626 509
                            $xf = self::getAttributes($xfTag);
627 509
                            $numFmt = null;
628
629 509
                            if ($xf['numFmtId']) {
630 507
                                if (isset($numFmts)) {
631 218
                                    $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
632
633 218
                                    if (isset($tmpNumFmt['formatCode'])) {
634 217
                                        $numFmt = (string) $tmpNumFmt['formatCode'];
635
                                    }
636
                                }
637
638
                                // We shouldn't override any of the built-in MS Excel values (values below id 164)
639
                                //  But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used
640
                                //  So we make allowance for them rather than lose formatting masks
641
                                if (
642 507
                                    $numFmt === null &&
643 507
                                    (int) $xf['numFmtId'] < 164 &&
644 507
                                    NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== ''
645
                                ) {
646 503
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
647
                                }
648
                            }
649 509
                            $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? '');
650
651 509
                            $style = (object) [
652 509
                                'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL,
653 509
                                'font' => $fonts[(int) ($xf['fontId'])],
654 509
                                'fill' => $fills[(int) ($xf['fillId'])],
655 509
                                'border' => $borders[(int) ($xf['borderId'])],
656 509
                                'alignment' => $xfTag->alignment,
657 509
                                'protection' => $xfTag->protection,
658 509
                                'quotePrefix' => $quotePrefix,
659 509
                            ];
660 509
                            $styles[] = $style;
661
662
                            // add style to cellXf collection
663 509
                            $objStyle = new Style();
664 509
                            $this->styleReader->readStyle($objStyle, $style);
665 509
                            if ($addingFirstCellXf) {
666 509
                                $excel->removeCellXfByIndex(0); // remove the default style
667 509
                                $addingFirstCellXf = false;
668
                            }
669 509
                            $excel->addCellXf($objStyle);
670
                        }
671
672 509
                        foreach ($cellXfTags as $xfTag) {
673 509
                            $xf = self::getAttributes($xfTag);
674 509
                            $numFmt = NumberFormat::FORMAT_GENERAL;
675 509
                            if ($numFmts && $xf['numFmtId']) {
676 218
                                $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
677 218
                                if (isset($tmpNumFmt['formatCode'])) {
678 13
                                    $numFmt = (string) $tmpNumFmt['formatCode'];
679 216
                                } elseif ((int) $xf['numFmtId'] < 165) {
680 216
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
681
                                }
682
                            }
683
684 509
                            $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? '');
685
686 509
                            $cellStyle = (object) [
687 509
                                'numFmt' => $numFmt,
688 509
                                'font' => $fonts[(int) ($xf['fontId'])],
689 509
                                'fill' => $fills[((int) $xf['fillId'])],
690 509
                                'border' => $borders[(int) ($xf['borderId'])],
691 509
                                'alignment' => $xfTag->alignment,
692 509
                                'protection' => $xfTag->protection,
693 509
                                'quotePrefix' => $quotePrefix,
694 509
                            ];
695 509
                            $cellStyles[] = $cellStyle;
696
697
                            // add style to cellStyleXf collection
698 509
                            $objStyle = new Style();
699 509
                            $this->styleReader->readStyle($objStyle, $cellStyle);
700 509
                            if ($addingFirstCellStyleXf) {
701 509
                                $excel->removeCellStyleXfByIndex(0); // remove the default style
702 509
                                $addingFirstCellStyleXf = false;
703
                            }
704 509
                            $excel->addCellStyleXf($objStyle);
705
                        }
706
                    }
707 509
                    $this->styleReader->setStyleXml($xmlStyles);
708 509
                    $this->styleReader->setNamespace($mainNS);
709 509
                    $this->styleReader->setStyleBaseData($theme, $styles, $cellStyles);
710 509
                    $dxfs = $this->styleReader->dxfs($this->readDataOnly);
711 509
                    $styles = $this->styleReader->styles();
712
713
                    // Read content after setting the styles
714 509
                    $sharedStrings = [];
715 509
                    $relType = "rel:Relationship[@Type='"
716 509
                        //. Namespaces::SHARED_STRINGS
717 509
                        . "$xmlNamespaceBase/sharedStrings"
718 509
                        . "']";
719 509
                    $xpath = self::getArrayItem($relsWorkbook->xpath($relType));
720
721 509
                    if ($xpath) {
722 482
                        $xmlStrings = $this->loadZip("$dir/$xpath[Target]", $mainNS);
723 482
                        if (isset($xmlStrings->si)) {
724 410
                            foreach ($xmlStrings->si as $val) {
725 410
                                if (isset($val->t)) {
726 408
                                    $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
727 30
                                } elseif (isset($val->r)) {
728 30
                                    $sharedStrings[] = $this->parseRichText($val);
729
                                }
730
                            }
731
                        }
732
                    }
733
734 509
                    $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS);
735 509
                    $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS);
736
737
                    // Set base date
738 509
                    if ($xmlWorkbookNS->workbookPr) {
739 502
                        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
740 502
                        $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr);
741 502
                        if (isset($attrs1904['date1904'])) {
742 8
                            if (self::boolean((string) $attrs1904['date1904'])) {
743
                                Date::setExcelCalendar(Date::CALENDAR_MAC_1904);
744
                            }
745
                        }
746
                    }
747
748
                    // Set protection
749 509
                    $this->readProtection($excel, $xmlWorkbook);
750
751 509
                    $sheetId = 0; // keep track of new sheet id in final workbook
752 509
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
753 509
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
754 509
                    $mapSheetId = []; // mapping of sheet ids from old to new
755
756 509
                    $charts = $chartDetails = [];
757
758 509
                    if ($xmlWorkbookNS->sheets) {
759
                        /** @var SimpleXMLElement $eleSheet */
760 509
                        foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) {
761 509
                            $eleSheetAttr = self::getAttributes($eleSheet);
762 509
                            ++$oldSheetId;
763
764
                            // Check if sheet should be skipped
765 509
                            if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) {
766 1
                                ++$countSkippedSheets;
767 1
                                $mapSheetId[$oldSheetId] = null;
768
769 1
                                continue;
770
                            }
771
772 509
                            $sheetReferenceId = (string) self::getArrayItem(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id');
773 509
                            if (isset($worksheets[$sheetReferenceId]) === false) {
774 1
                                ++$countSkippedSheets;
775 1
                                $mapSheetId[$oldSheetId] = null;
776
777 1
                                continue;
778
                            }
779
                            // Map old sheet id in original workbook to new sheet id.
780
                            // They will differ if loadSheetsOnly() is being used
781 509
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
782
783
                            // Load sheet
784 509
                            $docSheet = $excel->createSheet();
785
                            //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet
786
                            //        references in formula cells... during the load, all formulae should be correct,
787
                            //        and we're simply bringing the worksheet name in line with the formula, not the
788
                            //        reverse
789 509
                            $docSheet->setTitle((string) $eleSheetAttr['name'], false, false);
790
791 509
                            $fileWorksheet = (string) $worksheets[$sheetReferenceId];
792 509
                            $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS);
793 509
                            $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS);
794
795
                            // Shared Formula table is unique to each Worksheet, so we need to reset it here
796 509
                            $this->sharedFormulae = [];
797
798 509
                            if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') {
799 18
                                $docSheet->setSheetState((string) $eleSheetAttr['state']);
800
                            }
801 509
                            if ($xmlSheetNS) {
802 509
                                $xmlSheetMain = $xmlSheetNS->children($mainNS);
803
                                // Setting Conditional Styles adjusts selected cells, so we need to execute this
804
                                //    before reading the sheet view data to get the actual selected cells
805 509
                                if (!$this->readDataOnly && ($xmlSheet->conditionalFormatting)) {
806 199
                                    (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load();
807
                                }
808 509
                                if (!$this->readDataOnly && $xmlSheet->extLst) {
809 196
                                    (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->loadFromExt($this->styleReader);
810
                                }
811 509
                                if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) {
812 507
                                    $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet);
813 507
                                    $sheetViews->load();
814
                                }
815
816 509
                                $sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheetNS);
817 509
                                $sheetViewOptions->load($this->getReadDataOnly(), $this->styleReader);
818
819 509
                                (new ColumnAndRowAttributes($docSheet, $xmlSheetNS))
820 509
                                    ->load($this->getReadFilter(), $this->getReadDataOnly());
821
                            }
822
823 509
                            if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) {
824 493
                                $cIndex = 1; // Cell Start from 1
825 493
                                foreach ($xmlSheetNS->sheetData->row as $row) {
826 493
                                    $rowIndex = 1;
827 493
                                    foreach ($row->c as $c) {
828 492
                                        $cAttr = self::getAttributes($c);
829 492
                                        $r = (string) $cAttr['r'];
830 492
                                        if ($r == '') {
831 1
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
832
                                        }
833 492
                                        $cellDataType = (string) $cAttr['t'];
834 492
                                        $value = null;
835 492
                                        $calculatedValue = null;
836
837
                                        // Read cell?
838 492
                                        if ($this->getReadFilter() !== null) {
839 492
                                            $coordinates = Coordinate::coordinateFromString($r);
840
841 492
                                            if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) {
842
                                                // Normally, just testing for the f attribute should identify this cell as containing a formula
843
                                                // that we need to read, even though it is outside of the filter range, in case it is a shared formula.
844
                                                // But in some cases, this attribute isn't set; so we need to delve a level deeper and look at
845
                                                // whether or not the cell has a child formula element that is shared.
846 3
                                                if (isset($cAttr->f) || (isset($c->f, $c->f->attributes()['t']) && strtolower((string) $c->f->attributes()['t']) === 'shared')) {
847
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError', false);
848
                                                }
849 3
                                                ++$rowIndex;
850
851 3
                                                continue;
852
                                            }
853
                                        }
854
855
                                        // Read cell!
856
                                        switch ($cellDataType) {
857 492
                                            case 's':
858 409
                                                if ((string) $c->v != '') {
859 409
                                                    $value = $sharedStrings[(int) ($c->v)];
860
861 409
                                                    if ($value instanceof RichText) {
862 409
                                                        $value = clone $value;
863
                                                    }
864
                                                } else {
865 3
                                                    $value = '';
866
                                                }
867
868 409
                                                break;
869 448
                                            case 'b':
870 17
                                                if (!isset($c->f)) {
871 14
                                                    if (isset($c->v)) {
872 14
                                                        $value = self::castToBoolean($c);
873
                                                    } else {
874 1
                                                        $value = null;
875 14
                                                        $cellDataType = DATATYPE::TYPE_NULL;
876
                                                    }
877
                                                } else {
878
                                                    // Formula
879 3
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToBoolean');
880 3
                                                    if (isset($c->f['t'])) {
881
                                                        $att = $c->f;
882
                                                        $docSheet->getCell($r)->setFormulaAttributes($att);
883
                                                    }
884
                                                }
885
886 17
                                                break;
887 444
                                            case 'inlineStr':
888 10
                                                if (isset($c->f)) {
889
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError');
890
                                                } else {
891 10
                                                    $value = $this->parseRichText($c->is);
892
                                                }
893
894 10
                                                break;
895 441
                                            case 'e':
896 182
                                                if (!isset($c->f)) {
897
                                                    $value = self::castToError($c);
898
                                                } else {
899
                                                    // Formula
900 182
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError');
901
                                                }
902
903 182
                                                break;
904
                                            default:
905 441
                                                if (!isset($c->f)) {
906 433
                                                    $value = self::castToString($c);
907
                                                } else {
908
                                                    // Formula
909 307
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToString');
910 307
                                                    if (isset($c->f['t'])) {
911
                                                        $attributes = $c->f['t'];
912
                                                        $docSheet->getCell($r)->setFormulaAttributes(['t' => (string) $attributes]);
913
                                                    }
914
                                                }
915
916 441
                                                break;
917
                                        }
918
919
                                        // read empty cells or the cells are not empty
920 492
                                        if ($this->readEmptyCells || ($value !== null && $value !== '')) {
921
                                            // Rich text?
922 492
                                            if ($value instanceof RichText && $this->readDataOnly) {
923
                                                $value = $value->getPlainText();
924
                                            }
925
926 492
                                            $cell = $docSheet->getCell($r);
927
                                            // Assign value
928 492
                                            if ($cellDataType != '') {
929
                                                // it is possible, that datatype is numeric but with an empty string, which result in an error
930 435
                                                if ($cellDataType === DataType::TYPE_NUMERIC && ($value === '' || $value === null)) {
931 1
                                                    $cellDataType = DataType::TYPE_NULL;
932
                                                }
933 435
                                                if ($cellDataType !== DataType::TYPE_NULL) {
934 435
                                                    $cell->setValueExplicit($value, $cellDataType);
935
                                                }
936
                                            } else {
937 427
                                                $cell->setValue($value);
938
                                            }
939 492
                                            if ($calculatedValue !== null) {
940 308
                                                $cell->setCalculatedValue($calculatedValue);
941
                                            }
942
943
                                            // Style information?
944 492
                                            if ($cAttr['s'] && !$this->readDataOnly) {
945
                                                // no style index means 0, it seems
946 331
                                                $cell->setXfIndex(isset($styles[(int) ($cAttr['s'])]) ?
947 331
                                                    (int) ($cAttr['s']) : 0);
948
                                                // issue 3495
949 331
                                                if ($cell->getDataType() === DataType::TYPE_FORMULA) {
950 217
                                                    $cell->getStyle()->setQuotePrefix(false);
951
                                                }
952
                                            }
953
                                        }
954 492
                                        ++$rowIndex;
955
                                    }
956 493
                                    ++$cIndex;
957
                                }
958
                            }
959
960 509
                            if (!$this->readDataOnly && $xmlSheetNS && $xmlSheetNS->sheetProtection) {
961 62
                                $protAttr = $xmlSheetNS->sheetProtection->attributes() ?? [];
962 62
                                foreach ($protAttr as $key => $value) {
963 62
                                    $method = 'set' . ucfirst($key);
964 62
                                    $docSheet->getProtection()->$method(self::boolean((string) $value));
965
                                }
966
                            }
967
968 509
                            if ($xmlSheet) {
969 501
                                $this->readSheetProtection($docSheet, $xmlSheet);
970
                            }
971
972 509
                            if ($this->readDataOnly === false) {
973 509
                                $this->readAutoFilter($xmlSheet, $docSheet);
974 509
                                $this->readTables($xmlSheet, $docSheet, $dir, $fileWorksheet, $zip);
975
                            }
976
977 509
                            if ($xmlSheetNS && $xmlSheetNS->mergeCells && $xmlSheetNS->mergeCells->mergeCell && !$this->readDataOnly) {
978 46
                                foreach ($xmlSheetNS->mergeCells->mergeCell as $mergeCellx) {
979
                                    /** @scrutinizer ignore-call */
980 46
                                    $mergeCell = $mergeCellx->attributes();
981 46
                                    $mergeRef = (string) ($mergeCell['ref'] ?? '');
982 46
                                    if (strpos($mergeRef, ':') !== false) {
983 46
                                        $docSheet->mergeCells($mergeRef, Worksheet::MERGE_CELL_CONTENT_HIDE);
984
                                    }
985
                                }
986
                            }
987
988 509
                            if ($xmlSheet && !$this->readDataOnly) {
989 501
                                $unparsedLoadedData = (new PageSetup($docSheet, $xmlSheet))->load($unparsedLoadedData);
990
                            }
991
992 509
                            if ($xmlSheet !== false && isset($xmlSheet->extLst, $xmlSheet->extLst->ext, $xmlSheet->extLst->ext['uri']) && ($xmlSheet->extLst->ext['uri'] == '{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}')) {
993
                                // Create dataValidations node if does not exists, maybe is better inside the foreach ?
994 5
                                if (!$xmlSheet->dataValidations) {
995
                                    $xmlSheet->addChild('dataValidations');
996
                                }
997
998 5
                                foreach ($xmlSheet->extLst->ext->children(Namespaces::DATA_VALIDATIONS1)->dataValidations->dataValidation as $item) {
999 5
                                    $item = self::testSimpleXml($item);
1000 5
                                    $node = self::testSimpleXml($xmlSheet->dataValidations)->addChild('dataValidation');
1001 5
                                    foreach ($item->attributes() ?? [] as $attr) {
1002 5
                                        $node->addAttribute($attr->getName(), $attr);
1003
                                    }
1004 5
                                    $node->addAttribute('sqref', $item->children(Namespaces::DATA_VALIDATIONS2)->sqref);
1005 5
                                    if (isset($item->formula1)) {
1006 5
                                        $childNode = $node->addChild('formula1');
1007 5
                                        if ($childNode !== null) { // null should never happen
1008 5
                                            $childNode[0] = (string) $item->formula1->children(Namespaces::DATA_VALIDATIONS2)->f; // @phpstan-ignore-line
1009
                                        }
1010
                                    }
1011
                                }
1012
                            }
1013
1014 509
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
1015 12
                                (new DataValidations($docSheet, $xmlSheet))->load();
1016
                            }
1017
1018
                            // unparsed sheet AlternateContent
1019 509
                            if ($xmlSheet && !$this->readDataOnly) {
1020 501
                                $mc = $xmlSheet->children(Namespaces::COMPATIBILITY);
1021 501
                                if ($mc->AlternateContent) {
1022 3
                                    foreach ($mc->AlternateContent as $alternateContent) {
1023 3
                                        $alternateContent = self::testSimpleXml($alternateContent);
1024 3
                                        $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
1025
                                    }
1026
                                }
1027
                            }
1028
1029
                            // Add hyperlinks
1030 509
                            if (!$this->readDataOnly) {
1031 509
                                $hyperlinkReader = new Hyperlinks($docSheet);
1032
                                // Locate hyperlink relations
1033 509
                                $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
1034 509
                                if ($zip->locateName($relationsFileName)) {
1035 422
                                    $relsWorksheet = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS);
1036 422
                                    $hyperlinkReader->readHyperlinks($relsWorksheet);
1037
                                }
1038
1039
                                // Loop through hyperlinks
1040 509
                                if ($xmlSheetNS && $xmlSheetNS->children($mainNS)->hyperlinks) {
1041 14
                                    $hyperlinkReader->setHyperlinks($xmlSheetNS->children($mainNS)->hyperlinks);
1042
                                }
1043
                            }
1044
1045
                            // Add comments
1046 509
                            $comments = [];
1047 509
                            $vmlComments = [];
1048 509
                            if (!$this->readDataOnly) {
1049
                                // Locate comment relations
1050 509
                                $commentRelations = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
1051 509
                                if ($zip->locateName($commentRelations)) {
1052 422
                                    $relsWorksheet = $this->loadZip($commentRelations, Namespaces::RELATIONSHIPS);
1053 422
                                    foreach ($relsWorksheet->Relationship as $elex) {
1054 327
                                        $ele = self::getAttributes($elex);
1055 327
                                        if ($ele['Type'] == Namespaces::COMMENTS) {
1056 20
                                            $comments[(string) $ele['Id']] = (string) $ele['Target'];
1057
                                        }
1058 327
                                        if ($ele['Type'] == Namespaces::VML) {
1059 23
                                            $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
1060
                                        }
1061
                                    }
1062
                                }
1063
1064
                                // Loop through comments
1065 509
                                foreach ($comments as $relName => $relPath) {
1066
                                    // Load comments file
1067 20
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1068
                                    // okay to ignore namespace - using xpath
1069 20
                                    $commentsFile = $this->loadZip($relPath, '');
1070
1071
                                    // Utility variables
1072 20
                                    $authors = [];
1073 20
                                    $commentsFile->registerXpathNamespace('com', $mainNS);
1074 20
                                    $authorPath = self::xpathNoFalse($commentsFile, 'com:authors/com:author');
1075 20
                                    foreach ($authorPath as $author) {
1076 20
                                        $authors[] = (string) $author;
1077
                                    }
1078
1079
                                    // Loop through contents
1080 20
                                    $contentPath = self::xpathNoFalse($commentsFile, 'com:commentList/com:comment');
1081 20
                                    foreach ($contentPath as $comment) {
1082 20
                                        $commentx = $comment->attributes();
1083 20
                                        $commentModel = $docSheet->getComment((string) $commentx['ref']);
1084 20
                                        if (isset($commentx['authorId'])) {
1085 20
                                            $commentModel->setAuthor($authors[(int) $commentx['authorId']]);
1086
                                        }
1087 20
                                        $commentModel->setText($this->parseRichText($comment->children($mainNS)->text));
1088
                                    }
1089
                                }
1090
1091
                                // later we will remove from it real vmlComments
1092 509
                                $unparsedVmlDrawings = $vmlComments;
1093 509
                                $vmlDrawingContents = [];
1094
1095
                                // Loop through VML comments
1096 509
                                foreach ($vmlComments as $relName => $relPath) {
1097
                                    // Load VML comments file
1098 23
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1099
1100
                                    try {
1101
                                        // no namespace okay - processed with Xpath
1102 23
                                        $vmlCommentsFile = $this->loadZip($relPath, '', true);
1103 23
                                        $vmlCommentsFile->registerXPathNamespace('v', Namespaces::URN_VML);
1104
                                    } catch (Throwable $ex) {
1105
                                        //Ignore unparsable vmlDrawings. Later they will be moved from $unparsedVmlDrawings to $unparsedLoadedData
1106
                                        continue;
1107
                                    }
1108
1109
                                    // Locate VML drawings image relations
1110 23
                                    $drowingImages = [];
1111 23
                                    $VMLDrawingsRelations = dirname($relPath) . '/_rels/' . basename($relPath) . '.rels';
1112 23
                                    $vmlDrawingContents[$relName] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $relPath));
1113 23
                                    if ($zip->locateName($VMLDrawingsRelations)) {
1114 9
                                        $relsVMLDrawing = $this->loadZip($VMLDrawingsRelations, Namespaces::RELATIONSHIPS);
1115 9
                                        foreach ($relsVMLDrawing->Relationship as $elex) {
1116 5
                                            $ele = self::getAttributes($elex);
1117 5
                                            if ($ele['Type'] == Namespaces::IMAGE) {
1118 5
                                                $drowingImages[(string) $ele['Id']] = (string) $ele['Target'];
1119
                                            }
1120
                                        }
1121
                                    }
1122
1123 23
                                    $shapes = self::xpathNoFalse($vmlCommentsFile, '//v:shape');
1124 23
                                    foreach ($shapes as $shape) {
1125 23
                                        $shape->registerXPathNamespace('v', Namespaces::URN_VML);
1126
1127 23
                                        if (isset($shape['style'])) {
1128 23
                                            $style = (string) $shape['style'];
1129 23
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
1130 23
                                            $column = null;
1131 23
                                            $row = null;
1132 23
                                            $fillImageRelId = null;
1133 23
                                            $fillImageTitle = '';
1134
1135 23
                                            $clientData = $shape->xpath('.//x:ClientData');
1136 23
                                            if (is_array($clientData) && !empty($clientData)) {
1137 22
                                                $clientData = $clientData[0];
1138
1139 22
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
1140 20
                                                    $temp = $clientData->xpath('.//x:Row');
1141 20
                                                    if (is_array($temp)) {
1142 20
                                                        $row = $temp[0];
1143
                                                    }
1144
1145 20
                                                    $temp = $clientData->xpath('.//x:Column');
1146 20
                                                    if (is_array($temp)) {
1147 20
                                                        $column = $temp[0];
1148
                                                    }
1149
                                                }
1150
                                            }
1151
1152 23
                                            $fillImageRelNode = $shape->xpath('.//v:fill/@o:relid');
1153 23
                                            if (is_array($fillImageRelNode) && !empty($fillImageRelNode)) {
1154 3
                                                $fillImageRelNode = $fillImageRelNode[0];
1155
1156 3
                                                if (isset($fillImageRelNode['relid'])) {
1157 3
                                                    $fillImageRelId = (string) $fillImageRelNode['relid'];
1158
                                                }
1159
                                            }
1160
1161 23
                                            $fillImageTitleNode = $shape->xpath('.//v:fill/@o:title');
1162 23
                                            if (is_array($fillImageTitleNode) && !empty($fillImageTitleNode)) {
1163 3
                                                $fillImageTitleNode = $fillImageTitleNode[0];
1164
1165 3
                                                if (isset($fillImageTitleNode['title'])) {
1166 3
                                                    $fillImageTitle = (string) $fillImageTitleNode['title'];
1167
                                                }
1168
                                            }
1169
1170 23
                                            if (($column !== null) && ($row !== null)) {
1171
                                                // Set comment properties
1172 20
                                                $comment = $docSheet->getComment([$column + 1, $row + 1]);
1173 20
                                                $comment->getFillColor()->setRGB($fillColor);
1174 20
                                                if (isset($drowingImages[$fillImageRelId])) {
1175 3
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1176 3
                                                    $objDrawing->setName($fillImageTitle);
1177 3
                                                    $imagePath = str_replace('../', 'xl/', $drowingImages[$fillImageRelId]);
1178 3
                                                    $objDrawing->setPath(
1179 3
                                                        'zip://' . File::realpath($filename) . '#' . $imagePath,
1180 3
                                                        true,
1181 3
                                                        $zip
1182 3
                                                    );
1183 3
                                                    $comment->setBackgroundImage($objDrawing);
1184
                                                }
1185
1186
                                                // Parse style
1187 20
                                                $styleArray = explode(';', str_replace(' ', '', $style));
1188 20
                                                foreach ($styleArray as $stylePair) {
1189 20
                                                    $stylePair = explode(':', $stylePair);
1190
1191 20
                                                    if ($stylePair[0] == 'margin-left') {
1192 19
                                                        $comment->setMarginLeft($stylePair[1]);
1193
                                                    }
1194 20
                                                    if ($stylePair[0] == 'margin-top') {
1195 19
                                                        $comment->setMarginTop($stylePair[1]);
1196
                                                    }
1197 20
                                                    if ($stylePair[0] == 'width') {
1198 19
                                                        $comment->setWidth($stylePair[1]);
1199
                                                    }
1200 20
                                                    if ($stylePair[0] == 'height') {
1201 19
                                                        $comment->setHeight($stylePair[1]);
1202
                                                    }
1203 20
                                                    if ($stylePair[0] == 'visibility') {
1204 20
                                                        $comment->setVisible($stylePair[1] == 'visible');
1205
                                                    }
1206
                                                }
1207
1208 20
                                                unset($unparsedVmlDrawings[$relName]);
1209
                                            }
1210
                                        }
1211
                                    }
1212
                                }
1213
1214
                                // unparsed vmlDrawing
1215 509
                                if ($unparsedVmlDrawings) {
1216 5
                                    foreach ($unparsedVmlDrawings as $rId => $relPath) {
1217 5
                                        $rId = substr($rId, 3); // rIdXXX
1218 5
                                        $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
1219 5
                                        $unparsedVmlDrawing[$rId] = [];
1220 5
                                        $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
1221 5
                                        $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
1222 5
                                        $unparsedVmlDrawing[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
1223 5
                                        unset($unparsedVmlDrawing);
1224
                                    }
1225
                                }
1226
1227
                                // Header/footer images
1228 509
                                if ($xmlSheetNS && $xmlSheetNS->legacyDrawingHF) {
1229 2
                                    $vmlHfRid = '';
1230 2
                                    $vmlHfRidAttr = $xmlSheetNS->legacyDrawingHF->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT);
1231 2
                                    if ($vmlHfRidAttr !== null && isset($vmlHfRidAttr['id'])) {
1232 2
                                        $vmlHfRid = (string) $vmlHfRidAttr['id'][0];
1233
                                    }
1234 2
                                    if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1235 2
                                        $relsWorksheet = $this->loadZipNoNamespace(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels', Namespaces::RELATIONSHIPS);
1236 2
                                        $vmlRelationship = '';
1237
1238 2
                                        foreach ($relsWorksheet->Relationship as $ele) {
1239 2
                                            if ((string) $ele['Type'] == Namespaces::VML && (string) $ele['Id'] === $vmlHfRid) {
1240 2
                                                $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1241
1242 2
                                                break;
1243
                                            }
1244
                                        }
1245
1246 2
                                        if ($vmlRelationship != '') {
1247
                                            // Fetch linked images
1248 2
                                            $relsVML = $this->loadZipNoNamespace(dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels', Namespaces::RELATIONSHIPS);
1249 2
                                            $drawings = [];
1250 2
                                            if (isset($relsVML->Relationship)) {
1251 2
                                                foreach ($relsVML->Relationship as $ele) {
1252 2
                                                    if ($ele['Type'] == Namespaces::IMAGE) {
1253 2
                                                        $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
1254
                                                    }
1255
                                                }
1256
                                            }
1257
                                            // Fetch VML document
1258 2
                                            $vmlDrawing = $this->loadZipNoNamespace($vmlRelationship, '');
1259 2
                                            $vmlDrawing->registerXPathNamespace('v', Namespaces::URN_VML);
1260
1261 2
                                            $hfImages = [];
1262
1263 2
                                            $shapes = self::xpathNoFalse($vmlDrawing, '//v:shape');
1264 2
                                            foreach ($shapes as $idx => $shape) {
1265 2
                                                $shape->registerXPathNamespace('v', Namespaces::URN_VML);
1266 2
                                                $imageData = $shape->xpath('//v:imagedata');
1267
1268 2
                                                if (empty($imageData)) {
1269
                                                    continue;
1270
                                                }
1271
1272 2
                                                $imageData = $imageData[$idx];
1273
1274 2
                                                $imageData = self::getAttributes($imageData, Namespaces::URN_MSOFFICE);
1275 2
                                                $style = self::toCSSArray((string) $shape['style']);
1276
1277 2
                                                if (array_key_exists((string) $imageData['relid'], $drawings)) {
1278 2
                                                    $shapeId = (string) $shape['id'];
1279 2
                                                    $hfImages[$shapeId] = new HeaderFooterDrawing();
1280 2
                                                    if (isset($imageData['title'])) {
1281 2
                                                        $hfImages[$shapeId]->setName((string) $imageData['title']);
1282
                                                    }
1283
1284 2
                                                    $hfImages[$shapeId]->setPath('zip://' . File::realpath($filename) . '#' . $drawings[(string) $imageData['relid']], false);
1285 2
                                                    $hfImages[$shapeId]->setResizeProportional(false);
1286 2
                                                    $hfImages[$shapeId]->setWidth($style['width']);
1287 2
                                                    $hfImages[$shapeId]->setHeight($style['height']);
1288 2
                                                    if (isset($style['margin-left'])) {
1289 2
                                                        $hfImages[$shapeId]->setOffsetX($style['margin-left']);
1290
                                                    }
1291 2
                                                    $hfImages[$shapeId]->setOffsetY($style['margin-top']);
1292 2
                                                    $hfImages[$shapeId]->setResizeProportional(true);
1293
                                                }
1294
                                            }
1295
1296 2
                                            $docSheet->getHeaderFooter()->setImages($hfImages);
1297
                                        }
1298
                                    }
1299
                                }
1300
                            }
1301
1302
                            // TODO: Autoshapes from twoCellAnchors!
1303 509
                            $drawingFilename = dirname("$dir/$fileWorksheet")
1304 509
                                . '/_rels/'
1305 509
                                . basename($fileWorksheet)
1306 509
                                . '.rels';
1307 509
                            if (substr($drawingFilename, 0, 7) === 'xl//xl/') {
1308 4
                                $drawingFilename = substr($drawingFilename, 4);
1309
                            }
1310 509
                            if (substr($drawingFilename, 0, 8) === '/xl//xl/') {
1311 5
                                $drawingFilename = substr($drawingFilename, 5);
1312
                            }
1313 509
                            if ($zip->locateName($drawingFilename)) {
1314 424
                                $relsWorksheet = $this->loadZipNoNamespace($drawingFilename, Namespaces::RELATIONSHIPS);
1315 424
                                $drawings = [];
1316 424
                                foreach ($relsWorksheet->Relationship as $ele) {
1317 325
                                    if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
1318 85
                                        $eleTarget = (string) $ele['Target'];
1319 85
                                        if (substr($eleTarget, 0, 4) === '/xl/') {
1320 3
                                            $drawings[(string) $ele['Id']] = substr($eleTarget, 1);
1321
                                        } else {
1322 83
                                            $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1323
                                        }
1324
                                    }
1325
                                }
1326
1327 424
                                if ($xmlSheetNS->drawing && !$this->readDataOnly) {
1328 85
                                    $unparsedDrawings = [];
1329 85
                                    $fileDrawing = null;
1330 85
                                    foreach ($xmlSheetNS->drawing as $drawing) {
1331 85
                                        $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id');
1332 85
                                        $fileDrawing = $drawings[$drawingRelId];
1333 85
                                        $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels';
1334 85
                                        $relsDrawing = $this->loadZipNoNamespace($drawingFilename, $xmlNamespaceBase);
1335
1336 85
                                        $images = [];
1337 85
                                        $hyperlinks = [];
1338 85
                                        if ($relsDrawing && $relsDrawing->Relationship) {
1339 80
                                            foreach ($relsDrawing->Relationship as $ele) {
1340 80
                                                $eleType = (string) $ele['Type'];
1341 80
                                                if ($eleType === Namespaces::HYPERLINK) {
1342 2
                                                    $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1343
                                                }
1344 80
                                                if ($eleType === "$xmlNamespaceBase/image") {
1345 41
                                                    $eleTarget = (string) $ele['Target'];
1346 41
                                                    if (substr($eleTarget, 0, 4) === '/xl/') {
1347 1
                                                        $eleTarget = substr($eleTarget, 1);
1348 1
                                                        $images[(string) $ele['Id']] = $eleTarget;
1349
                                                    } else {
1350 41
                                                        $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $eleTarget);
1351
                                                    }
1352 56
                                                } elseif ($eleType === "$xmlNamespaceBase/chart") {
1353 54
                                                    if ($this->includeCharts) {
1354 54
                                                        $eleTarget = (string) $ele['Target'];
1355 54
                                                        if (substr($eleTarget, 0, 4) === '/xl/') {
1356 2
                                                            $index = substr($eleTarget, 1);
1357
                                                        } else {
1358 53
                                                            $index = self::dirAdd($fileDrawing, $eleTarget);
1359
                                                        }
1360 54
                                                        $charts[$index] = [
1361 54
                                                            'id' => (string) $ele['Id'],
1362 54
                                                            'sheet' => $docSheet->getTitle(),
1363 54
                                                        ];
1364
                                                    }
1365
                                                }
1366
                                            }
1367
                                        }
1368
1369 85
                                        $xmlDrawing = $this->loadZipNoNamespace($fileDrawing, '');
1370 85
                                        $xmlDrawingChildren = $xmlDrawing->children(Namespaces::SPREADSHEET_DRAWING);
1371
1372 85
                                        if ($xmlDrawingChildren->oneCellAnchor) {
1373 15
                                            foreach ($xmlDrawingChildren->oneCellAnchor as $oneCellAnchor) {
1374 15
                                                $oneCellAnchor = self::testSimpleXml($oneCellAnchor);
1375 15
                                                if ($oneCellAnchor->pic->blipFill) {
1376
                                                    /** @var SimpleXMLElement $blip */
1377 11
                                                    $blip = $oneCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip;
1378
                                                    /** @var SimpleXMLElement $xfrm */
1379 11
                                                    $xfrm = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm;
1380
                                                    /** @var SimpleXMLElement $outerShdw */
1381 11
                                                    $outerShdw = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw;
1382
1383 11
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1384 11
                                                    $objDrawing->setName((string) self::getArrayItem(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'name'));
1385 11
                                                    $objDrawing->setDescription((string) self::getArrayItem(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'descr'));
1386 11
                                                    $embedImageKey = (string) self::getArrayItem(
1387 11
                                                        self::getAttributes($blip, $xmlNamespaceBase),
1388 11
                                                        'embed'
1389 11
                                                    );
1390 11
                                                    if (isset($images[$embedImageKey])) {
1391 11
                                                        $objDrawing->setPath(
1392 11
                                                            'zip://' . File::realpath($filename) . '#' .
1393 11
                                                            $images[$embedImageKey],
1394 11
                                                            false
1395 11
                                                        );
1396
                                                    } else {
1397
                                                        $linkImageKey = (string) self::getArrayItem(
1398
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1399
                                                            'link'
1400
                                                        );
1401
                                                        if (isset($images[$linkImageKey])) {
1402
                                                            $url = str_replace('xl/drawings/', '', $images[$linkImageKey]);
1403
                                                            $objDrawing->setPath($url);
1404
                                                        }
1405
                                                    }
1406 11
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
1407
1408 11
                                                    $objDrawing->setOffsetX((int) Drawing::EMUToPixels($oneCellAnchor->from->colOff));
1409 11
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
1410 11
                                                    $objDrawing->setResizeProportional(false);
1411 11
                                                    $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cx')));
1412 11
                                                    $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cy')));
1413 11
                                                    if ($xfrm) {
1414 11
                                                        $objDrawing->setRotation((int) Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot')));
1415
                                                    }
1416 11
                                                    if ($outerShdw) {
1417 2
                                                        $shadow = $objDrawing->getShadow();
1418 2
                                                        $shadow->setVisible(true);
1419 2
                                                        $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'blurRad')));
1420 2
                                                        $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'dist')));
1421 2
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($outerShdw), 'dir')));
1422 2
                                                        $shadow->setAlignment((string) self::getArrayItem(self::getAttributes($outerShdw), 'algn'));
1423 2
                                                        $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr;
1424 2
                                                        $shadow->getColor()->setRGB(self::getArrayItem(self::getAttributes($clr), 'val'));
1425 2
                                                        $shadow->setAlpha(self::getArrayItem(self::getAttributes($clr->alpha), 'val') / 1000);
1426
                                                    }
1427
1428 11
                                                    $this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks);
1429
1430 11
                                                    $objDrawing->setWorksheet($docSheet);
1431 4
                                                } elseif ($this->includeCharts && $oneCellAnchor->graphicFrame) {
1432
                                                    // Exported XLSX from Google Sheets positions charts with a oneCellAnchor
1433 3
                                                    $coordinates = Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1);
1434 3
                                                    $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff);
1435 3
                                                    $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
1436 3
                                                    $width = Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cx'));
1437 3
                                                    $height = Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cy'));
1438
1439 3
                                                    $graphic = $oneCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic;
1440
                                                    /** @var SimpleXMLElement $chartRef */
1441 3
                                                    $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart;
1442 3
                                                    $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase);
1443
1444 3
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1445 3
                                                        'fromCoordinate' => $coordinates,
1446 3
                                                        'fromOffsetX' => $offsetX,
1447 3
                                                        'fromOffsetY' => $offsetY,
1448 3
                                                        'width' => $width,
1449 3
                                                        'height' => $height,
1450 3
                                                        'worksheetTitle' => $docSheet->getTitle(),
1451 3
                                                        'oneCellAnchor' => true,
1452 3
                                                    ];
1453
                                                }
1454
                                            }
1455
                                        }
1456 85
                                        if ($xmlDrawingChildren->twoCellAnchor) {
1457 66
                                            foreach ($xmlDrawingChildren->twoCellAnchor as $twoCellAnchor) {
1458 66
                                                $twoCellAnchor = self::testSimpleXml($twoCellAnchor);
1459 66
                                                if ($twoCellAnchor->pic->blipFill) {
1460 30
                                                    $blip = $twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip;
1461 30
                                                    $xfrm = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm;
1462 30
                                                    $outerShdw = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw;
1463 30
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1464
                                                    /** @scrutinizer ignore-call */
1465 30
                                                    $editAs = $twoCellAnchor->attributes();
1466 30
                                                    if (isset($editAs, $editAs['editAs'])) {
1467 27
                                                        $objDrawing->setEditAs($editAs['editAs']);
1468
                                                    }
1469 30
                                                    $objDrawing->setName((string) self::getArrayItem(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'name'));
1470 30
                                                    $objDrawing->setDescription((string) self::getArrayItem(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'descr'));
1471 30
                                                    $embedImageKey = (string) self::getArrayItem(
1472 30
                                                        self::getAttributes($blip, $xmlNamespaceBase),
1473 30
                                                        'embed'
1474 30
                                                    );
1475 30
                                                    if (isset($images[$embedImageKey])) {
1476 29
                                                        $objDrawing->setPath(
1477 29
                                                            'zip://' . File::realpath($filename) . '#' .
1478 29
                                                            $images[$embedImageKey],
1479 29
                                                            false
1480 29
                                                        );
1481
                                                    } else {
1482 1
                                                        $linkImageKey = (string) self::getArrayItem(
1483 1
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1484 1
                                                            'link'
1485 1
                                                        );
1486 1
                                                        if (isset($images[$linkImageKey])) {
1487 1
                                                            $url = str_replace('xl/drawings/', '', $images[$linkImageKey]);
1488 1
                                                            $objDrawing->setPath($url);
1489
                                                        }
1490
                                                    }
1491 30
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1));
1492
1493 30
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff));
1494 30
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
1495
1496 30
                                                    $objDrawing->setCoordinates2(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1));
1497
1498 30
                                                    $objDrawing->setOffsetX2(Drawing::EMUToPixels($twoCellAnchor->to->colOff));
1499 30
                                                    $objDrawing->setOffsetY2(Drawing::EMUToPixels($twoCellAnchor->to->rowOff));
1500
1501 30
                                                    $objDrawing->setResizeProportional(false);
1502
1503 30
                                                    if ($xfrm) {
1504 30
                                                        $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($xfrm->ext), 'cx')));
1505 30
                                                        $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($xfrm->ext), 'cy')));
1506 30
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot')));
1507
                                                    }
1508 30
                                                    if ($outerShdw) {
1509
                                                        $shadow = $objDrawing->getShadow();
1510
                                                        $shadow->setVisible(true);
1511
                                                        $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'blurRad')));
1512
                                                        $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'dist')));
1513
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($outerShdw), 'dir')));
1514
                                                        $shadow->setAlignment((string) self::getArrayItem(self::getAttributes($outerShdw), 'algn'));
1515
                                                        $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr;
1516
                                                        $shadow->getColor()->setRGB(self::getArrayItem(self::getAttributes($clr), 'val'));
1517
                                                        $shadow->setAlpha(self::getArrayItem(self::getAttributes($clr->alpha), 'val') / 1000);
1518
                                                    }
1519
1520 30
                                                    $this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks);
1521
1522 30
                                                    $objDrawing->setWorksheet($docSheet);
1523 51
                                                } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
1524 51
                                                    $fromCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
1525 51
                                                    $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff);
1526 51
                                                    $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
1527 51
                                                    $toCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
1528 51
                                                    $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff);
1529 51
                                                    $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
1530 51
                                                    $graphic = $twoCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic;
1531
                                                    /** @var SimpleXMLElement $chartRef */
1532 51
                                                    $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart;
1533 51
                                                    $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase);
1534
1535 51
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1536 51
                                                        'fromCoordinate' => $fromCoordinate,
1537 51
                                                        'fromOffsetX' => $fromOffsetX,
1538 51
                                                        'fromOffsetY' => $fromOffsetY,
1539 51
                                                        'toCoordinate' => $toCoordinate,
1540 51
                                                        'toOffsetX' => $toOffsetX,
1541 51
                                                        'toOffsetY' => $toOffsetY,
1542 51
                                                        'worksheetTitle' => $docSheet->getTitle(),
1543 51
                                                    ];
1544
                                                }
1545
                                            }
1546
                                        }
1547 85
                                        if ($xmlDrawingChildren->absoluteAnchor) {
1548 1
                                            foreach ($xmlDrawingChildren->absoluteAnchor as $absoluteAnchor) {
1549 1
                                                if (($this->includeCharts) && ($absoluteAnchor->graphicFrame)) {
1550 1
                                                    $graphic = $absoluteAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic;
1551
                                                    /** @var SimpleXMLElement $chartRef */
1552 1
                                                    $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart;
1553 1
                                                    $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase);
1554 1
                                                    $width = Drawing::EMUToPixels((int) self::getArrayItem(self::getAttributes($absoluteAnchor->ext), 'cx')[0]);
1555 1
                                                    $height = Drawing::EMUToPixels((int) self::getArrayItem(self::getAttributes($absoluteAnchor->ext), 'cy')[0]);
1556
1557 1
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1558 1
                                                        'fromCoordinate' => 'A1',
1559 1
                                                        'fromOffsetX' => 0,
1560 1
                                                        'fromOffsetY' => 0,
1561 1
                                                        'width' => $width,
1562 1
                                                        'height' => $height,
1563 1
                                                        'worksheetTitle' => $docSheet->getTitle(),
1564 1
                                                    ];
1565
                                                }
1566
                                            }
1567
                                        }
1568 85
                                        if (empty($relsDrawing) && $xmlDrawing->count() == 0) {
1569
                                            // Save Drawing without rels and children as unparsed
1570 9
                                            $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML();
1571
                                        }
1572
                                    }
1573
1574
                                    // store original rId of drawing files
1575 85
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = [];
1576 85
                                    foreach ($relsWorksheet->Relationship as $ele) {
1577 85
                                        if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
1578 85
                                            $drawingRelId = (string) $ele['Id'];
1579 85
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = $drawingRelId;
1580 85
                                            if (isset($unparsedDrawings[$drawingRelId])) {
1581 9
                                                $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['Drawings'][$drawingRelId] = $unparsedDrawings[$drawingRelId];
1582
                                            }
1583
                                        }
1584
                                    }
1585 85
                                    if ($xmlSheet->legacyDrawing && !$this->readDataOnly) {
1586 6
                                        foreach ($xmlSheet->legacyDrawing as $drawing) {
1587 6
                                            $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id');
1588 6
                                            if (isset($vmlDrawingContents[$drawingRelId])) {
1589 6
                                                $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['legacyDrawing'] = $vmlDrawingContents[$drawingRelId];
1590
                                            }
1591
                                        }
1592
                                    }
1593
1594
                                    // unparsed drawing AlternateContent
1595 85
                                    $xmlAltDrawing = $this->loadZip((string) $fileDrawing, Namespaces::COMPATIBILITY);
1596
1597 85
                                    if ($xmlAltDrawing->AlternateContent) {
1598 3
                                        foreach ($xmlAltDrawing->AlternateContent as $alternateContent) {
1599 3
                                            $alternateContent = self::testSimpleXml($alternateContent);
1600 3
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML();
1601
                                        }
1602
                                    }
1603
                                }
1604
                            }
1605
1606 509
                            $this->readFormControlProperties($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1607 509
                            $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1608
1609
                            // Loop through definedNames
1610 509
                            if ($xmlWorkbook->definedNames) {
1611 250
                                foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1612
                                    // Extract range
1613 92
                                    $extractedRange = (string) $definedName;
1614 92
                                    if (($spos = strpos($extractedRange, '!')) !== false) {
1615 75
                                        $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1616
                                    } else {
1617 31
                                        $extractedRange = str_replace('$', '', $extractedRange);
1618
                                    }
1619
1620
                                    // Valid range?
1621 92
                                    if ($extractedRange == '') {
1622
                                        continue;
1623
                                    }
1624
1625
                                    // Some definedNames are only applicable if we are on the same sheet...
1626 92
                                    if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) {
1627
                                        // Switch on type
1628 41
                                        switch ((string) $definedName['name']) {
1629 41
                                            case '_xlnm._FilterDatabase':
1630 16
                                                if ((string) $definedName['hidden'] !== '1') {
1631
                                                    $extractedRange = explode(',', $extractedRange);
1632
                                                    foreach ($extractedRange as $range) {
1633
                                                        $autoFilterRange = $range;
1634
                                                        if (strpos($autoFilterRange, ':') !== false) {
1635
                                                            $docSheet->getAutoFilter()->setRange($autoFilterRange);
1636
                                                        }
1637
                                                    }
1638
                                                }
1639
1640 16
                                                break;
1641 25
                                            case '_xlnm.Print_Titles':
1642
                                                // Split $extractedRange
1643 2
                                                $extractedRange = explode(',', $extractedRange);
1644
1645
                                                // Set print titles
1646 2
                                                foreach ($extractedRange as $range) {
1647 2
                                                    $matches = [];
1648 2
                                                    $range = str_replace('$', '', $range);
1649
1650
                                                    // check for repeating columns, e g. 'A:A' or 'A:D'
1651 2
                                                    if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
1652
                                                        $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]);
1653 2
                                                    } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
1654
                                                        // check for repeating rows, e.g. '1:1' or '1:5'
1655 2
                                                        $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]);
1656
                                                    }
1657
                                                }
1658
1659 2
                                                break;
1660 24
                                            case '_xlnm.Print_Area':
1661 7
                                                $rangeSets = preg_split("/('?(?:.*?)'?(?:![A-Z0-9]+:[A-Z0-9]+)),?/", $extractedRange, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) ?: [];
1662 7
                                                $newRangeSets = [];
1663 7
                                                foreach ($rangeSets as $rangeSet) {
1664 7
                                                    [, $rangeSet] = Worksheet::extractSheetTitle($rangeSet, true);
1665 7
                                                    if (empty($rangeSet)) {
1666
                                                        continue;
1667
                                                    }
1668 7
                                                    if (strpos($rangeSet, ':') === false) {
1669
                                                        $rangeSet = $rangeSet . ':' . $rangeSet;
1670
                                                    }
1671 7
                                                    $newRangeSets[] = str_replace('$', '', $rangeSet);
1672
                                                }
1673 7
                                                if (count($newRangeSets) > 0) {
1674 7
                                                    $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
1675
                                                }
1676
1677 7
                                                break;
1678
                                            default:
1679 18
                                                break;
1680
                                        }
1681
                                    }
1682
                                }
1683
                            }
1684
1685
                            // Next sheet id
1686 509
                            ++$sheetId;
1687
                        }
1688
1689
                        // Loop through definedNames
1690 509
                        if ($xmlWorkbook->definedNames) {
1691 250
                            foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1692
                                // Extract range
1693 92
                                $extractedRange = (string) $definedName;
1694
1695
                                // Valid range?
1696 92
                                if ($extractedRange == '') {
1697
                                    continue;
1698
                                }
1699
1700
                                // Some definedNames are only applicable if we are on the same sheet...
1701 92
                                if ((string) $definedName['localSheetId'] != '') {
1702
                                    // Local defined name
1703
                                    // Switch on type
1704 41
                                    switch ((string) $definedName['name']) {
1705 41
                                        case '_xlnm._FilterDatabase':
1706 25
                                        case '_xlnm.Print_Titles':
1707 24
                                        case '_xlnm.Print_Area':
1708 24
                                            break;
1709
                                        default:
1710 18
                                            if ($mapSheetId[(int) $definedName['localSheetId']] !== null) {
1711 18
                                                $range = Worksheet::extractSheetTitle((string) $definedName, true);
1712 18
                                                $scope = $excel->getSheet($mapSheetId[(int) $definedName['localSheetId']]);
1713 18
                                                if (strpos((string) $definedName, '!') !== false) {
1714 18
                                                    $range[0] = str_replace("''", "'", $range[0]);
1715 18
                                                    $range[0] = str_replace("'", '', $range[0]);
1716 18
                                                    if ($worksheet = $excel->getSheetByName($range[0])) { // @phpstan-ignore-line
1717 18
                                                        $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $worksheet, $extractedRange, true, $scope));
1718
                                                    } else {
1719 18
                                                        $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true, $scope));
1720
                                                    }
1721
                                                } else {
1722
                                                    $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true));
1723
                                                }
1724
                                            }
1725
1726 41
                                            break;
1727
                                    }
1728 68
                                } elseif (!isset($definedName['localSheetId'])) {
1729 68
                                    $definedRange = (string) $definedName;
1730
                                    // "Global" definedNames
1731 68
                                    $locatedSheet = null;
1732 68
                                    if (strpos((string) $definedName, '!') !== false) {
1733
                                        // Modify range, and extract the first worksheet reference
1734
                                        // Need to split on a comma or a space if not in quotes, and extract the first part.
1735 50
                                        $definedNameValueParts = preg_split("/[ ,](?=([^']*'[^']*')*[^']*$)/miuU", $definedRange);
1736
                                        // Extract sheet name
1737 50
                                        [$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true); // @phpstan-ignore-line
1738 50
                                        $extractedSheetName = trim($extractedSheetName, "'");
1739
1740
                                        // Locate sheet
1741 50
                                        $locatedSheet = $excel->getSheetByName($extractedSheetName);
1742
                                    }
1743
1744 68
                                    if ($locatedSheet === null && !DefinedName::testIfFormula($definedRange)) {
1745 1
                                        $definedRange = '#REF!';
1746
                                    }
1747 68
                                    $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $locatedSheet, $definedRange, false));
1748
                                }
1749
                            }
1750
                        }
1751
                    }
1752
1753 509
                    (new WorkbookView($excel))->viewSettings($xmlWorkbook, $mainNS, $mapSheetId, $this->readDataOnly);
1754
1755 509
                    break;
1756
            }
1757
        }
1758
1759 509
        if (!$this->readDataOnly) {
1760 509
            $contentTypes = $this->loadZip('[Content_Types].xml');
1761
1762
            // Default content types
1763 509
            foreach ($contentTypes->Default as $contentType) {
1764 508
                switch ($contentType['ContentType']) {
1765 508
                    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings':
1766 267
                        $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType'];
1767
1768 267
                        break;
1769
                }
1770
            }
1771
1772
            // Override content types
1773 509
            foreach ($contentTypes->Override as $contentType) {
1774 509
                switch ($contentType['ContentType']) {
1775 509
                    case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
1776 55
                        if ($this->includeCharts) {
1777 54
                            $chartEntryRef = ltrim((string) $contentType['PartName'], '/');
1778 54
                            $chartElements = $this->loadZip($chartEntryRef);
1779 54
                            $chartReader = new Chart($chartNS, $drawingNS);
1780 54
                            $objChart = $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml'));
1781 54
                            if (isset($charts[$chartEntryRef])) {
1782 54
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
1783 54
                                if (isset($chartDetails[$chartPositionRef])) {
1784 54
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); // @phpstan-ignore-line
1785 54
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
1786
                                    // For oneCellAnchor or absoluteAnchor positioned charts,
1787
                                    //     toCoordinate is not in the data. Does it need to be calculated?
1788 54
                                    if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) {
1789
                                        // twoCellAnchor
1790 51
                                        $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
1791 51
                                        $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
1792
                                    } else {
1793
                                        // oneCellAnchor or absoluteAnchor (e.g. Chart sheet)
1794 4
                                        $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
1795 4
                                        $objChart->setBottomRightPosition('', $chartDetails[$chartPositionRef]['width'], $chartDetails[$chartPositionRef]['height']);
1796 4
                                        if (array_key_exists('oneCellAnchor', $chartDetails[$chartPositionRef])) {
1797 3
                                            $objChart->setOneCellAnchor($chartDetails[$chartPositionRef]['oneCellAnchor']);
1798
                                        }
1799
                                    }
1800
                                }
1801
                            }
1802
                        }
1803
1804 55
                        break;
1805
1806
                        // unparsed
1807 509
                    case 'application/vnd.ms-excel.controlproperties+xml':
1808 3
                        $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
1809
1810 3
                        break;
1811
                }
1812
            }
1813
        }
1814
1815 509
        $excel->setUnparsedLoadedData($unparsedLoadedData);
1816
1817 509
        $zip->close();
1818
1819 509
        return $excel;
1820
    }
1821
1822
    /**
1823
     * @return RichText
1824
     */
1825 54
    private function parseRichText(?SimpleXMLElement $is)
1826
    {
1827 54
        $value = new RichText();
1828
1829 54
        if (isset($is->t)) {
1830 16
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
1831 38
        } elseif ($is !== null) {
1832 38
            if (is_object($is->r)) {
1833
                /** @var SimpleXMLElement $run */
1834 38
                foreach ($is->r as $run) {
1835 35
                    if (!isset($run->rPr)) {
1836 26
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
1837
                    } else {
1838 34
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
1839 34
                        $objFont = $objText->getFont() ?? new StyleFont();
1840
1841 34
                        if (isset($run->rPr->rFont)) {
1842 34
                            $attr = $run->rPr->rFont->attributes();
1843 34
                            if (isset($attr['val'])) {
1844 34
                                $objFont->setName((string) $attr['val']);
1845
                            }
1846
                        }
1847 34
                        if (isset($run->rPr->sz)) {
1848 34
                            $attr = $run->rPr->sz->attributes();
1849 34
                            if (isset($attr['val'])) {
1850 34
                                $objFont->setSize((float) $attr['val']);
1851
                            }
1852
                        }
1853 34
                        if (isset($run->rPr->color)) {
1854 32
                            $objFont->setColor(new Color($this->styleReader->readColor($run->rPr->color)));
1855
                        }
1856 34
                        if (isset($run->rPr->b)) {
1857 30
                            $attr = $run->rPr->b->attributes();
1858
                            if (
1859 30
                                (isset($attr['val']) && self::boolean((string) $attr['val'])) ||
1860 30
                                (!isset($attr['val']))
1861
                            ) {
1862 29
                                $objFont->setBold(true);
1863
                            }
1864
                        }
1865 34
                        if (isset($run->rPr->i)) {
1866 6
                            $attr = $run->rPr->i->attributes();
1867
                            if (
1868 6
                                (isset($attr['val']) && self::boolean((string) $attr['val'])) ||
1869 6
                                (!isset($attr['val']))
1870
                            ) {
1871 4
                                $objFont->setItalic(true);
1872
                            }
1873
                        }
1874 34
                        if (isset($run->rPr->vertAlign)) {
1875
                            $attr = $run->rPr->vertAlign->attributes();
1876
                            if (isset($attr['val'])) {
1877
                                $vertAlign = strtolower((string) $attr['val']);
1878
                                if ($vertAlign == 'superscript') {
1879
                                    $objFont->setSuperscript(true);
1880
                                }
1881
                                if ($vertAlign == 'subscript') {
1882
                                    $objFont->setSubscript(true);
1883
                                }
1884
                            }
1885
                        }
1886 34
                        if (isset($run->rPr->u)) {
1887 6
                            $attr = $run->rPr->u->attributes();
1888 6
                            if (!isset($attr['val'])) {
1889 1
                                $objFont->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
1890
                            } else {
1891 5
                                $objFont->setUnderline((string) $attr['val']);
1892
                            }
1893
                        }
1894 34
                        if (isset($run->rPr->strike)) {
1895 5
                            $attr = $run->rPr->strike->attributes();
1896
                            if (
1897 5
                                (isset($attr['val']) && self::boolean((string) $attr['val'])) ||
1898 5
                                (!isset($attr['val']))
1899
                            ) {
1900
                                $objFont->setStrikethrough(true);
1901
                            }
1902
                        }
1903
                    }
1904
                }
1905
            }
1906
        }
1907
1908 54
        return $value;
1909
    }
1910
1911 2
    private function readRibbon(Spreadsheet $excel, string $customUITarget, ZipArchive $zip): void
1912
    {
1913 2
        $baseDir = dirname($customUITarget);
1914 2
        $nameCustomUI = basename($customUITarget);
1915
        // get the xml file (ribbon)
1916 2
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
1917 2
        $customUIImagesNames = [];
1918 2
        $customUIImagesBinaries = [];
1919
        // something like customUI/_rels/customUI.xml.rels
1920 2
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
1921 2
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
1922 2
        if ($dataRels) {
1923
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
1924
            $UIRels = simplexml_load_string(
1925
                $this->getSecurityScannerOrThrow()->scan($dataRels),
1926
                'SimpleXMLElement',
1927
                Settings::getLibXmlLoaderOptions()
1928
            );
1929
            if (false !== $UIRels) {
1930
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
1931
                foreach ($UIRels->Relationship as $ele) {
1932
                    if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/image') {
1933
                        // an image ?
1934
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
1935
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
1936
                    }
1937
                }
1938
            }
1939
        }
1940 2
        if ($localRibbon) {
1941 2
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
1942 2
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
1943
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
1944
            } else {
1945 2
                $excel->setRibbonBinObjects(null, null);
1946
            }
1947
        } else {
1948
            $excel->setRibbonXMLData(null, null);
1949
            $excel->setRibbonBinObjects(null, null);
1950
        }
1951
    }
1952
1953
    /**
1954
     * @param null|array|bool|SimpleXMLElement $array
1955
     * @param int|string $key
1956
     *
1957
     * @return mixed
1958
     */
1959 522
    private static function getArrayItem($array, $key = 0)
1960
    {
1961 522
        return ($array === null || is_bool($array)) ? null : ($array[$key] ?? null);
1962
    }
1963
1964
    /**
1965
     * @param null|SimpleXMLElement|string $base
1966
     * @param null|SimpleXMLElement|string $add
1967
     */
1968 313
    private static function dirAdd($base, $add): string
1969
    {
1970 313
        $base = (string) $base;
1971 313
        $add = (string) $add;
1972
1973 313
        return (string) preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
1974
    }
1975
1976 2
    private static function toCSSArray(string $style): array
1977
    {
1978 2
        $style = self::stripWhiteSpaceFromStyleString($style);
1979
1980 2
        $temp = explode(';', $style);
1981 2
        $style = [];
1982 2
        foreach ($temp as $item) {
1983 2
            $item = explode(':', $item);
1984
1985 2
            if (strpos($item[1], 'px') !== false) {
1986 1
                $item[1] = str_replace('px', '', $item[1]);
1987
            }
1988 2
            if (strpos($item[1], 'pt') !== false) {
1989 2
                $item[1] = str_replace('pt', '', $item[1]);
1990 2
                $item[1] = (string) Font::fontSizeToPixels((int) $item[1]);
1991
            }
1992 2
            if (strpos($item[1], 'in') !== false) {
1993
                $item[1] = str_replace('in', '', $item[1]);
1994
                $item[1] = (string) Font::inchSizeToPixels((int) $item[1]);
1995
            }
1996 2
            if (strpos($item[1], 'cm') !== false) {
1997
                $item[1] = str_replace('cm', '', $item[1]);
1998
                $item[1] = (string) Font::centimeterSizeToPixels((int) $item[1]);
1999
            }
2000
2001 2
            $style[$item[0]] = $item[1];
2002
        }
2003
2004 2
        return $style;
2005
    }
2006
2007 5
    public static function stripWhiteSpaceFromStyleString(string $string): string
2008
    {
2009 5
        return trim(str_replace(["\r", "\n", ' '], '', $string), ';');
2010
    }
2011
2012 72
    private static function boolean(string $value): bool
2013
    {
2014 72
        if (is_numeric($value)) {
2015 60
            return (bool) $value;
2016
        }
2017
2018 23
        return $value === 'true' || $value === 'TRUE';
2019
    }
2020
2021
    /**
2022
     * @param array $hyperlinks
2023
     */
2024 41
    private function readHyperLinkDrawing(\PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing, SimpleXMLElement $cellAnchor, $hyperlinks): void
2025
    {
2026 41
        $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick;
2027
2028 41
        if ($hlinkClick->count() === 0) {
2029 39
            return;
2030
        }
2031
2032 2
        $hlinkId = (string) self::getAttributes($hlinkClick, Namespaces::SCHEMA_OFFICE_DOCUMENT)['id'];
2033 2
        $hyperlink = new Hyperlink(
2034 2
            $hyperlinks[$hlinkId],
2035 2
            (string) self::getArrayItem(self::getAttributes($cellAnchor->pic->nvPicPr->cNvPr), 'name')
2036 2
        );
2037 2
        $objDrawing->setHyperlink($hyperlink);
2038
    }
2039
2040 509
    private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook): void
2041
    {
2042 509
        if (!$xmlWorkbook->workbookProtection) {
2043 493
            return;
2044
        }
2045
2046 20
        $excel->getSecurity()->setLockRevision(self::getLockValue($xmlWorkbook->workbookProtection, 'lockRevision'));
2047 20
        $excel->getSecurity()->setLockStructure(self::getLockValue($xmlWorkbook->workbookProtection, 'lockStructure'));
2048 20
        $excel->getSecurity()->setLockWindows(self::getLockValue($xmlWorkbook->workbookProtection, 'lockWindows'));
2049
2050 20
        if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
2051 1
            $excel->getSecurity()->setRevisionsPassword(
2052 1
                (string) $xmlWorkbook->workbookProtection['revisionsPassword'],
2053 1
                true
2054 1
            );
2055
        }
2056
2057 20
        if ($xmlWorkbook->workbookProtection['workbookPassword']) {
2058 2
            $excel->getSecurity()->setWorkbookPassword(
2059 2
                (string) $xmlWorkbook->workbookProtection['workbookPassword'],
2060 2
                true
2061 2
            );
2062
        }
2063
    }
2064
2065 20
    private static function getLockValue(SimpleXmlElement $protection, string $key): ?bool
2066
    {
2067 20
        $returnValue = null;
2068 20
        $protectKey = $protection[$key];
2069 20
        if (!empty($protectKey)) {
2070 9
            $protectKey = (string) $protectKey;
2071 9
            $returnValue = $protectKey !== 'false' && (bool) $protectKey;
2072
        }
2073
2074 20
        return $returnValue;
2075
    }
2076
2077 509
    private function readFormControlProperties(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void
2078
    {
2079 509
        $zip = $this->zip;
2080 509
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2081 292
            return;
2082
        }
2083
2084 422
        $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
2085 422
        $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS);
2086 422
        $ctrlProps = [];
2087 422
        foreach ($relsWorksheet->Relationship as $ele) {
2088 323
            if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/ctrlProp') {
2089 3
                $ctrlProps[(string) $ele['Id']] = $ele;
2090
            }
2091
        }
2092
2093 422
        $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
2094 422
        foreach ($ctrlProps as $rId => $ctrlProp) {
2095 3
            $rId = substr($rId, 3); // rIdXXX
2096 3
            $unparsedCtrlProps[$rId] = [];
2097 3
            $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
2098 3
            $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
2099 3
            $unparsedCtrlProps[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
2100
        }
2101 422
        unset($unparsedCtrlProps);
2102
    }
2103
2104 509
    private function readPrinterSettings(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void
2105
    {
2106 509
        $zip = $this->zip;
2107 509
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2108 292
            return;
2109
        }
2110
2111 422
        $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
2112 422
        $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS);
2113 422
        $sheetPrinterSettings = [];
2114 422
        foreach ($relsWorksheet->Relationship as $ele) {
2115 323
            if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/printerSettings') {
2116 261
                $sheetPrinterSettings[(string) $ele['Id']] = $ele;
2117
            }
2118
        }
2119
2120 422
        $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
2121 422
        foreach ($sheetPrinterSettings as $rId => $printerSettings) {
2122 261
            $rId = substr($rId, 3); // rIdXXX
2123 261
            if (substr($rId, -2) !== 'ps') {
2124 261
                $rId = $rId . 'ps'; // rIdXXX, add 'ps' suffix to avoid identical resource identifier collision with unparsed vmlDrawing
2125
            }
2126 261
            $unparsedPrinterSettings[$rId] = [];
2127 261
            $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']);
2128 261
            $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target'];
2129 261
            $unparsedPrinterSettings[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
2130
        }
2131 422
        unset($unparsedPrinterSettings);
2132
    }
2133
2134 513
    private function getWorkbookBaseName(): array
2135
    {
2136 513
        $workbookBasename = '';
2137 513
        $xmlNamespaceBase = '';
2138
2139
        // check if it is an OOXML archive
2140 513
        $rels = $this->loadZip(self::INITIAL_FILE);
2141 513
        foreach ($rels->children(Namespaces::RELATIONSHIPS)->Relationship as $rel) {
2142 513
            $rel = self::getAttributes($rel);
2143 513
            $type = (string) $rel['Type'];
2144
            switch ($type) {
2145 14
                case Namespaces::OFFICE_DOCUMENT:
2146 14
                case Namespaces::PURL_OFFICE_DOCUMENT:
2147 513
                    $basename = basename((string) $rel['Target']);
2148 513
                    $xmlNamespaceBase = dirname($type);
2149 513
                    if (preg_match('/workbook.*\.xml/', $basename)) {
2150 513
                        $workbookBasename = $basename;
2151
                    }
2152
2153 513
                    break;
2154
            }
2155
        }
2156
2157 513
        return [$workbookBasename, $xmlNamespaceBase];
2158
    }
2159
2160 501
    private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void
2161
    {
2162 501
        if ($this->readDataOnly || !$xmlSheet->sheetProtection) {
2163 447
            return;
2164
        }
2165
2166 62
        $algorithmName = (string) $xmlSheet->sheetProtection['algorithmName'];
2167 62
        $protection = $docSheet->getProtection();
2168 62
        $protection->setAlgorithm($algorithmName);
2169
2170 62
        if ($algorithmName) {
2171 2
            $protection->setPassword((string) $xmlSheet->sheetProtection['hashValue'], true);
2172 2
            $protection->setSalt((string) $xmlSheet->sheetProtection['saltValue']);
2173 2
            $protection->setSpinCount((int) $xmlSheet->sheetProtection['spinCount']);
2174
        } else {
2175 61
            $protection->setPassword((string) $xmlSheet->sheetProtection['password'], true);
2176
        }
2177
2178 62
        if ($xmlSheet->protectedRanges->protectedRange) {
2179 2
            foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
2180 2
                $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
2181
            }
2182
        }
2183
    }
2184
2185 509
    private function readAutoFilter(
2186
        SimpleXMLElement $xmlSheet,
2187
        Worksheet $docSheet
2188
    ): void {
2189 509
        if ($xmlSheet && $xmlSheet->autoFilter) {
2190 14
            (new AutoFilter($docSheet, $xmlSheet))->load();
2191
        }
2192
    }
2193
2194 509
    private function readTables(
2195
        SimpleXMLElement $xmlSheet,
2196
        Worksheet $docSheet,
2197
        string $dir,
2198
        string $fileWorksheet,
2199
        ZipArchive $zip
2200
    ): void {
2201 509
        if ($xmlSheet && $xmlSheet->tableParts && (int) $xmlSheet->tableParts['count'] > 0) {
2202 22
            $this->readTablesInTablesFile($xmlSheet, $dir, $fileWorksheet, $zip, $docSheet);
2203
        }
2204
    }
2205
2206 22
    private function readTablesInTablesFile(
2207
        SimpleXMLElement $xmlSheet,
2208
        string $dir,
2209
        string $fileWorksheet,
2210
        ZipArchive $zip,
2211
        Worksheet $docSheet
2212
    ): void {
2213 22
        foreach ($xmlSheet->tableParts->tablePart as $tablePart) {
2214 22
            $relation = self::getAttributes($tablePart, Namespaces::SCHEMA_OFFICE_DOCUMENT);
2215 22
            $tablePartRel = (string) $relation['id'];
2216 22
            $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
2217
2218 22
            if ($zip->locateName($relationsFileName)) {
2219 22
                $relsTableReferences = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS);
2220 22
                foreach ($relsTableReferences->Relationship as $relationship) {
2221 22
                    $relationshipAttributes = self::getAttributes($relationship, '');
2222
2223 22
                    if ((string) $relationshipAttributes['Id'] === $tablePartRel) {
2224 22
                        $relationshipFileName = (string) $relationshipAttributes['Target'];
2225 22
                        $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName;
2226 22
                        $relationshipFilePath = File::realpath($relationshipFilePath);
2227
2228 22
                        if ($this->fileExistsInArchive($this->zip, $relationshipFilePath)) {
2229 22
                            $tableXml = $this->loadZip($relationshipFilePath);
2230 22
                            (new TableReader($docSheet, $tableXml))->load();
2231
                        }
2232
                    }
2233
                }
2234
            }
2235
        }
2236
    }
2237
2238 509
    private static function extractStyles(?SimpleXMLElement $sxml, string $node1, string $node2): array
2239
    {
2240 509
        $array = [];
2241 509
        if ($sxml && $sxml->{$node1}->{$node2}) {
2242 509
            foreach ($sxml->{$node1}->{$node2} as $node) {
2243 509
                $array[] = $node;
2244
            }
2245
        }
2246
2247 509
        return $array;
2248
    }
2249
2250 509
    private static function extractPalette(?SimpleXMLElement $sxml): array
2251
    {
2252 509
        $array = [];
2253 509
        if ($sxml && $sxml->colors->indexedColors) {
2254 12
            foreach ($sxml->colors->indexedColors->rgbColor as $node) {
2255 12
                if ($node !== null) {
2256 12
                    $attr = $node->attributes();
2257 12
                    if (isset($attr['rgb'])) {
2258 12
                        $array[] = (string) $attr['rgb'];
2259
                    }
2260
                }
2261
            }
2262
        }
2263
2264 509
        return $array;
2265
    }
2266
}
2267