Passed
Pull Request — master (#4377)
by Owen
13:50
created

Xlsx::loadZip()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

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