Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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