Passed
Pull Request — master (#4139)
by Owen
11:02
created

Xlsx   F

Complexity

Total Complexity 513

Size/Duplication

Total Lines 2379
Duplicated Lines 0 %

Test Coverage

Coverage 95.07%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 513
eloc 1420
c 1
b 0
f 0
dl 0
loc 2379
ccs 1351
cts 1421
cp 0.9507
rs 0.8

40 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A canRead() 0 17 3
A fileExistsInArchive() 0 18 3
A castToBoolean() 0 10 4
A falseToArray() 0 3 2
A loadZip() 0 14 2
A castToError() 0 3 2
A loadZipNonamespace() 0 11 2
A getAttributes() 0 3 2
A listWorksheetNames() 0 30 5
A testSimpleXml() 0 3 2
C listWorksheetInfo() 0 85 17
A getFromZipArchive() 0 27 5
A xpathNoFalse() 0 3 1
A castToFormula() 0 29 6
A castToString() 0 3 2
A boolean() 0 7 3
D parseRichText() 0 84 29
A dirAdd() 0 6 1
A getWorkbookBaseName() 0 24 5
A readBackgroundImage() 0 16 6
A getLockValue() 0 10 3
A readTablesInTablesFile() 0 26 6
A storeFormulaAttributes() 0 12 4
B processIgnoredErrors() 0 36 11
A readHyperLinkDrawing() 0 14 2
A stripWhiteSpaceFromStyleString() 0 3 1
B onlyNoteVml() 0 30 7
A readFormControlProperties() 0 25 5
A getArrayItem() 0 3 3
A readSheetProtection() 0 21 6
F loadSpreadsheetFromFile() 0 1488 321
A extractPalette() 0 15 6
B readPrinterSettings() 0 29 6
B readRibbon() 0 39 8
A toCSSArray() 0 29 6
A readAutoFilter() 0 6 3
A readProtection() 0 21 4
A extractStyles() 0 10 4
A readTables() 0 12 4

How to fix   Complexity   

Complex Class

Complex classes like Xlsx often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Xlsx, and based on these observations, apply Extract Interface, too.

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 677
    public function __construct()
67
    {
68 677
        parent::__construct();
69 677
        $this->referenceHelper = ReferenceHelper::getInstance();
70 677
        $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 653
    public static function testSimpleXml(mixed $value): SimpleXMLElement
96
    {
97 653
        return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
98
    }
99
100 649
    public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement
101
    {
102 649
        return self::testSimpleXml($value === null ? $value : $value->attributes($ns));
103
    }
104
105
    // Phpstan thinks, correctly, that xpath can return false.
106 620
    private static function xpathNoFalse(SimpleXMLElement $sxml, string $path): array
107
    {
108 620
        return self::falseToArray($sxml->xpath($path));
109
    }
110
111 620
    public static function falseToArray(mixed $value): array
112
    {
113 620
        return is_array($value) ? $value : [];
114
    }
115
116 649
    private function loadZip(string $filename, string $ns = '', bool $replaceUnclosedBr = false): SimpleXMLElement
117
    {
118 649
        $contents = $this->getFromZipArchive($this->zip, $filename);
119 649
        if ($replaceUnclosedBr) {
120 33
            $contents = str_replace('<br>', '<br/>', $contents);
121
        }
122 649
        $rels = @simplexml_load_string(
123 649
            $this->getSecurityScannerOrThrow()->scan($contents),
124 649
            'SimpleXMLElement',
125 649
            Settings::getLibXmlLoaderOptions(),
126 649
            $ns
127 649
        );
128
129 649
        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 620
    private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElement
135
    {
136 620
        $contents = $this->getFromZipArchive($this->zip, $filename);
137 620
        $rels = simplexml_load_string(
138 620
            $this->getSecurityScannerOrThrow()->scan($contents),
139 620
            'SimpleXMLElement',
140 620
            Settings::getLibXmlLoaderOptions(),
141 620
            ($ns === '' ? $ns : '')
142 620
        );
143
144 620
        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 495
    private static function castToString(?SimpleXMLElement $c): ?string
303
    {
304 495
        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 610
    private function fileExistsInArchive(ZipArchive $archive, string $fileName = ''): bool
341
    {
342
        // Root-relative paths
343 610
        if (str_contains($fileName, '//')) {
344 1
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
345
        }
346 610
        $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 610
        $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE);
353 610
        if ($contents === false) {
354 4
            $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE);
355
        }
356
357 610
        return $contents !== false;
358
    }
359
360 649
    private function getFromZipArchive(ZipArchive $archive, string $fileName = ''): string
361
    {
362
        // Root-relative paths
363 649
        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 649
        $fileName = (string) preg_replace('/^\.\//', '', $fileName);
369 649
        $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 649
        $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
375
376
        // Apache POI fixes
377 649
        if ($contents === false) {
378 40
            $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
379
        }
380
381
        // Has the file been saved with Windoze directory separators rather than unix?
382 649
        if ($contents === false) {
383 37
            $contents = $archive->getFromName(str_replace('/', '\\', $fileName), 0, ZipArchive::FL_NOCASE);
384
        }
385
386 649
        return ($contents === false) ? '' : $contents;
387
    }
388
389
    /**
390
     * Loads Spreadsheet from file.
391
     */
392 623
    protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
393
    {
394 623
        File::assertFile($filename, self::INITIAL_FILE);
395
396
        // Initialisations
397 620
        $excel = new Spreadsheet();
398 620
        $excel->removeSheetByIndex(0);
399 620
        $addingFirstCellStyleXf = true;
400 620
        $addingFirstCellXf = true;
401
402 620
        $unparsedLoadedData = [];
403
404 620
        $this->zip = $zip = new ZipArchive();
405 620
        $zip->open($filename);
406
407
        //    Read the theme first, because we need the colour scheme when reading the styles
408 620
        [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName();
409 620
        $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML;
410 620
        $chartNS = self::REL_TO_CHART[$xmlNamespaceBase] ?? Namespaces::CHART;
411 620
        $wbRels = $this->loadZip("xl/_rels/{$workbookBasename}.rels", Namespaces::RELATIONSHIPS);
412 620
        $theme = null;
413 620
        $this->styleReader = new Styles();
414 620
        foreach ($wbRels->Relationship as $relx) {
415 619
            $rel = self::getAttributes($relx);
416 619
            $relTarget = (string) $rel['Target'];
417 619
            if (str_starts_with($relTarget, '/xl/')) {
418 12
                $relTarget = substr($relTarget, 4);
419
            }
420 619
            switch ($rel['Type']) {
421 619
                case "$xmlNamespaceBase/theme":
422 608
                    if (!$this->fileExistsInArchive($zip, "xl/{$relTarget}")) {
423 3
                        break; // issue3770
424
                    }
425 605
                    $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
426 605
                    $themeOrderAdditional = count($themeOrderArray);
427
428 605
                    $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS);
429 605
                    $xmlThemeName = self::getAttributes($xmlTheme);
430 605
                    $xmlTheme = $xmlTheme->children($drawingNS);
431 605
                    $themeName = (string) $xmlThemeName['name'];
432
433 605
                    $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme);
434 605
                    $colourSchemeName = (string) $colourScheme['name'];
435 605
                    $excel->getTheme()->setThemeColorName($colourSchemeName);
436 605
                    $colourScheme = $xmlTheme->themeElements->clrScheme->children($drawingNS);
437
438 605
                    $themeColours = [];
439 605
                    foreach ($colourScheme as $k => $xmlColour) {
440 605
                        $themePos = array_search($k, $themeOrderArray);
441 605
                        if ($themePos === false) {
442 605
                            $themePos = $themeOrderAdditional++;
443
                        }
444 605
                        if (isset($xmlColour->sysClr)) {
445 598
                            $xmlColourData = self::getAttributes($xmlColour->sysClr);
446 598
                            $themeColours[$themePos] = (string) $xmlColourData['lastClr'];
447 598
                            $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['lastClr']);
448 605
                        } elseif (isset($xmlColour->srgbClr)) {
449 605
                            $xmlColourData = self::getAttributes($xmlColour->srgbClr);
450 605
                            $themeColours[$themePos] = (string) $xmlColourData['val'];
451 605
                            $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['val']);
452
                        }
453
                    }
454 605
                    $theme = new Theme($themeName, $colourSchemeName, $themeColours);
455 605
                    $this->styleReader->setTheme($theme);
456
457 605
                    $fontScheme = self::getAttributes($xmlTheme->themeElements->fontScheme);
458 605
                    $fontSchemeName = (string) $fontScheme['name'];
459 605
                    $excel->getTheme()->setThemeFontName($fontSchemeName);
460 605
                    $majorFonts = [];
461 605
                    $minorFonts = [];
462 605
                    $fontScheme = $xmlTheme->themeElements->fontScheme->children($drawingNS);
463 605
                    $majorLatin = self::getAttributes($fontScheme->majorFont->latin)['typeface'] ?? '';
464 605
                    $majorEastAsian = self::getAttributes($fontScheme->majorFont->ea)['typeface'] ?? '';
465 605
                    $majorComplexScript = self::getAttributes($fontScheme->majorFont->cs)['typeface'] ?? '';
466 605
                    $minorLatin = self::getAttributes($fontScheme->minorFont->latin)['typeface'] ?? '';
467 605
                    $minorEastAsian = self::getAttributes($fontScheme->minorFont->ea)['typeface'] ?? '';
468 605
                    $minorComplexScript = self::getAttributes($fontScheme->minorFont->cs)['typeface'] ?? '';
469
470 605
                    foreach ($fontScheme->majorFont->font as $xmlFont) {
471 596
                        $fontAttributes = self::getAttributes($xmlFont);
472 596
                        $script = (string) ($fontAttributes['script'] ?? '');
473 596
                        if (!empty($script)) {
474 596
                            $majorFonts[$script] = (string) ($fontAttributes['typeface'] ?? '');
475
                        }
476
                    }
477 605
                    foreach ($fontScheme->minorFont->font as $xmlFont) {
478 596
                        $fontAttributes = self::getAttributes($xmlFont);
479 596
                        $script = (string) ($fontAttributes['script'] ?? '');
480 596
                        if (!empty($script)) {
481 596
                            $minorFonts[$script] = (string) ($fontAttributes['typeface'] ?? '');
482
                        }
483
                    }
484 605
                    $excel->getTheme()->setMajorFontValues($majorLatin, $majorEastAsian, $majorComplexScript, $majorFonts);
485 605
                    $excel->getTheme()->setMinorFontValues($minorLatin, $minorEastAsian, $minorComplexScript, $minorFonts);
486
487 605
                    break;
488
            }
489
        }
490
491 620
        $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
492
493 620
        $propertyReader = new PropertyReader($this->getSecurityScannerOrThrow(), $excel->getProperties());
494 620
        $charts = $chartDetails = [];
495 620
        foreach ($rels->Relationship as $relx) {
496 620
            $rel = self::getAttributes($relx);
497 620
            $relTarget = (string) $rel['Target'];
498
            // issue 3553
499 620
            if ($relTarget[0] === '/') {
500 7
                $relTarget = substr($relTarget, 1);
501
            }
502 620
            $relType = (string) $rel['Type'];
503 620
            $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
504
            switch ($relType) {
505 613
                case Namespaces::CORE_PROPERTIES:
506 609
                    $propertyReader->readCoreProperties($this->getFromZipArchive($zip, $relTarget));
507
508 609
                    break;
509 620
                case "$xmlNamespaceBase/extended-properties":
510 608
                    $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget));
511
512 608
                    break;
513 620
                case "$xmlNamespaceBase/custom-properties":
514 52
                    $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget));
