Passed
Pull Request — master (#4170)
by Owen
19:47 queued 09:24
created

Xlsx::testSimpleXml()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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