Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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