515
516 52
                    break;
517
                    //Ribbon
518 620
                case Namespaces::EXTENSIBILITY:
519 2
                    $customUI = $relTarget;
520 2
                    if ($customUI) {
521 2
                        $this->readRibbon($excel, $customUI, $zip);
522
                    }
523
524 2
                    break;
525 620
                case "$xmlNamespaceBase/officeDocument":
526 620
                    $dir = dirname($relTarget);
527
528
                    // Do not specify namespace in next stmt - do it in Xpath
529 620
                    $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', Namespaces::RELATIONSHIPS);
530 620
                    $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS);
531
532 620
                    $worksheets = [];
533 620
                    $macros = $customUI = null;
534 620
                    foreach ($relsWorkbook->Relationship as $elex) {
535 620
                        $ele = self::getAttributes($elex);
536 620
                        switch ($ele['Type']) {
537 613
                            case Namespaces::WORKSHEET:
538 613
                            case Namespaces::PURL_WORKSHEET:
539 620
                                $worksheets[(string) $ele['Id']] = $ele['Target'];
540
541 620
                                break;
542 613
                            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 613
                            case Namespaces::VBA:
550 3
                                $macros = $ele['Target'];
551
552 3
                                break;
553
                        }
554
                    }
555
556 620
                    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 620
                    $relType = "rel:Relationship[@Type='"
570 620
                        . "$xmlNamespaceBase/styles"
571 620
                        . "']";
572 620
                    $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType));
573
574 620
                    if ($xpath === null) {
575 1
                        $xmlStyles = self::testSimpleXml(null);
576
                    } else {
577 620
                        $stylesTarget = (string) $xpath['Target'];
578 620
                        $stylesTarget = str_starts_with($stylesTarget, '/') ? substr($stylesTarget, 1) : "$dir/$stylesTarget";
579 620
                        $xmlStyles = $this->loadZip($stylesTarget, $mainNS);
580
                    }
581
582 620
                    $palette = self::extractPalette($xmlStyles);
583 620
                    $this->styleReader->setWorkbookPalette($palette);
584 620
                    $fills = self::extractStyles($xmlStyles, 'fills', 'fill');
585 620
                    $fonts = self::extractStyles($xmlStyles, 'fonts', 'font');
586 620
                    $borders = self::extractStyles($xmlStyles, 'borders', 'border');
587 620
                    $xfTags = self::extractStyles($xmlStyles, 'cellXfs', 'xf');
588 620
                    $cellXfTags = self::extractStyles($xmlStyles, 'cellStyleXfs', 'xf');
589
590 620
                    $styles = [];
591 620
                    $cellStyles = [];
592 620
                    $numFmts = null;
593 620
                    if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) {
594 235
                        $numFmts = $xmlStyles->numFmts[0];
595
                    }
596 620
                    if (isset($numFmts) && ($numFmts !== null)) {
597 235
                        $numFmts->registerXPathNamespace('sml', $mainNS);
598
                    }
599 620
                    $this->styleReader->setNamespace($mainNS);
600 620
                    if (!$this->readDataOnly/* && $xmlStyles*/) {
601 619
                        foreach ($xfTags as $xfTag) {
602 619
                            $xf = self::getAttributes($xfTag);
603 619
                            $numFmt = null;
604
605 619
                            if ($xf['numFmtId']) {
606 617
                                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 617
                                    $numFmt === null
619 617
                                    && (int) $xf['numFmtId'] < 164
620 617
                                    && NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== ''
621
                                ) {
622 611
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
623
                                }
624
                            }
625 619
                            $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? '');
626
627 619
                            $style = (object) [
628 619
                                'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL,
629 619
                                'font' => $fonts[(int) ($xf['fontId'])],
630 619
                                'fill' => $fills[(int) ($xf['fillId'])],
631 619
                                'border' => $borders[(int) ($xf['borderId'])],
632 619
                                'alignment' => $xfTag->alignment,
633 619
                                'protection' => $xfTag->protection,
634 619
                                'quotePrefix' => $quotePrefix,
635 619
                            ];
636 619
                            $styles[] = $style;
637
638
                            // add style to cellXf collection
639 619
                            $objStyle = new Style();
640 619
                            $this->styleReader->readStyle($objStyle, $style);
641 619
                            if ($addingFirstCellXf) {
642 619
                                $excel->removeCellXfByIndex(0); // remove the default style
643 619
                                $addingFirstCellXf = false;
644
                            }
645 619
                            $excel->addCellXf($objStyle);
646
                        }
647
648 619
                        foreach ($cellXfTags as $xfTag) {
649 618
                            $xf = self::getAttributes($xfTag);
650 618
                            $numFmt = NumberFormat::FORMAT_GENERAL;
651 618
                            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 618
                            $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? '');
661
662 618
                            $cellStyle = (object) [
663 618
                                'numFmt' => $numFmt,
664 618
                                'font' => $fonts[(int) ($xf['fontId'])],
665 618
                                'fill' => $fills[((int) $xf['fillId'])],
666 618
                                'border' => $borders[(int) ($xf['borderId'])],
667 618
                                'alignment' => $xfTag->alignment,
668 618
                                'protection' => $xfTag->protection,
669 618
                                'quotePrefix' => $quotePrefix,
670 618
                            ];
671 618
                            $cellStyles[] = $cellStyle;
672
673
                            // add style to cellStyleXf collection
674 618
                            $objStyle = new Style();
675 618
                            $this->styleReader->readStyle($objStyle, $cellStyle);
676 618
                            if ($addingFirstCellStyleXf) {
677 618
                                $excel->removeCellStyleXfByIndex(0); // remove the default style
678 618
                                $addingFirstCellStyleXf = false;
679
                            }
