Failed Conditions
Pull Request — master (#4275)
by Owen
21:43 queued 04:18
created

Xlsx::loadSpreadsheetFromFile()   F

Complexity

Conditions 327
Paths > 20000

Size

Total Lines 1507
Code Lines 973

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 920
CRAP Score 335.9235

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 973
c 2
b 0
f 0
dl 0
loc 1507
rs 0
ccs 920
cts 962
cp 0.9563
cc 327
nc 21131086
nop 1
crap 335.9235

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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