Passed
Pull Request — master (#4142)
by Owen
16:30 queued 03:39
created

Xlsx::readTables()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

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