680 618
                            $excel->addCellStyleXf($objStyle);
681
                        }
682
                    }
683 620
                    $this->styleReader->setStyleXml($xmlStyles);
684 620
                    $this->styleReader->setNamespace($mainNS);
685 620
                    $this->styleReader->setStyleBaseData($theme, $styles, $cellStyles);
686 620
                    $dxfs = $this->styleReader->dxfs($this->readDataOnly);
687 620
                    $styles = $this->styleReader->styles();
688
689
                    // Read content after setting the styles
690 620
                    $sharedStrings = [];
691 620
                    $relType = "rel:Relationship[@Type='"
692 620
                        //. Namespaces::SHARED_STRINGS
693 620
                        . "$xmlNamespaceBase/sharedStrings"
694 620
                        . "']";
695 620
                    $xpath = self::getArrayItem($relsWorkbook->xpath($relType));
696
697 620
                    if ($xpath) {
698 578
                        $sharedStringsTarget = (string) $xpath['Target'];
699 578
                        $sharedStringsTarget = str_starts_with($sharedStringsTarget, '/') ? substr($sharedStringsTarget, 1) : "$dir/$sharedStringsTarget";
700 578
                        $xmlStrings = $this->loadZip($sharedStringsTarget, $mainNS);
701 578
                        if (isset($xmlStrings->si)) {
702 470
                            foreach ($xmlStrings->si as $val) {
703 470
                                if (isset($val->t)) {
704 467
                                    $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 620
                    $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS);
715 620
                    $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS);
716
717
                    // Set base date
718 620
                    $excel->setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
719 620
                    if ($xmlWorkbookNS->workbookPr) {
720 611
                        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
721 611
                        $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr);
722 611
                        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 620
                    $this->readProtection($excel, $xmlWorkbook);
732
733 620
                    $sheetId = 0; // keep track of new sheet id in final workbook
734 620
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
735 620
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
736 620
                    $mapSheetId = []; // mapping of sheet ids from old to new
737
738 620
                    $charts = $chartDetails = [];
739
740 620
                    if ($xmlWorkbookNS->sheets) {
741
                        /** @var SimpleXMLElement $eleSheet */
742 620
                        foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) {
743 620
                            $eleSheetAttr = self::getAttributes($eleSheet);
744 620
                            ++$oldSheetId;
745
746
                            // Check if sheet should be skipped
747 620
                            if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) {
748 6
                                ++$countSkippedSheets;
749 6
                                $mapSheetId[$oldSheetId] = null;
750
751 6
                                continue;
752
                            }
753
754 619
                            $sheetReferenceId = (string) self::getArrayItem(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id');
755 619
                            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 619
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
764
765
                            // Load sheet
766 619
                            $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 619
                            $docSheet->setTitle((string) $eleSheetAttr['name'], false, false);
772
773 619
                            $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 619
                            if ($fileWorksheet[0] == '/' && $dir !== '.') {
780 12
                                $fileWorksheet = substr($fileWorksheet, strlen($dir) + 2);
781
                            }
782 619
                            $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS);
783 619
                            $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS);
784
785
                            // Shared Formula table is unique to each Worksheet, so we need to reset it here
786 619
                            $this->sharedFormulae = [];
787
788 619
                            if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') {
789 25
                                $docSheet->setSheetState((string) $eleSheetAttr['state']);
790
                            }
791 619
                            if ($xmlSheetNS) {
792 619
                                $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 619
                                if (!$this->readDataOnly && ($xmlSheet->conditionalFormatting)) {
796 205
                                    (new ConditionalStyles($docSheet, $xmlSheet, $dxfs, $this->styleReader))->load();
797
                                }
798 619
                                if (!$this->readDataOnly && $xmlSheet->extLst) {
799 197
                                    (new ConditionalStyles($docSheet, $xmlSheet, $dxfs, $this->styleReader))->loadFromExt();
800
                                }
801 619
                                if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) {
802 616
                                    $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet);
803 616
                                    $sheetViews->load();
804
                                }
805
806 619
                                $sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheetNS);
807 619
                                $sheetViewOptions->load($this->readDataOnly, $this->styleReader);
808
809 619
                                (new ColumnAndRowAttributes($docSheet, $xmlSheetNS))
810 619
                                    ->load($this->getReadFilter(), $this->readDataOnly, $this->ignoreRowsWithNoCells);
811
                            }
812
813 619
                            $holdSelectedCells = $docSheet->getSelectedCells();
814 619
                            if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) {
815 595
                                $cIndex = 1; // Cell Start from 1
816 595
                                foreach ($xmlSheetNS->sheetData->row as $row) {
817 595
                                    $rowIndex = 1;
818 595
                                    foreach ($row->c as $c) {
819 581
                                        $cAttr = self::getAttributes($c);
820 581
                                        $r = (string) $cAttr['r'];
821 581
                                        if ($r == '') {
822 2
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
823
                                        }
824 581
                                        $cellDataType = (string) $cAttr['t'];
825 581
                                        $originalCellDataTypeNumeric = $cellDataType === '';
826 581
                                        $value = null;
827 581
                                        $calculatedValue = null;
828
829
                                        // Read cell?
830 581
                                        if ($this->getReadFilter() !== null) {
831 581
                                            $coordinates = Coordinate::coordinateFromString($r);
832
833 581
                                            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 581
                                            case DataType::TYPE_STRING:
850 469
                                                if ((string) $c->v != '') {
851 469
                                                    $value = $sharedStrings[(int) ($c->v)];
852
853 469
                                                    if ($value instanceof RichText) {
854 33
                                                        $value = clone $value;
855
                                                    }
856
                                                } else {
857 16
                                                    $value = '';
858
                                                }
859
860 469
                                                break;
861 506
                                            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 501
                                                    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 496
                                                    $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 495
                                                            $calculatedValue = ExcelError::SPILL();
904 480
                                                        }
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 495
                                                    self::storeFormulaAttributes($c->f, $docSheet, $r);
922
                                                }
923
924
                                                break;
925 581
                                        }
926
927 581
                                        // 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 581
                                                $value = $value->getPlainText();
932
                                            }
933 581
934
                                            $cell = $docSheet->getCell($r);
935 518
                                            // 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 518
                                                if ($cellDataType === DataType::TYPE_NUMERIC && ($value === '' || $value === null)) {
939 518
                                                    $cellDataType = DataType::TYPE_NULL;
940
                                                }
941
                                                if ($cellDataType !== DataType::TYPE_NULL) {
942 472
                                                    $cell->setValueExplicit($value, $cellDataType);
943
                                                }
944 581
                                            } else {
945 337
                                                $cell->setValue($value);
946
                                            }
947
                                            if ($calculatedValue !== null) {
948
                                                $cell->setCalculatedValue($calculatedValue, $originalCellDataTypeNumeric);
949 581
                                            }
950 580
951 580
                                            // Style information?
952
                                            if (!$this->readDataOnly) {
953 580
                                                $holdSelected = $docSheet->getSelectedCells();
954 580
                                                $cAttrS = (int) ($cAttr['s'] ?? 0);
955
                                                // no style index means 0, it seems
956 580
                                                $cAttrS = isset($styles[$cAttrS]) ? $cAttrS : 0;
957 2
                                                $cell->setXfIndex($cAttrS);
958
                                                // issue 3495
959 580
                                                if ($cellDataType === DataType::TYPE_FORMULA && $styles[$cAttrS]->quotePrefix === true) {
960
                                                    $cell->getStyle()->setQuotePrefix(false);
961
                                                }
962 581
                                                $docSheet->setSelectedCells($holdSelected);
963
                                            }
964 595
                                        }
965
                                        ++$rowIndex;
966
                                    }
967 619
                                    ++$cIndex;
968 619
                                }
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 619
                                }
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 619
                                }
984 609
                            }
985
986
                            if ($xmlSheet) {
987 619
                                $this->readSheetProtection($docSheet, $xmlSheet);
988 618
                            }
989 618
990
                            if ($this->readDataOnly === false) {
991
                                $this->readAutoFilter($xmlSheetNS, $docSheet);
992 619
                                $this->readBackgroundImage($xmlSheetNS, $docSheet, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels');
993
                            }
994 619
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 619
                                }
1005 608
                            }
1006
1007
                            if ($xmlSheet && !$this->readDataOnly) {
1008 619
                                $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 619
                                }
1039 15
                            }
1040
1041
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
1042
                                (new DataValidations($docSheet, $xmlSheet))->load();
1043 619
                            }
1044 608
1045 608
                            // unparsed sheet AlternateContent
1046 4
                            if ($xmlSheet && !$this->readDataOnly) {
1047 4
                                $mc = $xmlSheet->children(Namespaces::COMPATIBILITY);
1048 4
                                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 619
                            }
