Passed
Push — master ( c28abd...363705 )
by
unknown
18:13 queued 06:33
created

Xlsx::replacePrefixes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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