Passed
Pull Request — master (#4377)
by Owen
12:45
created

Xlsx::loadZipNonamespace()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

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