1055 618
1056
                            // Add hyperlinks
1057 618
                            if (!$this->readDataOnly) {
1058 618
                                $hyperlinkReader = new Hyperlinks($docSheet);
1059 510
                                // Locate hyperlink relations
1060 510
                                $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 618
                                }
1065 17
1066
                                // Loop through hyperlinks
1067
                                if ($xmlSheetNS && $xmlSheetNS->children($mainNS)->hyperlinks) {
1068
                                    $hyperlinkReader->setHyperlinks($xmlSheetNS->children($mainNS)->hyperlinks);
1069
                                }
1070 619
                            }
1071 619
1072 619
                            // Add comments
1073
                            $comments = [];
1074 618
                            $vmlComments = [];
1075 618
                            if (!$this->readDataOnly) {
1076 510
                                // Locate comment relations
1077 510
                                $commentRelations = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
1078 372
                                if ($zip->locateName($commentRelations) !== false) {
1079 372
                                    $relsWorksheet = $this->loadZip($commentRelations, Namespaces::RELATIONSHIPS);
1080 30
                                    foreach ($relsWorksheet->Relationship as $elex) {
1081
                                        $ele = self::getAttributes($elex);
1082 372
                                        if ($ele['Type'] == Namespaces::COMMENTS) {
1083 33
                                            $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 618
                                }
1090
1091 30
                                // Loop through comments
1092
                                foreach ($comments as $relName => $relPath) {
1093 30
                                    // Load comments file
1094
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1095
                                    // okay to ignore namespace - using xpath
1096 30
                                    $commentsFile = $this->loadZip($relPath, '');
1097 30
1098 30
                                    // Utility variables
1099 30
                                    $authors = [];
1100 30
                                    $commentsFile->registerXpathNamespace('com', $mainNS);
1101
                                    $authorPath = self::xpathNoFalse($commentsFile, 'com:authors/com:author');
1102
                                    foreach ($authorPath as $author) {
1103
                                        $authors[] = (string) $author;
1104 30
                                    }
1105 30
1106 30
                                    // Loop through contents
1107 30
                                    $contentPath = self::xpathNoFalse($commentsFile, 'com:commentList/com:comment');
1108 30
                                    foreach ($contentPath as $comment) {
1109 30
                                        $commentx = $comment->attributes();
1110
                                        $commentModel = $docSheet->getComment((string) $commentx['ref']);
1111 30
                                        if (isset($commentx['authorId'])) {
1112
                                            $commentModel->setAuthor($authors[(int) $commentx['authorId']]);
1113
                                        }
1114
                                        $commentModel->setText($this->parseRichText($comment->children($mainNS)->text));
1115
                                    }
1116 618
                                }
1117 618
1118
                                // later we will remove from it real vmlComments
1119
                                $unparsedVmlDrawings = $vmlComments;
1120 618
                                $vmlDrawingContents = [];
1121
1122 33
                                // Loop through VML comments
1123
                                foreach ($vmlComments as $relName => $relPath) {
1124
                                    // Load VML comments file
1125
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1126 33
1127 33
                                    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 33
                                    }
1135 33
1136 33
                                    // Locate VML drawings image relations
1137 33
                                    $drowingImages = [];
1138 17
                                    $VMLDrawingsRelations = dirname($relPath) . '/_rels/' . basename($relPath) . '.rels';
1139 17
                                    $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 33
                                        }
1148 33
                                    }
1149 32
1150
                                    $shapes = self::xpathNoFalse($vmlCommentsFile, '//v:shape');
1151 32
                                    foreach ($shapes as $shape) {
1152 32
                                        $shape->registerXPathNamespace('v', Namespaces::URN_VML);
1153 32
1154 32
                                        if (isset($shape['style'])) {
1155 32
                                            $style = (string) $shape['style'];
1156 32
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
1157 32
                                            $column = null;
1158 32
                                            $row = null;
1159
                                            $textHAlign = null;
1160 32
                                            $fillImageRelId = null;
1161 32
                                            $fillImageTitle = '';
1162 32
1163 32
                                            $clientData = $shape->xpath('.//x:ClientData');
1164 32
                                            $textboxDirection = '';
1165 1
                                            $textboxPath = $shape->xpath('.//v:textbox');
1166 31
                                            $textbox = (string) ($textboxPath[0]['style'] ?? '');
1167 1
                                            if (preg_match('/rtl/i', $textbox) === 1) {
1168
                                                $textboxDirection = Comment::TEXTBOX_DIRECTION_RTL;
1169 32
                                            } elseif (preg_match('/ltr/i', $textbox) === 1) {
1170 31
                                                $textboxDirection = Comment::TEXTBOX_DIRECTION_LTR;
1171
                                            }
1172 31
                                            if (is_array($clientData) && !empty($clientData)) {
1173 29
                                                $clientData = $clientData[0];
1174 29
1175 29
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
1176
                                                    $temp = $clientData->xpath('.//x:Row');
1177
                                                    if (is_array($temp)) {
1178 29
                                                        $row = $temp[0];
1179 29
                                                    }
1180 29
1181
                                                    $temp = $clientData->xpath('.//x:Column');
1182 29
                                                    if (is_array($temp)) {
1183 29
                                                        $column = $temp[0];
1184 2
                                                    }
1185
                                                    $temp = $clientData->xpath('.//x:TextHAlign');
1186
                                                    if (!empty($temp)) {
1187
                                                        $textHAlign = strtolower($temp[0]);
1188 32
                                                    }
1189 32
                                                }
1190 32
                                            }
1191 2
                                            $rowx = (string) $row;
1192
                                            $colx = (string) $column;
1193 32
                                            if (is_numeric($rowx) && is_numeric($colx) && $textHAlign !== null) {
1194 2
                                                $docSheet->getComment([1 + (int) $colx, 1 + (int) $rowx], false)->setAlignment((string) $textHAlign);
1195
                                            }
1196
                                            if (is_numeric($rowx) && is_numeric($colx) && $textboxDirection !== '') {
1197 32
                                                $docSheet->getComment([1 + (int) $colx, 1 + (int) $rowx], false)->setTextboxDirection($textboxDirection);
1198 32
                                            }
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 32
                                                }
1207 32
                                            }
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 32
                                                }
1216
                                            }
1217 29
1218 29
                                            if (($column !== null) && ($row !== null)) {
1219 29
                                                // 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 29
                                                }
1233 29
1234 29
                                                // Parse style
1235
                                                $styleArray = explode(';', str_replace(' ', '', $style));
1236 29
                                                foreach ($styleArray as $stylePair) {
1237 26
                                                    $stylePair = explode(':', $stylePair);
1238
1239 29
                                                    if ($stylePair[0] == 'margin-left') {
1240 26
                                                        $comment->setMarginLeft($stylePair[1]);
1241
                                                    }
1242 29
                                                    if ($stylePair[0] == 'margin-top') {
1243 26
                                                        $comment->setMarginTop($stylePair[1]);
1244
                                                    }
1245 29
                                                    if ($stylePair[0] == 'width') {
1246 26
                                                        $comment->setWidth($stylePair[1]);
1247
                                                    }
1248 29
                                                    if ($stylePair[0] == 'height') {
1249 29
                                                        $comment->setHeight($stylePair[1]);
1250
                                                    }
1251
                                                    if ($stylePair[0] == 'visibility') {
1252
                                                        $comment->setVisible($stylePair[1] == 'visible');
1253 29
                                                    }
1254
                                                }
1255
1256
                                                unset($unparsedVmlDrawings[$relName]);
1257
                                            }
1258
                                        }
1259
                                    }
1260 618
                                }
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 618
                                }
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 619
                            }
1349 619
1350 619
                            // TODO: Autoshapes from twoCellAnchors!
1351 619
                            $drawingFilename = dirname("$dir/$fileWorksheet")
1352 619
                                . '/_rels/'
1353
                                . basename($fileWorksheet)
1354
                                . '.rels';
1355 619
                            if (str_starts_with($drawingFilename, 'xl//xl/')) {
1356
                                $drawingFilename = substr($drawingFilename, 4);
1357
                            }
1358 619
                            if (str_starts_with($drawingFilename, '/xl//xl/')) {
1359 511
                                $drawingFilename = substr($drawingFilename, 5);
1360 511
                            }
1361 511
                            if ($zip->locateName($drawingFilename) !== false) {
1362 373
                                $relsWorksheet = $this->loadZip($drawingFilename, Namespaces::RELATIONSHIPS);
1363 373
                                $drawings = [];
1364 107
                                foreach ($relsWorksheet->Relationship as $elex) {
1365 107
                                    $ele = self::getAttributes($elex);
1366 4
                                    if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
1367
                                        $eleTarget = (string) $ele['Target'];
1368 104
                                        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 511
                                    }
1374 107
                                }
