Passed
Push — master ( 440039...6cc2bb )
by Mark
23:06 queued 12:16
created

Xlsx::testSimpleXml()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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