Passed
Pull Request — master (#3481)
by Mark
11:46
created

Xlsx::listWorksheetInfo()   C

Complexity

Conditions 17
Paths 38

Size

Total Lines 84
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 60
CRAP Score 17

Importance

Changes 0
Metric Value
eloc 57
dl 0
loc 84
rs 5.2166
c 0
b 0
f 0
ccs 60
cts 60
cp 1
cc 17
nc 38
nop 1
crap 17

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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