1375 107
1376 107
                                if ($xmlSheetNS->drawing && !$this->readDataOnly) {
1377 107
                                    $unparsedDrawings = [];
1378 107
                                    $fileDrawing = null;
1379 107
                                    foreach ($xmlSheetNS->drawing as $drawing) {
1380 107
                                        $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id');
1381
                                        $fileDrawing = $drawings[$drawingRelId];
1382 107
                                        $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels';
1383 107
                                        $relsDrawing = $this->loadZip($drawingFilename, Namespaces::RELATIONSHIPS);
1384 107
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 107
                                            }
1417 107
                                        }
1418
1419 107
                                        $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 107
                                                }
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 107
                                                }
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 107
                                                }
1622
                                            }
1623 14
                                        }
1624
                                        if (empty($relsDrawing) && $xmlDrawing->count() == 0) {
1625
                                            // Save Drawing without rels and children as unparsed
1626
                                            $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML();
1627
                                        }
1628 107
                                    }
1629 107
1630 107
                                    // store original rId of drawing files
1631 107
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = [];
1632 107
                                    foreach ($relsWorksheet->Relationship as $elex) {
1633 107
                                        $ele = self::getAttributes($elex);
1634 107
                                        if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
1635 14
                                            $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 107
                                            }
1640 9
                                        }
1641 9
                                    }
1642 9
                                    if ($xmlSheet->legacyDrawing && !$this->readDataOnly) {
1643 9
                                        foreach ($xmlSheet->legacyDrawing as $drawing) {
1644 5
                                            $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id');
1645
                                            if (isset($vmlDrawingContents[$drawingRelId])) {
1646
                                                if (self::onlyNoteVml($vmlDrawingContents[$drawingRelId]) === false) {
1647
                                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['legacyDrawing'] = $vmlDrawingContents[$drawingRelId];
1648
                                                }
1649
                                            }
1650
                                        }
1651 107
                                    }
1652
1653 107
                                    // unparsed drawing AlternateContent
1654 4
                                    $xmlAltDrawing = $this->loadZip((string) $fileDrawing, Namespaces::COMPATIBILITY);
1655 4
1656 4
                                    if ($xmlAltDrawing->AlternateContent) {
1657
                                        foreach ($xmlAltDrawing->AlternateContent as $alternateContent) {
1658
                                            $alternateContent = self::testSimpleXml($alternateContent);
1659
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML();
1660
                                        }
1661
                                    }
1662 619
                                }
1663 619
                            }
1664
1665
                            $this->readFormControlProperties($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1666 619
                            $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1667 322
1668
                            // Loop through definedNames
1669 99
                            if ($xmlWorkbook->definedNames) {
1670 99
                                foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1671 81
                                    // Extract range
1672
                                    $extractedRange = (string) $definedName;
1673 33
                                    if (($spos = strpos($extractedRange, '!')) !== false) {
1674
                                        $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1675
                                    } else {
1676
                                        $extractedRange = str_replace('$', '', $extractedRange);
1677 99
                                    }
1678
1679
                                    // Valid range?
1680
                                    if ($extractedRange == '') {
1681
                                        continue;
1682 99
                                    }
1683
1684 45
                                    // Some definedNames are only applicable if we are on the same sheet...
1685 45
                                    if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) {
1686 18
                                        // Switch on type
1687
                                        switch ((string) $definedName['name']) {
1688
                                            case '_xlnm._FilterDatabase':
1689
                                                if ((string) $definedName['hidden'] !== '1') {
1690
                                                    $extractedRange = explode(',', $extractedRange);
1691
                                                    foreach ($extractedRange as $range) {
1692
                                                        $autoFilterRange = $range;
1693
                                                        if (str_contains($autoFilterRange, ':')) {
1694
                                                            $docSheet->getAutoFilter()->setRange($autoFilterRange);
1695
                                                        }
1696 18
                                                    }
1697 27
                                                }
1698
1699 3
                                                break;
1700
                                            case '_xlnm.Print_Titles':
1701
                                                // Split $extractedRange
1702 3
                                                $extractedRange = explode(',', $extractedRange);
1703 3
1704 3
                                                // Set print titles
1705
                                                foreach ($extractedRange as $range) {
1706
                                                    $matches = [];
1707 3
                                                    $range = str_replace('$', '', $range);
1708
1709 3
                                                    // check for repeating columns, e g. 'A:A' or 'A:D'
1710
                                                    if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
1711 3
                                                        $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]);
1712
                                                    } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
1713
                                                        // check for repeating rows, e.g. '1:1' or '1:5'
1714
                                                        $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]);
1715 3
                                                    }
1716 26
                                                }
1717 8
1718 8
                                                break;
1719 8
                                            case '_xlnm.Print_Area':
1720 8
                                                $rangeSets = preg_split("/('?(?:.*?)'?(?:![A-Z0-9]+:[A-Z0-9]+)),?/", $extractedRange, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) ?: [];
1721 8
                                                $newRangeSets = [];
1722
                                                foreach ($rangeSets as $rangeSet) {
1723
                                                    [, $rangeSet] = Worksheet::extractSheetTitle($rangeSet, true);
1724 8
                                                    if (empty($rangeSet)) {
1725
                                                        continue;
1726
                                                    }
1727 8
                                                    if (!str_contains($rangeSet, ':')) {
1728
                                                        $rangeSet = $rangeSet . ':' . $rangeSet;
1729 8
                                                    }
1730 8
                                                    $newRangeSets[] = str_replace('$', '', $rangeSet);
1731
                                                }
1732
                                                if (count($newRangeSets) > 0) {
1733 8
                                                    $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
1734
                                                }
1735 19
1736
                                                break;
1737
                                            default:
1738
                                                break;
1739
                                        }
1740
                                    }
1741
                                }
1742 619
                            }
1743
1744
                            // Next sheet id
1745
                            ++$sheetId;
1746 620
                        }
1747 322
1748
                        // Loop through definedNames
1749 99
                        if ($xmlWorkbook->definedNames) {
1750
                            foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1751
                                // Extract range
1752 99
                                $extractedRange = (string) $definedName;
1753
1754
                                // Valid range?
1755
                                if ($extractedRange == '') {
1756
                                    continue;
1757 99
                                }
1758
1759
                                // Some definedNames are only applicable if we are on the same sheet...
1760 45
                                if ((string) $definedName['localSheetId'] != '') {
1761 45
                                    // Local defined name
1762 27
                                    // Switch on type
1763 26
                                    switch ((string) $definedName['name']) {
1764 28
                                        case '_xlnm._FilterDatabase':
1765
                                        case '_xlnm.Print_Titles':
1766 19
                                        case '_xlnm.Print_Area':
1767 19
                                            break;
1768 19
                                        default:
1769 19
                                            if ($mapSheetId[(int) $definedName['localSheetId']] !== null) {
1770 19
                                                $range = Worksheet::extractSheetTitle($extractedRange, true);
1771 19
                                                $scope = $excel->getSheet($mapSheetId[(int) $definedName['localSheetId']]);
1772 19
                                                if (str_contains((string) $definedName, '!')) {
1773 19
                                                    $range[0] = str_replace("''", "'", $range[0]);
1774
                                                    $range[0] = str_replace("'", '', $range[0]);
1775 14
                                                    if ($worksheet = $excel->getSheetByName($range[0])) {
1776
                                                        $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $worksheet, $extractedRange, true, $scope));
1777
                                                    } else {
1778
                                                        $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true, $scope));
1779
                                                    }
1780
                                                } else {
1781
                                                    $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true));
1782 19
                                                }
1783
                                            }
1784 73
1785
                                            break;
1786 73
                                    }
1787 73
                                } elseif (!isset($definedName['localSheetId'])) {
1788
                                    // "Global" definedNames
1789
                                    $locatedSheet = null;
1790 54
                                    if (str_contains((string) $definedName, '!')) {
1791 54
                                        // Modify range, and extract the first worksheet reference
1792
                                        // Need to split on a comma or a space if not in quotes, and extract the first part.
1793 54
                                        $definedNameValueParts = preg_split("/[ ,](?=([^']*'[^']*')*[^']*$)/miuU", $extractedRange);
1794 54
                                        if (is_array($definedNameValueParts)) {
1795
                                            // Extract sheet name
1796
                                            [$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true);
1797 54
                                            $extractedSheetName = trim((string) $extractedSheetName, "'");
1798
1799
                                            // Locate sheet
1800
                                            $locatedSheet = $excel->getSheetByName($extractedSheetName);
1801 73
                                        }
1802 1
                                    }
1803
1804 73
                                    if ($locatedSheet === null && !DefinedName::testIfFormula($extractedRange)) {
1805
                                        $extractedRange = '#REF!';
1806
                                    }
1807
                                    $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $locatedSheet, $extractedRange, false));
