Passed
Pull Request — master (#4139)
by Owen
14:04
created

Xlsx::extractPalette()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

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