Passed
Pull Request — master (#4203)
by Owen
14:07
created

Xlsx::replacePrefixes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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