1808
                                }
1809
                            }
1810 620
                        }
1811
                    }
1812 619
1813
                    (new WorkbookView($excel))->viewSettings($xmlWorkbook, $mainNS, $mapSheetId, $this->readDataOnly);
1814
1815
                    break;
1816 619
            }
1817 618
        }
1818
1819
        if (!$this->readDataOnly) {
1820 618
            $contentTypes = $this->loadZip('[Content_Types].xml');
1821 616
1822 616
            // Default content types
1823 287
            foreach ($contentTypes->Default as $contentType) {
1824
                switch ($contentType['ContentType']) {
1825 287
                    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings':
1826
                        $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType'];
1827
1828
                        break;
1829
                }
1830 618
            }
1831 617
1832 617
            // Override content types
1833 67
            foreach ($contentTypes->Override as $contentType) {
1834 65
                switch ($contentType['ContentType']) {
1835 65
                    case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
1836 65
                        if ($this->includeCharts) {
1837 65
                            $chartEntryRef = ltrim((string) $contentType['PartName'], '/');
1838 65
                            $chartElements = $this->loadZip($chartEntryRef);
1839 65
                            $chartReader = new Chart($chartNS, $drawingNS);
1840 65
                            $objChart = $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml'));
1841 65
                            if (isset($charts[$chartEntryRef])) {
1842 65
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
1843
                                if (isset($chartDetails[$chartPositionRef]) && $excel->getSheetByName($charts[$chartEntryRef]['sheet']) !== null) {
1844
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
1845 65
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
1846
                                    // For oneCellAnchor or absoluteAnchor positioned charts,
1847 61
                                    //     toCoordinate is not in the data. Does it need to be calculated?
1848 61
                                    if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) {
1849
                                        // twoCellAnchor
1850
                                        $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
1851 5
                                        $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
1852 5
                                    } else {
1853 5
                                        // oneCellAnchor or absoluteAnchor (e.g. Chart sheet)
1854 4
                                        $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
1855
                                        $objChart->setBottomRightPosition('', $chartDetails[$chartPositionRef]['width'], $chartDetails[$chartPositionRef]['height']);
1856
                                        if (array_key_exists('oneCellAnchor', $chartDetails[$chartPositionRef])) {
1857
                                            $objChart->setOneCellAnchor($chartDetails[$chartPositionRef]['oneCellAnchor']);
1858
                                        }
1859
                                    }
1860
                                }
1861 67
                            }
1862
                        }
1863
1864 617
                        break;
1865 4
1866
                        // unparsed
1867 4
                    case 'application/vnd.ms-excel.controlproperties+xml':
1868
                        $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
1869
1870
                        break;
1871
                }
1872 619
            }
1873
        }
1874 619
1875
        $excel->setUnparsedLoadedData($unparsedLoadedData);
1876 619
1877
        $zip->close();
1878
1879 71
        return $excel;
1880
    }
1881 71
1882
    private function parseRichText(?SimpleXMLElement $is): RichText
1883 71
    {
1884 20
        $value = new RichText();
1885 52
1886 52
        if (isset($is->t)) {
1887
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
1888 52
        } elseif ($is !== null) {
1889 49
            if (is_object($is->r)) {
1890 33
                /** @var SimpleXMLElement $run */
1891
                foreach ($is->r as $run) {
1892 45
                    if (!isset($run->rPr)) {
1893 45
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
1894
                    } else {
1895 45
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
1896 45
                        $objFont = $objText->getFont() ?? new StyleFont();
1897 45
1898 45
                        if (isset($run->rPr->rFont)) {
1899
                            $attr = $run->rPr->rFont->attributes();
1900
                            if (isset($attr['val'])) {
1901 45
                                $objFont->setName((string) $attr['val']);
1902 45
                            }
1903 45
                        }
1904 45
                        if (isset($run->rPr->sz)) {
1905
                            $attr = $run->rPr->sz->attributes();
1906
                            if (isset($attr['val'])) {
1907 45
                                $objFont->setSize((float) $attr['val']);
1908 43
                            }
1909
                        }
1910 45
                        if (isset($run->rPr->color)) {
1911 38
                            $objFont->setColor(new Color($this->styleReader->readColor($run->rPr->color)));
1912
                        }
1913 38
                        if (isset($run->rPr->b)) {
1914 38
                            $attr = $run->rPr->b->attributes();
1915
                            if (
1916 36
                                (isset($attr['val']) && self::boolean((string) $attr['val']))
1917
                                || (!isset($attr['val']))
1918
                            ) {
1919 45
                                $objFont->setBold(true);
1920 11
                            }
1921
                        }
1922 11
                        if (isset($run->rPr->i)) {
1923 11
                            $attr = $run->rPr->i->attributes();
1924
                            if (
1925 4
                                (isset($attr['val']) && self::boolean((string) $attr['val']))
1926
                                || (!isset($attr['val']))
1927
                            ) {
1928 45
                                $objFont->setItalic(true);
1929
                            }
1930
                        }
1931
                        if (isset($run->rPr->vertAlign)) {
1932
                            $attr = $run->rPr->vertAlign->attributes();
1933
                            if (isset($attr['val'])) {
1934
                                $vertAlign = strtolower((string) $attr['val']);
1935
                                if ($vertAlign == 'superscript') {
1936
                                    $objFont->setSuperscript(true);
1937
                                }
1938
                                if ($vertAlign == 'subscript') {
1939
                                    $objFont->setSubscript(true);
1940 45
                                }
1941 11
                            }
1942 11
                        }
1943 1
                        if (isset($run->rPr->u)) {
1944
                            $attr = $run->rPr->u->attributes();
1945 10
                            if (!isset($attr['val'])) {
1946
                                $objFont->setUnderline(StyleFont::UNDERLINE_SINGLE);
1947
                            } else {
1948 45
                                $objFont->setUnderline((string) $attr['val']);
1949 10
                            }
1950
                        }
1951 10
                        if (isset($run->rPr->strike)) {
1952 10
                            $attr = $run->rPr->strike->attributes();
1953
                            if (
1954
                                (isset($attr['val']) && self::boolean((string) $attr['val']))
1955
                                || (!isset($attr['val']))
1956
                            ) {
1957
                                $objFont->setStrikethrough(true);
1958
                            }
1959
                        }
1960
                    }
1961
                }
1962 71
            }
1963
        }
1964
1965 2
        return $value;
1966
    }
1967 2
1968 2
    private function readRibbon(Spreadsheet $excel, string $customUITarget, ZipArchive $zip): void
1969
    {
1970 2
        $baseDir = dirname($customUITarget);
1971 2
        $nameCustomUI = basename($customUITarget);
1972 2
        // get the xml file (ribbon)
1973
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
1974 2
        $customUIImagesNames = [];
1975 2
        $customUIImagesBinaries = [];
1976 2
        // something like customUI/_rels/customUI.xml.rels
1977
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
1978
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
1979
        if ($dataRels) {
1980
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
1981
            $UIRels = simplexml_load_string(
1982
                $this->getSecurityScannerOrThrow()->scan($dataRels),
1983
                'SimpleXMLElement',
1984
                Settings::getLibXmlLoaderOptions()
1985
            );
1986
            if (false !== $UIRels) {
1987
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
1988
                foreach ($UIRels->Relationship as $ele) {
1989
                    if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/image') {
1990
                        // an image ?
1991
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
1992
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
1993
                    }
1994 2
                }
1995 2
            }
1996 2
        }
1997
        if ($localRibbon) {
1998
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
1999 2
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2000
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
2001
            } else {
2002
                $excel->setRibbonBinObjects(null, null);
2003
            }
2004
        } else {
2005
            $excel->setRibbonXMLData(null, null);
2006
            $excel->setRibbonBinObjects(null, null);
2007 635
        }
2008
    }
2009 635
2010
    private static function getArrayItem(null|array|bool|SimpleXMLElement $array, int|string $key = 0): mixed
2011
    {
2012 345
        return ($array === null || is_bool($array)) ? null : ($array[$key] ?? null);
2013
    }
2014 345
2015 345
    private static function dirAdd(null|SimpleXMLElement|string $base, null|SimpleXMLElement|string $add): string
2016
    {
2017 345
        $base = (string) $base;
2018
        $add = (string) $add;
2019
2020 2
        return (string) preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
2021
    }
2022 2
2023
    private static function toCSSArray(string $style): array
2024 2
    {
2025 2
        $style = self::stripWhiteSpaceFromStyleString($style);
2026 2
2027 2
        $temp = explode(';', $style);
2028
        $style = [];
2029 2
        foreach ($temp as $item) {
2030 1
            $item = explode(':', $item);
2031
2032 2
            if (str_contains($item[1], 'px')) {
2033 2
                $item[1] = str_replace('px', '', $item[1]);
2034 2
            }
2035
            if (str_contains($item[1], 'pt')) {
2036 2
                $item[1] = str_replace('pt', '', $item[1]);
2037
                $item[1] = (string) Font::fontSizeToPixels((int) $item[1]);
2038
            }
2039
            if (str_contains($item[1], 'in')) {
2040 2
                $item[1] = str_replace('in', '', $item[1]);
2041
                $item[1] = (string) Font::inchSizeToPixels((int) $item[1]);
2042
            }
2043
            if (str_contains($item[1], 'cm')) {
2044
                $item[1] = str_replace('cm', '', $item[1]);
2045 2
                $item[1] = (string) Font::centimeterSizeToPixels((int) $item[1]);
2046
            }
2047
2048 2
            $style[$item[0]] = $item[1];
2049
        }
2050
2051 5
        return $style;
2052
    }
2053 5
2054
    public static function stripWhiteSpaceFromStyleString(string $string): string
2055
    {
2056 87
        return trim(str_replace(["\r", "\n", ' '], '', $string), ';');
2057
    }
2058 87
2059 68
    private static function boolean(string $value): bool
2060
    {
2061
        if (is_numeric($value)) {
2062 32
            return (bool) $value;
2063
        }
2064
2065 52
        return $value === 'true' || $value === 'TRUE';
2066
    }
2067 52
2068
    private function readHyperLinkDrawing(\PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing, SimpleXMLElement $cellAnchor, array $hyperlinks): void
2069 52
    {
2070 50
        $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick;
2071
2072
        if ($hlinkClick->count() === 0) {
2073 2
            return;
2074 2
        }
2075 2
2076 2
        $hlinkId = (string) self::getAttributes($hlinkClick, Namespaces::SCHEMA_OFFICE_DOCUMENT)['id'];
2077 2
        $hyperlink = new Hyperlink(
2078 2
            $hyperlinks[$hlinkId],
2079
            (string) self::getArrayItem(self::getAttributes($cellAnchor->pic->nvPicPr->cNvPr), 'name')
2080
        );
2081 620
        $objDrawing->setHyperlink($hyperlink);
2082
    }
2083 620
2084 600
    private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook): void
2085
    {
2086
        if (!$xmlWorkbook->workbookProtection) {
2087 24
            return;
2088 24
        }
2089 24
2090
        $excel->getSecurity()->setLockRevision(self::getLockValue($xmlWorkbook->workbookProtection, 'lockRevision'));
2091 24
        $excel->getSecurity()->setLockStructure(self::getLockValue($xmlWorkbook->workbookProtection, 'lockStructure'));
2092 1
        $excel->getSecurity()->setLockWindows(self::getLockValue($xmlWorkbook->workbookProtection, 'lockWindows'));
2093 1
2094 1
        if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
2095 1
            $excel->getSecurity()->setRevisionsPassword(
2096
                (string) $xmlWorkbook->workbookProtection['revisionsPassword'],
2097
                true
2098 24
            );
2099 2
        }
2100 2
2101 2
        if ($xmlWorkbook->workbookProtection['workbookPassword']) {
2102 2
            $excel->getSecurity()->setWorkbookPassword(
2103
                (string) $xmlWorkbook->workbookProtection['workbookPassword'],
2104
                true
2105
            );
2106 24
        }
2107
    }
2108 24
2109 24
    private static function getLockValue(SimpleXMLElement $protection, string $key): ?bool
2110 24
    {
2111 10
        $returnValue = null;
2112 10
        $protectKey = $protection[$key];
2113
        if (!empty($protectKey)) {
2114
            $protectKey = (string) $protectKey;
2115 24
            $returnValue = $protectKey !== 'false' && (bool) $protectKey;
2116
        }
2117
2118 619
        return $returnValue;
2119
    }
2120 619
2121 619
    private function readFormControlProperties(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void
2122 327
    {
2123
        $zip = $this->zip;
2124
        if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) {
2125 511
            return;
2126 511
        }
2127 511
2128 511
        $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
2129 368
        $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS);
2130 4
        $ctrlProps = [];
2131
        foreach ($relsWorksheet->Relationship as $ele) {
2132
            if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/ctrlProp') {
2133
                $ctrlProps[(string) $ele['Id']] = $ele;
2134 511
            }
2135 511
        }
2136 4
2137 4
        $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
2138 4
        foreach ($ctrlProps as $rId => $ctrlProp) {
2139 4
            $rId = substr($rId, 3); // rIdXXX
2140 4
            $unparsedCtrlProps[$rId] = [];
2141
            $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
2142 511
            $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
2143
            $unparsedCtrlProps[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
2144
        }
2145 619
        unset($unparsedCtrlProps);
2146
    }
2147 619
2148 619
    private function readPrinterSettings(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void
2149 327
    {
2150
        $zip = $this->zip;
2151
        if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) {
2152 511
            return;
2153 511
        }
2154 511
2155 511
        $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
2156 368
        $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS);
2157 279
        $sheetPrinterSettings = [];
2158
        foreach ($relsWorksheet->Relationship as $ele) {
2159
            if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/printerSettings') {
2160
                $sheetPrinterSettings[(string) $ele['Id']] = $ele;
2161 511
            }
2162 511
        }
2163 279
2164 279
        $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
2165 279
        foreach ($sheetPrinterSettings as $rId => $printerSettings) {
2166
            $rId = substr($rId, 3); // rIdXXX
2167 279
            if (!str_ends_with($rId, 'ps')) {
2168 279
                $rId = $rId . 'ps'; // rIdXXX, add 'ps' suffix to avoid identical resource identifier collision with unparsed vmlDrawing
2169 279
            }
2170 279
            $unparsedPrinterSettings[$rId] = [];
2171 279
            $target = (string) str_replace('/xl/', '../', (string) $printerSettings['Target']);
2172
            $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $target);
2173 511
            $unparsedPrinterSettings[$rId]['relFilePath'] = $target;
2174
            $unparsedPrinterSettings[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
2175
        }
2176 624
        unset($unparsedPrinterSettings);
2177
    }
2178 624
2179 624
    private function getWorkbookBaseName(): array
2180
    {
2181
        $workbookBasename = '';
2182 624
        $xmlNamespaceBase = '';
2183 624
2184 624
        // check if it is an OOXML archive
2185 624
        $rels = $this->loadZip(self::INITIAL_FILE);
2186
        foreach ($rels->children(Namespaces::RELATIONSHIPS)->Relationship as $rel) {
2187 616
            $rel = self::getAttributes($rel);
2188 606
            $type = (string) $rel['Type'];
2189 624
            switch ($type) {
2190 624
                case Namespaces::OFFICE_DOCUMENT:
2191 624
                case Namespaces::PURL_OFFICE_DOCUMENT:
2192 624
                    $basename = basename((string) $rel['Target']);
2193
                    $xmlNamespaceBase = dirname($type);
2194
                    if (preg_match('/workbook.*\.xml/', $basename)) {
2195 624
                        $workbookBasename = $basename;
2196
                    }
2197
2198
                    break;
2199 624
            }
2200
        }
2201
2202 609
        return [$workbookBasename, $xmlNamespaceBase];
2203
    }
2204 609
2205 553
    private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void
2206
    {
2207
        if ($this->readDataOnly || !$xmlSheet->sheetProtection) {
2208 66
            return;
2209 66
        }
2210 66
2211
        $algorithmName = (string) $xmlSheet->sheetProtection['algorithmName'];
2212 66
        $protection = $docSheet->getProtection();
2213 2
        $protection->setAlgorithm($algorithmName);
2214 2
2215 2
        if ($algorithmName) {
2216
            $protection->setPassword((string) $xmlSheet->sheetProtection['hashValue'], true);
2217 65
            $protection->setSalt((string) $xmlSheet->sheetProtection['saltValue']);
2218
            $protection->setSpinCount((int) $xmlSheet->sheetProtection['spinCount']);
2219
        } else {
2220 66
            $protection->setPassword((string) $xmlSheet->sheetProtection['password'], true);
2221 3
        }
2222 3
2223
        if ($xmlSheet->protectedRanges->protectedRange) {
2224
            foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
2225
                $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true, (string) $protectedRange['name'], (string) $protectedRange['securityDescriptor']);
2226
            }
2227 618
        }
2228
    }
2229
2230
    private function readAutoFilter(
2231 618
        SimpleXMLElement $xmlSheet,
2232 16
        Worksheet $docSheet
2233
    ): void {
2234
        if ($xmlSheet && $xmlSheet->autoFilter) {
2235
            (new AutoFilter($docSheet, $xmlSheet))->load();
2236 618
        }
2237
    }
2238
2239
    private function readBackgroundImage(
2240
        SimpleXMLElement $xmlSheet,
2241 618
        Worksheet $docSheet,
2242 1
        string $relsName
2243 1
    ): void {
2244 1
        if ($xmlSheet && $xmlSheet->picture) {
2245 1
            $id = (string) self::getArrayItem(self::getAttributes($xmlSheet->picture, Namespaces::SCHEMA_OFFICE_DOCUMENT), 'id');
2246 1
            $rels = $this->loadZip($relsName);
2247 1
            foreach ($rels->Relationship as $rel) {
2248 1
                $attrs = $rel->attributes() ?? [];
2249 1
                $rid = (string) ($attrs['Id'] ?? '');
2250 1
                $target = (string) ($attrs['Target'] ?? '');
2251 1
                if ($rid === $id && substr($target, 0, 2) === '..') {
2252
                    $target = 'xl' . substr($target, 2);
2253
                    $content = $this->getFromZipArchive($this->zip, $target);
2254
                    $docSheet->setBackgroundImage($content);
2255
                }
2256
            }
2257 619
        }
2258
    }
2259
2260
    private function readTables(
2261
        SimpleXMLElement $xmlSheet,
2262
        Worksheet $docSheet,
2263
        string $dir,
2264
        string $fileWorksheet,
2265 619
        ZipArchive $zip,
2266 31
        string $namespaceTable
2267 31
    ): void {
2268 27
        if ($xmlSheet && $xmlSheet->tableParts) {
2269
            $attributes = $xmlSheet->tableParts->attributes() ?? ['count' => 0];
2270
            if (((int) $attributes['count']) > 0) {
2271
                $this->readTablesInTablesFile($xmlSheet, $dir, $fileWorksheet, $zip, $docSheet, $namespaceTable);
2272
            }
2273 27
        }
2274
    }
2275
2276
    private function readTablesInTablesFile(
2277
        SimpleXMLElement $xmlSheet,
2278
        string $dir,
2279
        string $fileWorksheet,
2280
        ZipArchive $zip,
2281 27
        Worksheet $docSheet,
2282 27
        string $namespaceTable
2283 27
    ): void {
2284 27
        foreach ($xmlSheet->tableParts->tablePart as $tablePart) {
2285
            $relation = self::getAttributes($tablePart, Namespaces::SCHEMA_OFFICE_DOCUMENT);
2286 27
            $tablePartRel = (string) $relation['id'];
2287 27
            $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
2288 27
2289 27
            if ($zip->locateName($relationsFileName) !== false) {
2290
                $relsTableReferences = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS);
2291 27
                foreach ($relsTableReferences->Relationship as $relationship) {
2292 27
                    $relationshipAttributes = self::getAttributes($relationship, '');
2293 27
2294 27
                    if ((string) $relationshipAttributes['Id'] === $tablePartRel) {
2295
                        $relationshipFileName = (string) $relationshipAttributes['Target'];
2296 27
                        $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName;
2297 27
                        $relationshipFilePath = File::realpath($relationshipFilePath);
2298 27
2299
                        if ($this->fileExistsInArchive($this->zip, $relationshipFilePath)) {
2300
                            $tableXml = $this->loadZip($relationshipFilePath, $namespaceTable);
2301
                            (new TableReader($docSheet, $tableXml))->load();
2302
                        }
2303
                    }
2304
                }
2305
            }
2306 620
        }
2307
    }
2308 620
2309 620
    private static function extractStyles(?SimpleXMLElement $sxml, string $node1, string $node2): array
2310 620
    {
2311 620
        $array = [];
2312
        if ($sxml && $sxml->{$node1}->{$node2}) {
2313
            foreach ($sxml->{$node1}->{$node2} as $node) {
2314
                $array[] = $node;
2315 620
            }
2316
        }
2317
2318 620
        return $array;
2319
    }
2320 620
2321 620
    private static function extractPalette(?SimpleXMLElement $sxml): array
2322 15
    {
2323 15
        $array = [];
2324 15
        if ($sxml && $sxml->colors->indexedColors) {
2325 15
            foreach ($sxml->colors->indexedColors->rgbColor as $node) {
2326 15
                if ($node !== null) {
2327
                    $attr = $node->attributes();
2328
                    if (isset($attr['rgb'])) {
2329
                        $array[] = (string) $attr['rgb'];
2330
                    }
2331
                }
2332 620
            }
2333
        }
2334
2335 3
        return $array;
2336
    }
2337 3
2338 3
    private function processIgnoredErrors(SimpleXMLElement $xml, Worksheet $sheet): void
2339 3
    {
2340 3
        $attributes = self::getAttributes($xml);
2341 3
        $sqref = (string) ($attributes['sqref'] ?? '');
2342 3
        $numberStoredAsText = (string) ($attributes['numberStoredAsText'] ?? '');
2343 3
        $formula = (string) ($attributes['formula'] ?? '');
2344 3
        $twoDigitTextYear = (string) ($attributes['twoDigitTextYear'] ?? '');
2345 3
        $evalError = (string) ($attributes['evalError'] ?? '');
2346 3
        if (!empty($sqref)) {
2347 3
            $explodedSqref = explode(' ', $sqref);
2348 3
            $pattern1 = '/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/';
2349 3
            foreach ($explodedSqref as $sqref1) {
2350 3
                if (preg_match($pattern1, $sqref1, $matches) === 1) {
2351 2
                    $firstRow = $matches[2];
2352 2
                    $firstCol = $matches[1];
2353
                    if (array_key_exists(3, $matches)) {
2354 3
                        $lastCol = $matches[4];
2355 3
                        $lastRow = $matches[5];
2356
                    } else {
2357 3
                        $lastCol = $firstCol;
2358 3
                        $lastRow = $firstRow;
2359 3
                    }
2360 3
                    ++$lastCol;
2361 3
                    for ($row = $firstRow; $row <= $lastRow; ++$row) {
2362
                        for ($col = $firstCol; $col !== $lastCol; ++$col) {
2363 3
                            if ($numberStoredAsText === '1') {
2364 1
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setNumberStoredAsText(true);
2365
                            }
2366 3
                            if ($formula === '1') {
2367 1
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setFormula(true);
2368
                            }
2369 3
                            if ($twoDigitTextYear === '1') {
2370 1
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setTwoDigitTextYear(true);
2371
                            }
2372
                            if ($evalError === '1') {
2373
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setEvalError(true);
2374
                            }
2375
                        }
2376
                    }
2377
                }
2378
            }
2379 9
        }
2380
    }
2381 9
2382
    private static function storeFormulaAttributes(SimpleXMLElement $f, Worksheet $docSheet, string $r): void
2383
    {
2384 9
        $formulaAttributes = [];
2385
        $attributes = $f->attributes();
2386
        if (isset($attributes['t'])) {
2387
            $formulaAttributes['t'] = (string) $attributes['t'];
2388
        }
2389 9
        if (isset($attributes['ref'])) {
2390 1
            $formulaAttributes['ref'] = (string) $attributes['ref'];
2391
        }
2392 8
        if (!empty($formulaAttributes)) {
2393 8
            $docSheet->getCell($r)->setFormulaAttributes($formulaAttributes);
2394 8
        }
2395 8
    }
2396
2397
    private static function onlyNoteVml(string $data): bool
2398 8
    {
2399 8
        $data = str_replace('<br>', '<br/>', $data);
2400
2401
        try {
2402 8
            $sxml = @simplexml_load_string($data);
2403 8
        } catch (Throwable) {
2404 4
            $sxml = false;
2405
        }
2406
2407
        if ($sxml === false) {
2408 5
            return false;
2409
        }
2410
        $shapes = $sxml->children(Namespaces::URN_VML);
2411
        foreach ($shapes->shape as $shape) {
2412
            $clientData = $shape->children(Namespaces::URN_EXCEL);
2413
            if (!isset($clientData->ClientData)) {
2414
                return false;
2415
            }
2416
            $attrs = $clientData->ClientData->attributes();
2417
            if (!isset($attrs['ObjectType'])) {
2418
                return false;
2419
            }
2420
            $objectType = (string) $attrs['ObjectType'];
2421
            if ($objectType !== 'Note') {
2422
                return false;
2423
            }
2424
        }
2425
2426
        return true;
2427
    }
2428
}
2429