• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PhpSpreadsheet / 18013950625

25 Sep 2025 04:20PM UTC coverage: 95.867% (+0.3%) from 95.602%
18013950625

push

github

web-flow
Merge pull request #4663 from oleibman/tweakcoveralls

Tweak Coveralls

45116 of 47061 relevant lines covered (95.87%)

373.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.77
/src/PhpSpreadsheet/Reader/Xlsx.php
1
<?php
2

3
namespace PhpOffice\PhpSpreadsheet\Reader;
4

5
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
6
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
7
use PhpOffice\PhpSpreadsheet\Cell\DataType;
8
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
9
use PhpOffice\PhpSpreadsheet\Comment;
10
use PhpOffice\PhpSpreadsheet\DefinedName;
11
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
12
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\AutoFilter;
13
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart;
14
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ColumnAndRowAttributes;
15
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ConditionalStyles;
16
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\DataValidations;
17
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Hyperlinks;
18
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
19
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\PageSetup;
20
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Properties as PropertyReader;
21
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SharedFormula;
22
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViewOptions;
23
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViews;
24
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles;
25
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\TableReader;
26
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Theme;
27
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\WorkbookView;
28
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
29
use PhpOffice\PhpSpreadsheet\RichText\RichText;
30
use PhpOffice\PhpSpreadsheet\Shared\Date;
31
use PhpOffice\PhpSpreadsheet\Shared\Drawing;
32
use PhpOffice\PhpSpreadsheet\Shared\File;
33
use PhpOffice\PhpSpreadsheet\Shared\Font;
34
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
35
use PhpOffice\PhpSpreadsheet\Spreadsheet;
36
use PhpOffice\PhpSpreadsheet\Style\Color;
37
use PhpOffice\PhpSpreadsheet\Style\Font as StyleFont;
38
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
39
use PhpOffice\PhpSpreadsheet\Style\Style;
40
use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing;
41
use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableDxfsStyle;
42
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
43
use SimpleXMLElement;
44
use Throwable;
45
use XMLReader;
46
use ZipArchive;
47

48
class Xlsx extends BaseReader
49
{
50
    const INITIAL_FILE = '_rels/.rels';
51

52
    /**
53
     * ReferenceHelper instance.
54
     */
55
    private ReferenceHelper $referenceHelper;
56

57
    private ZipArchive $zip;
58

59
    private Styles $styleReader;
60

61
    /** @var SharedFormula[] */
62
    private array $sharedFormulae = [];
63

64
    private bool $parseHuge = false;
65

66
    /**
67
     * Allow use of LIBXML_PARSEHUGE.
68
     * This option can lead to memory leaks and failures,
69
     * and is not recommended. But some very large spreadsheets
70
     * seem to require it.
71
     */
72
    public function setParseHuge(bool $parseHuge): void
×
73
    {
74
        $this->parseHuge = $parseHuge;
×
75
    }
76

77
    /**
78
     * Create a new Xlsx Reader instance.
79
     */
80
    public function __construct()
774✔
81
    {
82
        parent::__construct();
774✔
83
        $this->referenceHelper = ReferenceHelper::getInstance();
774✔
84
        $this->securityScanner = XmlScanner::getInstance($this);
774✔
85
    }
86

87
    /**
88
     * Can the current IReader read the file?
89
     */
90
    public function canRead(string $filename): bool
39✔
91
    {
92
        if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) {
39✔
93
            return false;
16✔
94
        }
95

96
        $result = false;
23✔
97
        $this->zip = $zip = new ZipArchive();
23✔
98

99
        if ($zip->open($filename) === true) {
23✔
100
            [$workbookBasename] = $this->getWorkbookBaseName();
23✔
101
            $result = !empty($workbookBasename);
23✔
102

103
            $zip->close();
23✔
104
        }
105

106
        return $result;
23✔
107
    }
108

109
    public static function testSimpleXml(mixed $value): SimpleXMLElement
747✔
110
    {
111
        return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
747✔
112
    }
113

114
    public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement
743✔
115
    {
116
        return self::testSimpleXml($value === null ? $value : $value->attributes($ns));
743✔
117
    }
118

119
    // Phpstan thinks, correctly, that xpath can return false.
120
    /** @return mixed[] */
121
    private static function xpathNoFalse(SimpleXMLElement $sxml, string $path): array
713✔
122
    {
123
        return self::falseToArray($sxml->xpath($path));
713✔
124
    }
125

126
    /** @return mixed[] */
127
    public static function falseToArray(mixed $value): array
713✔
128
    {
129
        return is_array($value) ? $value : [];
713✔
130
    }
131

132
    private function loadZip(string $filename, string $ns = '', bool $replaceUnclosedBr = false): SimpleXMLElement
743✔
133
    {
134
        $contents = $this->getFromZipArchive($this->zip, $filename);
743✔
135
        if ($replaceUnclosedBr) {
743✔
136
            $contents = str_replace('<br>', '<br/>', $contents);
38✔
137
        }
138
        $rels = @simplexml_load_string(
743✔
139
            $this->getSecurityScannerOrThrow()->scan($contents),
743✔
140
            SimpleXMLElement::class,
743✔
141
            $this->parseHuge ? LIBXML_PARSEHUGE : 0,
743✔
142
            $ns
743✔
143
        );
743✔
144

145
        return self::testSimpleXml($rels);
743✔
146
    }
147

148
    // This function is just to identify cases where I'm not sure
149
    // why empty namespace is required.
150
    private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElement
711✔
151
    {
152
        $contents = $this->getFromZipArchive($this->zip, $filename);
711✔
153
        $rels = simplexml_load_string(
711✔
154
            $this->getSecurityScannerOrThrow()->scan($contents),
711✔
155
            SimpleXMLElement::class,
711✔
156
            $this->parseHuge ? LIBXML_PARSEHUGE : 0,
711✔
157
            ($ns === '' ? $ns : '')
711✔
158
        );
711✔
159

160
        return self::testSimpleXml($rels);
706✔
161
    }
162

163
    private const REL_TO_MAIN = [
164
        Namespaces::PURL_OFFICE_DOCUMENT => Namespaces::PURL_MAIN,
165
        Namespaces::THUMBNAIL => '',
166
    ];
167

168
    private const REL_TO_DRAWING = [
169
        Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING,
170
    ];
171

172
    private const REL_TO_CHART = [
173
        Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_CHART,
174
    ];
175

176
    /**
177
     * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
178
     *
179
     * @return string[]
180
     */
181
    public function listWorksheetNames(string $filename): array
18✔
182
    {
183
        File::assertFile($filename, self::INITIAL_FILE);
18✔
184

185
        $worksheetNames = [];
15✔
186

187
        $this->zip = $zip = new ZipArchive();
15✔
188
        $zip->open($filename);
15✔
189

190
        //    The files we're looking at here are small enough that simpleXML is more efficient than XMLReader
191
        $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
15✔
192
        foreach ($rels->Relationship as $relx) {
15✔
193
            $rel = self::getAttributes($relx);
15✔
194
            $relType = (string) $rel['Type'];
15✔
195
            $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
15✔
196
            if ($mainNS !== '') {
15✔
197
                $xmlWorkbook = $this->loadZip((string) $rel['Target'], $mainNS);
15✔
198

199
                if ($xmlWorkbook->sheets) {
15✔
200
                    foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
15✔
201
                        // Check if sheet should be skipped
202
                        $worksheetNames[] = (string) self::getAttributes($eleSheet)['name'];
15✔
203
                    }
204
                }
205
            }
206
        }
207

208
        $zip->close();
15✔
209

210
        return $worksheetNames;
15✔
211
    }
212

213
    /**
214
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
215
     *
216
     * @return array<int, array{worksheetName: string, lastColumnLetter: string, lastColumnIndex: int, totalRows: int, totalColumns: int, sheetState: string}>
217
     */
218
    public function listWorksheetInfo(string $filename): array
19✔
219
    {
220
        File::assertFile($filename, self::INITIAL_FILE);
19✔
221

222
        $worksheetInfo = [];
16✔
223

224
        $this->zip = $zip = new ZipArchive();
16✔
225
        $zip->open($filename);
16✔
226

227
        $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
16✔
228
        foreach ($rels->Relationship as $relx) {
16✔
229
            $rel = self::getAttributes($relx);
16✔
230
            $relType = (string) $rel['Type'];
16✔
231
            $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
16✔
232
            if ($mainNS !== '') {
16✔
233
                $relTarget = (string) $rel['Target'];
16✔
234
                $dir = dirname($relTarget);
16✔
235
                $namespace = dirname($relType);
16✔
236
                $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', Namespaces::RELATIONSHIPS);
16✔
237

238
                $worksheets = [];
16✔
239
                foreach ($relsWorkbook->Relationship as $elex) {
16✔
240
                    $ele = self::getAttributes($elex);
16✔
241
                    if (
242
                        ((string) $ele['Type'] === "$namespace/worksheet")
16✔
243
                        || ((string) $ele['Type'] === "$namespace/chartsheet")
16✔
244
                    ) {
245
                        $worksheets[(string) $ele['Id']] = $ele['Target'];
16✔
246
                    }
247
                }
248

249
                $xmlWorkbook = $this->loadZip($relTarget, $mainNS);
16✔
250
                if ($xmlWorkbook->sheets) {
16✔
251
                    $dir = dirname($relTarget);
16✔
252

253
                    foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
16✔
254
                        $tmpInfo = [
16✔
255
                            'worksheetName' => (string) self::getAttributes($eleSheet)['name'],
16✔
256
                            'lastColumnLetter' => 'A',
16✔
257
                            'lastColumnIndex' => 0,
16✔
258
                            'totalRows' => 0,
16✔
259
                            'totalColumns' => 0,
16✔
260
                        ];
16✔
261
                        $sheetState = (string) (self::getAttributes($eleSheet)['state'] ?? Worksheet::SHEETSTATE_VISIBLE);
16✔
262
                        $tmpInfo['sheetState'] = $sheetState;
16✔
263

264
                        $fileWorksheet = (string) $worksheets[self::getArrayItemString(self::getAttributes($eleSheet, $namespace), 'id')];
16✔
265
                        $fileWorksheetPath = str_starts_with($fileWorksheet, '/') ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet";
16✔
266

267
                        $xml = new XMLReader();
16✔
268
                        $xml->xml(
16✔
269
                            $this->getSecurityScannerOrThrow()
16✔
270
                                ->scan(
16✔
271
                                    $this->getFromZipArchive(
16✔
272
                                        $this->zip,
16✔
273
                                        $fileWorksheetPath
16✔
274
                                    )
16✔
275
                                ),
16✔
276
                            null,
16✔
277
                            $this->parseHuge ? LIBXML_PARSEHUGE : 0
16✔
278
                        );
16✔
279
                        $xml->setParserProperty(2, true);
16✔
280

281
                        $currCells = 0;
16✔
282
                        while ($xml->read()) {
16✔
283
                            if ($xml->localName == 'row' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) {
16✔
284
                                $row = (int) $xml->getAttribute('r');
16✔
285
                                $tmpInfo['totalRows'] = $row;
16✔
286
                                $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
16✔
287
                                $currCells = 0;
16✔
288
                            } elseif ($xml->localName == 'c' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) {
16✔
289
                                $cell = $xml->getAttribute('r');
16✔
290
                                $currCells = $cell ? max($currCells, Coordinate::indexesFromString($cell)[0]) : ($currCells + 1);
16✔
291
                            }
292
                        }
293
                        $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
16✔
294
                        $xml->close();
16✔
295

296
                        $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
16✔
297
                        $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
16✔
298

299
                        $worksheetInfo[] = $tmpInfo;
16✔
300
                    }
301
                }
302
            }
303
        }
304

305
        $zip->close();
16✔
306

307
        return $worksheetInfo;
16✔
308
    }
309

310
    private static function castToBoolean(SimpleXMLElement $c): bool
22✔
311
    {
312
        $value = isset($c->v) ? (string) $c->v : null;
22✔
313
        if ($value == '0') {
22✔
314
            return false;
15✔
315
        } elseif ($value == '1') {
18✔
316
            return true;
18✔
317
        }
318

319
        return (bool) $c->v;
×
320
    }
321

322
    private static function castToError(?SimpleXMLElement $c): ?string
189✔
323
    {
324
        return isset($c, $c->v) ? (string) $c->v : null;
189✔
325
    }
326

327
    private static function castToString(?SimpleXMLElement $c): ?string
551✔
328
    {
329
        return isset($c, $c->v) ? (string) $c->v : null;
551✔
330
    }
331

332
    public static function replacePrefixes(string $formula): string
383✔
333
    {
334
        return str_replace(['_xlfn.', '_xlws.'], '', $formula);
383✔
335
    }
336

337
    private function castToFormula(?SimpleXMLElement $c, string $r, string &$cellDataType, mixed &$value, mixed &$calculatedValue, string $castBaseType, bool $updateSharedCells = true): void
373✔
338
    {
339
        if ($c === null) {
373✔
340
            return;
×
341
        }
342
        $attr = $c->f->attributes();
373✔
343
        $cellDataType = DataType::TYPE_FORMULA;
373✔
344
        $formula = self::replacePrefixes((string) $c->f);
373✔
345
        $value = "=$formula";
373✔
346
        $calculatedValue = self::$castBaseType($c);
373✔
347

348
        // Shared formula?
349
        if (isset($attr['t']) && strtolower((string) $attr['t']) == 'shared') {
373✔
350
            $instance = (string) $attr['si'];
219✔
351

352
            if (!isset($this->sharedFormulae[(string) $attr['si']])) {
219✔
353
                $this->sharedFormulae[$instance] = new SharedFormula($r, $value);
219✔
354
            } elseif ($updateSharedCells === true) {
218✔
355
                // It's only worth the overhead of adjusting the shared formula for this cell if we're actually loading
356
                //     the cell, which may not be the case if we're using a read filter.
357
                $master = Coordinate::indexesFromString($this->sharedFormulae[$instance]->master());
218✔
358
                $current = Coordinate::indexesFromString($r);
218✔
359

360
                $difference = [0, 0];
218✔
361
                $difference[0] = $current[0] - $master[0];
218✔
362
                $difference[1] = $current[1] - $master[1];
218✔
363

364
                $value = $this->referenceHelper->updateFormulaReferences($this->sharedFormulae[$instance]->formula(), 'A1', $difference[0], $difference[1]);
218✔
365
            }
366
        }
367
    }
368

369
    private function fileExistsInArchive(ZipArchive $archive, string $fileName = ''): bool
698✔
370
    {
371
        // Root-relative paths
372
        if (str_contains($fileName, '//')) {
698✔
373
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
1✔
374
        }
375
        $fileName = File::realpath($fileName);
698✔
376

377
        // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
378
        //    so we need to load case-insensitively from the zip file
379

380
        // Apache POI fixes
381
        $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE);
698✔
382
        if ($contents === false) {
698✔
383
            $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE);
4✔
384
        }
385

386
        return $contents !== false;
698✔
387
    }
388

389
    private function getFromZipArchive(ZipArchive $archive, string $fileName = ''): string
743✔
390
    {
391
        // Root-relative paths
392
        if (str_contains($fileName, '//')) {
743✔
393
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
2✔
394
        }
395
        // Relative paths generated by dirname($filename) when $filename
396
        // has no path (i.e.files in root of the zip archive)
397
        $fileName = (string) preg_replace('/^\.\//', '', $fileName);
743✔
398
        $fileName = File::realpath($fileName);
743✔
399

400
        // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
401
        //    so we need to load case-insensitively from the zip file
402

403
        $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
743✔
404

405
        // Apache POI fixes
406
        if ($contents === false) {
743✔
407
            $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
53✔
408
        }
409

410
        // Has the file been saved with Windoze directory separators rather than unix?
411
        if ($contents === false) {
743✔
412
            $contents = $archive->getFromName(str_replace('/', '\\', $fileName), 0, ZipArchive::FL_NOCASE);
50✔
413
        }
414

415
        return ($contents === false) ? '' : $contents;
743✔
416
    }
417

418
    /**
419
     * Loads Spreadsheet from file.
420
     */
421
    protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
716✔
422
    {
423
        File::assertFile($filename, self::INITIAL_FILE);
716✔
424

425
        // Initialisations
426
        $excel = $this->newSpreadsheet();
713✔
427
        $excel->setValueBinder($this->valueBinder);
713✔
428
        $excel->removeSheetByIndex(0);
713✔
429
        $addingFirstCellStyleXf = true;
713✔
430
        $addingFirstCellXf = true;
713✔
431

432
        /** @var mixed[][][][] */
433
        $unparsedLoadedData = [];
713✔
434

435
        $this->zip = $zip = new ZipArchive();
713✔
436
        $zip->open($filename);
713✔
437

438
        //    Read the theme first, because we need the colour scheme when reading the styles
439
        [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName();
713✔
440
        $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML;
713✔
441
        $chartNS = self::REL_TO_CHART[$xmlNamespaceBase] ?? Namespaces::CHART;
713✔
442
        $wbRels = $this->loadZip("xl/_rels/{$workbookBasename}.rels", Namespaces::RELATIONSHIPS);
713✔
443
        $theme = null;
713✔
444
        $this->styleReader = new Styles();
713✔
445
        foreach ($wbRels->Relationship as $relx) {
713✔
446
            $rel = self::getAttributes($relx);
712✔
447
            $relTarget = (string) $rel['Target'];
712✔
448
            if (str_starts_with($relTarget, '/xl/')) {
712✔
449
                $relTarget = substr($relTarget, 4);
12✔
450
            }
451
            switch ($rel['Type']) {
712✔
452
                case "$xmlNamespaceBase/sheetMetadata":
712✔
453
                    if ($this->fileExistsInArchive($zip, "xl/{$relTarget}")) {
32✔
454
                        $excel->returnArrayAsArray();
32✔
455
                    }
456

457
                    break;
32✔
458
                case "$xmlNamespaceBase/theme":
712✔
459
                    if (!$this->fileExistsInArchive($zip, "xl/{$relTarget}")) {
696✔
460
                        break; // issue3770
3✔
461
                    }
462
                    $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
693✔
463
                    $themeOrderAdditional = count($themeOrderArray);
693✔
464

465
                    $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS);
693✔
466
                    $xmlThemeName = self::getAttributes($xmlTheme);
693✔
467
                    $xmlTheme = $xmlTheme->children($drawingNS);
693✔
468
                    $themeName = (string) $xmlThemeName['name'];
693✔
469

470
                    $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme);
693✔
471
                    $colourSchemeName = (string) $colourScheme['name'];
693✔
472
                    $excel->getTheme()->setThemeColorName($colourSchemeName);
693✔
473
                    $colourScheme = $xmlTheme->themeElements->clrScheme->children($drawingNS);
693✔
474

475
                    $themeColours = [];
693✔
476
                    foreach ($colourScheme as $k => $xmlColour) {
693✔
477
                        $themePos = array_search($k, $themeOrderArray);
693✔
478
                        if ($themePos === false) {
693✔
479
                            $themePos = $themeOrderAdditional++;
693✔
480
                        }
481
                        if (isset($xmlColour->sysClr)) {
693✔
482
                            $xmlColourData = self::getAttributes($xmlColour->sysClr);
673✔
483
                            $themeColours[$themePos] = (string) $xmlColourData['lastClr'];
673✔
484
                            $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['lastClr']);
673✔
485
                        } elseif (isset($xmlColour->srgbClr)) {
693✔
486
                            $xmlColourData = self::getAttributes($xmlColour->srgbClr);
693✔
487
                            $themeColours[$themePos] = (string) $xmlColourData['val'];
693✔
488
                            $excel->getTheme()->setThemeColor($k, (string) $xmlColourData['val']);
693✔
489
                        }
490
                    }
491
                    $theme = new Theme($themeName, $colourSchemeName, $themeColours);
693✔
492
                    $this->styleReader->setTheme($theme);
693✔
493

494
                    $fontScheme = self::getAttributes($xmlTheme->themeElements->fontScheme);
693✔
495
                    $fontSchemeName = (string) $fontScheme['name'];
693✔
496
                    $excel->getTheme()->setThemeFontName($fontSchemeName);
693✔
497
                    $majorFonts = [];
693✔
498
                    $minorFonts = [];
693✔
499
                    $fontScheme = $xmlTheme->themeElements->fontScheme->children($drawingNS);
693✔
500
                    $majorLatin = self::getAttributes($fontScheme->majorFont->latin)['typeface'] ?? '';
693✔
501
                    $majorEastAsian = self::getAttributes($fontScheme->majorFont->ea)['typeface'] ?? '';
693✔
502
                    $majorComplexScript = self::getAttributes($fontScheme->majorFont->cs)['typeface'] ?? '';
693✔
503
                    $minorLatin = self::getAttributes($fontScheme->minorFont->latin)['typeface'] ?? '';
693✔
504
                    $minorEastAsian = self::getAttributes($fontScheme->minorFont->ea)['typeface'] ?? '';
693✔
505
                    $minorComplexScript = self::getAttributes($fontScheme->minorFont->cs)['typeface'] ?? '';
693✔
506

507
                    foreach ($fontScheme->majorFont->font as $xmlFont) {
693✔
508
                        $fontAttributes = self::getAttributes($xmlFont);
671✔
509
                        $script = (string) ($fontAttributes['script'] ?? '');
671✔
510
                        if (!empty($script)) {
671✔
511
                            $majorFonts[$script] = (string) ($fontAttributes['typeface'] ?? '');
671✔
512
                        }
513
                    }
514
                    foreach ($fontScheme->minorFont->font as $xmlFont) {
693✔
515
                        $fontAttributes = self::getAttributes($xmlFont);
671✔
516
                        $script = (string) ($fontAttributes['script'] ?? '');
671✔
517
                        if (!empty($script)) {
671✔
518
                            $minorFonts[$script] = (string) ($fontAttributes['typeface'] ?? '');
671✔
519
                        }
520
                    }
521
                    $excel->getTheme()->setMajorFontValues($majorLatin, $majorEastAsian, $majorComplexScript, $majorFonts);
693✔
522
                    $excel->getTheme()->setMinorFontValues($minorLatin, $minorEastAsian, $minorComplexScript, $minorFonts);
693✔
523

524
                    break;
693✔
525
            }
526
        }
527

528
        $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
713✔
529

530
        $propertyReader = new PropertyReader($this->getSecurityScannerOrThrow(), $excel->getProperties());
713✔
531
        $charts = $chartDetails = [];
713✔
532
        foreach ($rels->Relationship as $relx) {
713✔
533
            $rel = self::getAttributes($relx);
713✔
534
            $relTarget = (string) $rel['Target'];
713✔
535
            // issue 3553
536
            if ($relTarget[0] === '/') {
713✔
537
                $relTarget = substr($relTarget, 1);
7✔
538
            }
539
            $relType = (string) $rel['Type'];
713✔
540
            $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
713✔
541
            switch ($relType) {
542
                case Namespaces::CORE_PROPERTIES:
706✔
543
                    $propertyReader->readCoreProperties($this->getFromZipArchive($zip, $relTarget));
693✔
544

545
                    break;
693✔
546
                case "$xmlNamespaceBase/extended-properties":
713✔
547
                    $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget));
684✔
548

549
                    break;
684✔
550
                case "$xmlNamespaceBase/custom-properties":
713✔
551
                    $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget));
59✔
552

553
                    break;
59✔
554
                    //Ribbon
555
                case Namespaces::EXTENSIBILITY:
713✔
556
                    $customUI = $relTarget;
2✔
557
                    if ($customUI) {
2✔
558
                        $this->readRibbon($excel, $customUI, $zip);
2✔
559
                    }
560

561
                    break;
2✔
562
                case "$xmlNamespaceBase/officeDocument":
713✔
563
                    $dir = dirname($relTarget);
713✔
564

565
                    // Do not specify namespace in next stmt - do it in Xpath
566
                    $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', Namespaces::RELATIONSHIPS);
713✔
567
                    $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS);
713✔
568

569
                    $worksheets = [];
713✔
570
                    $macros = $customUI = null;
713✔
571
                    foreach ($relsWorkbook->Relationship as $elex) {
713✔
572
                        $ele = self::getAttributes($elex);
713✔
573
                        switch ($ele['Type']) {
713✔
574
                            case Namespaces::WORKSHEET:
706✔
575
                            case Namespaces::PURL_WORKSHEET:
706✔
576
                                $worksheets[(string) $ele['Id']] = $ele['Target'];
713✔
577

578
                                break;
713✔
579
                            case Namespaces::CHARTSHEET:
706✔
580
                                if ($this->includeCharts === true) {
2✔
581
                                    $worksheets[(string) $ele['Id']] = $ele['Target'];
1✔
582
                                }
583

584
                                break;
2✔
585
                                // a vbaProject ? (: some macros)
586
                            case Namespaces::VBA:
706✔
587
                                $macros = $ele['Target'];
3✔
588

589
                                break;
3✔
590
                        }
591
                    }
592

593
                    if ($macros !== null) {
713✔
594
                        $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin
3✔
595
                        if (!empty($macrosCode)) {
3✔
596
                            $excel->setMacrosCode($macrosCode);
3✔
597
                            $excel->setHasMacros(true);
3✔
598
                            //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir
599
                            $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin');
3✔
600
                            $excel->setMacrosCertificate($Certificate);
3✔
601
                        }
602
                    }
603

604
                    $relType = "rel:Relationship[@Type='"
713✔
605
                        . "$xmlNamespaceBase/styles"
713✔
606
                        . "']";
713✔
607
                    /** @var ?SimpleXMLElement */
608
                    $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType));
713✔
609

610
                    if ($xpath === null) {
713✔
611
                        $xmlStyles = self::testSimpleXml(null);
1✔
612
                    } else {
613
                        $stylesTarget = (string) $xpath['Target'];
713✔
614
                        $stylesTarget = str_starts_with($stylesTarget, '/') ? substr($stylesTarget, 1) : "$dir/$stylesTarget";
713✔
615
                        $xmlStyles = $this->loadZip($stylesTarget, $mainNS);
713✔
616
                    }
617

618
                    $palette = self::extractPalette($xmlStyles);
713✔
619
                    $this->styleReader->setWorkbookPalette($palette);
713✔
620
                    $fills = self::extractStyles($xmlStyles, 'fills', 'fill');
713✔
621
                    $fonts = self::extractStyles($xmlStyles, 'fonts', 'font');
713✔
622
                    $borders = self::extractStyles($xmlStyles, 'borders', 'border');
713✔
623
                    $xfTags = self::extractStyles($xmlStyles, 'cellXfs', 'xf');
713✔
624
                    $cellXfTags = self::extractStyles($xmlStyles, 'cellStyleXfs', 'xf');
713✔
625

626
                    $styles = [];
713✔
627
                    $cellStyles = [];
713✔
628
                    $numFmts = null;
713✔
629
                    if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) {
713✔
630
                        $numFmts = $xmlStyles->numFmts[0];
250✔
631
                    }
632
                    if (isset($numFmts)) {
713✔
633
                        /** @var SimpleXMLElement $numFmts */
634
                        $numFmts->registerXPathNamespace('sml', $mainNS);
250✔
635
                    }
636
                    $this->styleReader->setNamespace($mainNS);
713✔
637
                    if (!$this->readDataOnly/* && $xmlStyles*/) {
713✔
638
                        foreach ($xfTags as $xfTag) {
710✔
639
                            /** @var SimpleXMLElement $xfTag */
640
                            $xf = self::getAttributes($xfTag);
710✔
641
                            $numFmt = null;
710✔
642

643
                            if ($xf['numFmtId']) {
710✔
644
                                if (isset($numFmts)) {
708✔
645
                                    /** @var ?SimpleXMLElement */
646
                                    $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
250✔
647

648
                                    if (isset($tmpNumFmt['formatCode'])) {
250✔
649
                                        $numFmt = (string) $tmpNumFmt['formatCode'];
249✔
650
                                    }
651
                                }
652

653
                                // We shouldn't override any of the built-in MS Excel values (values below id 164)
654
                                //  But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used
655
                                //  So we make allowance for them rather than lose formatting masks
656
                                if (
657
                                    $numFmt === null
708✔
658
                                    && (int) $xf['numFmtId'] < 164
708✔
659
                                    && NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== ''
708✔
660
                                ) {
661
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
697✔
662
                                }
663
                            }
664
                            $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? '');
710✔
665

666
                            $style = (object) [
710✔
667
                                'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL,
710✔
668
                                'font' => $fonts[(int) ($xf['fontId'])],
710✔
669
                                'fill' => $fills[(int) ($xf['fillId'])],
710✔
670
                                'border' => $borders[(int) ($xf['borderId'])],
710✔
671
                                'alignment' => $xfTag->alignment,
710✔
672
                                'protection' => $xfTag->protection,
710✔
673
                                'quotePrefix' => $quotePrefix,
710✔
674
                            ];
710✔
675
                            $styles[] = $style;
710✔
676

677
                            // add style to cellXf collection
678
                            $objStyle = new Style();
710✔
679
                            $this->styleReader
710✔
680
                                ->readStyle($objStyle, $style);
710✔
681
                            foreach ($this->styleReader->getFontCharsets() as $fontName => $charset) {
710✔
682
                                $excel->addFontCharset($fontName, $charset);
21✔
683
                            }
684
                            if ($addingFirstCellXf) {
710✔
685
                                $excel->removeCellXfByIndex(0); // remove the default style
710✔
686
                                $addingFirstCellXf = false;
710✔
687
                            }
688
                            $excel->addCellXf($objStyle);
710✔
689
                        }
690

691
                        foreach ($cellXfTags as $xfTag) {
710✔
692
                            /** @var SimpleXMLElement $xfTag */
693
                            $xf = self::getAttributes($xfTag);
709✔
694
                            $numFmt = NumberFormat::FORMAT_GENERAL;
709✔
695
                            if ($numFmts && $xf['numFmtId']) {
709✔
696
                                /** @var ?SimpleXMLElement */
697
                                $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
250✔
698
                                if (isset($tmpNumFmt['formatCode'])) {
250✔
699
                                    $numFmt = (string) $tmpNumFmt['formatCode'];
29✔
700
                                } elseif ((int) $xf['numFmtId'] < 165) {
248✔
701
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
248✔
702
                                }
703
                            }
704

705
                            $quotePrefix = (bool) (string) ($xf['quotePrefix'] ?? '');
709✔
706

707
                            $cellStyle = (object) [
709✔
708
                                'numFmt' => $numFmt,
709✔
709
                                'font' => $fonts[(int) ($xf['fontId'])],
709✔
710
                                'fill' => $fills[((int) $xf['fillId'])],
709✔
711
                                'border' => $borders[(int) ($xf['borderId'])],
709✔
712
                                'alignment' => $xfTag->alignment,
709✔
713
                                'protection' => $xfTag->protection,
709✔
714
                                'quotePrefix' => $quotePrefix,
709✔
715
                            ];
709✔
716
                            $cellStyles[] = $cellStyle;
709✔
717

718
                            // add style to cellStyleXf collection
719
                            $objStyle = new Style();
709✔
720
                            $this->styleReader->readStyle($objStyle, $cellStyle);
709✔
721
                            if ($addingFirstCellStyleXf) {
709✔
722
                                $excel->removeCellStyleXfByIndex(0); // remove the default style
709✔
723
                                $addingFirstCellStyleXf = false;
709✔
724
                            }
725
                            $excel->addCellStyleXf($objStyle);
709✔
726
                        }
727
                    }
728
                    $this->styleReader->setStyleXml($xmlStyles);
713✔
729
                    $this->styleReader->setNamespace($mainNS);
713✔
730
                    $this->styleReader->setStyleBaseData($theme, $styles, $cellStyles);
713✔
731
                    $dxfs = $this->styleReader->dxfs($this->readDataOnly);
713✔
732
                    $tableStyles = $this->styleReader->tableStyles($this->readDataOnly);
713✔
733
                    $styles = $this->styleReader->styles();
713✔
734

735
                    // Read content after setting the styles
736
                    $sharedStrings = [];
713✔
737
                    $relType = "rel:Relationship[@Type='"
713✔
738
                        //. Namespaces::SHARED_STRINGS
713✔
739
                        . "$xmlNamespaceBase/sharedStrings"
713✔
740
                        . "']";
713✔
741
                    /** @var ?SimpleXMLElement */
742
                    $xpath = self::getArrayItem($relsWorkbook->xpath($relType));
713✔
743

744
                    if ($xpath) {
713✔
745
                        $sharedStringsTarget = (string) $xpath['Target'];
652✔
746
                        $sharedStringsTarget = str_starts_with($sharedStringsTarget, '/') ? substr($sharedStringsTarget, 1) : "$dir/$sharedStringsTarget";
652✔
747
                        $xmlStrings = $this->loadZip($sharedStringsTarget, $mainNS);
652✔
748
                        if (isset($xmlStrings->si)) {
650✔
749
                            foreach ($xmlStrings->si as $val) {
519✔
750
                                if (isset($val->t)) {
519✔
751
                                    $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
515✔
752
                                } elseif (isset($val->r)) {
45✔
753
                                    $sharedStrings[] = $this->parseRichText($val);
45✔
754
                                } else {
755
                                    $sharedStrings[] = '';
1✔
756
                                }
757
                            }
758
                        }
759
                    }
760

761
                    $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS);
711✔
762
                    $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS);
706✔
763

764
                    // Set base date
765
                    $excel->setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
706✔
766
                    if ($xmlWorkbookNS->workbookPr) {
706✔
767
                        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
697✔
768
                        $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr);
697✔
769
                        if (isset($attrs1904['date1904'])) {
697✔
770
                            if (self::boolean((string) $attrs1904['date1904'])) {
15✔
771
                                Date::setExcelCalendar(Date::CALENDAR_MAC_1904);
4✔
772
                                $excel->setExcelCalendar(Date::CALENDAR_MAC_1904);
4✔
773
                            }
774
                        }
775
                    }
776

777
                    // Set protection
778
                    $this->readProtection($excel, $xmlWorkbook);
706✔
779

780
                    $sheetId = 0; // keep track of new sheet id in final workbook
706✔
781
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
706✔
782
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
706✔
783
                    $mapSheetId = []; // mapping of sheet ids from old to new
706✔
784

785
                    $charts = $chartDetails = [];
706✔
786

787
                    $sheetCreated = false;
706✔
788
                    if ($xmlWorkbookNS->sheets) {
706✔
789
                        foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) {
706✔
790
                            $eleSheetAttr = self::getAttributes($eleSheet);
706✔
791
                            ++$oldSheetId;
706✔
792

793
                            // Check if sheet should be skipped
794
                            if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) {
706✔
795
                                ++$countSkippedSheets;
9✔
796
                                $mapSheetId[$oldSheetId] = null;
9✔
797

798
                                continue;
9✔
799
                            }
800

801
                            $sheetReferenceId = self::getArrayItemString(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id');
702✔
802
                            if (isset($worksheets[$sheetReferenceId]) === false) {
702✔
803
                                ++$countSkippedSheets;
1✔
804
                                $mapSheetId[$oldSheetId] = null;
1✔
805

806
                                continue;
1✔
807
                            }
808
                            // Map old sheet id in original workbook to new sheet id.
809
                            // They will differ if loadSheetsOnly() is being used
810
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
702✔
811

812
                            // Load sheet
813
                            $docSheet = $excel->createSheet();
702✔
814
                            $sheetCreated = true;
702✔
815
                            //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet
816
                            //        references in formula cells... during the load, all formulae should be correct,
817
                            //        and we're simply bringing the worksheet name in line with the formula, not the
818
                            //        reverse
819
                            $docSheet->setTitle((string) $eleSheetAttr['name'], false, false);
702✔
820

821
                            $fileWorksheet = (string) $worksheets[$sheetReferenceId];
702✔
822
                            // issue 3665 adds test for /.
823
                            // This broke XlsxRootZipFilesTest,
824
                            //  but Excel reports an error with that file.
825
                            //  Testing dir for . avoids this problem.
826
                            //  It might be better just to drop the test.
827
                            if ($fileWorksheet[0] == '/' && $dir !== '.') {
702✔
828
                                $fileWorksheet = substr($fileWorksheet, strlen($dir) + 2);
12✔
829
                            }
830
                            $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS);
702✔
831
                            $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS);
702✔
832

833
                            // Shared Formula table is unique to each Worksheet, so we need to reset it here
834
                            $this->sharedFormulae = [];
702✔
835

836
                            if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') {
702✔
837
                                $docSheet->setSheetState((string) $eleSheetAttr['state']);
40✔
838
                            }
839
                            if ($xmlSheetNS) {
702✔
840
                                $xmlSheetMain = $xmlSheetNS->children($mainNS);
702✔
841
                                // Setting Conditional Styles adjusts selected cells, so we need to execute this
842
                                //    before reading the sheet view data to get the actual selected cells
843
                                if (!$this->readDataOnly && ($xmlSheet->conditionalFormatting)) {
702✔
844
                                    (new ConditionalStyles($docSheet, $xmlSheet, $dxfs, $this->styleReader))->load();
224✔
845
                                }
846
                                if (!$this->readDataOnly && $xmlSheet->extLst) {
702✔
847
                                    (new ConditionalStyles($docSheet, $xmlSheet, $dxfs, $this->styleReader))->loadFromExt();
202✔
848
                                }
849
                                if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) {
702✔
850
                                    $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet);
699✔
851
                                    $sheetViews->load();
699✔
852
                                }
853

854
                                $sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheetNS);
702✔
855
                                $sheetViewOptions->load($this->readDataOnly, $this->styleReader);
702✔
856

857
                                (new ColumnAndRowAttributes($docSheet, $xmlSheetNS))
702✔
858
                                    ->load($this->getReadFilter(), $this->readDataOnly, $this->ignoreRowsWithNoCells);
702✔
859
                            }
860

861
                            $holdSelectedCells = $docSheet->getSelectedCells();
702✔
862
                            if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) {
702✔
863
                                $cIndex = 1; // Cell Start from 1
654✔
864
                                foreach ($xmlSheetNS->sheetData->row as $row) {
654✔
865
                                    $rowIndex = 1;
654✔
866
                                    foreach ($row->c as $c) {
654✔
867
                                        $cAttr = self::getAttributes($c);
653✔
868
                                        $r = (string) $cAttr['r'];
653✔
869
                                        if ($r == '') {
653✔
870
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
2✔
871
                                        }
872
                                        $cellDataType = (string) $cAttr['t'];
653✔
873
                                        $originalCellDataTypeNumeric = $cellDataType === '';
653✔
874
                                        $value = null;
653✔
875
                                        $calculatedValue = null;
653✔
876

877
                                        // Read cell?
878
                                        $coordinates = Coordinate::coordinateFromString($r);
653✔
879

880
                                        if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) {
653✔
881
                                            // Normally, just testing for the f attribute should identify this cell as containing a formula
882
                                            // that we need to read, even though it is outside of the filter range, in case it is a shared formula.
883
                                            // But in some cases, this attribute isn't set; so we need to delve a level deeper and look at
884
                                            // whether or not the cell has a child formula element that is shared.
885
                                            if (isset($cAttr->f) || (isset($c->f, $c->f->attributes()['t']) && strtolower((string) $c->f->attributes()['t']) === 'shared')) {
4✔
886
                                                $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError', false);
×
887
                                            }
888
                                            ++$rowIndex;
4✔
889

890
                                            continue;
4✔
891
                                        }
892

893
                                        // Read cell!
894
                                        $useFormula = isset($c->f)
653✔
895
                                            && ((string) $c->f !== '' || (isset($c->f->attributes()['t']) && strtolower((string) $c->f->attributes()['t']) === 'shared'));
653✔
896
                                        switch ($cellDataType) {
897
                                            case DataType::TYPE_STRING:
22✔
898
                                                if ((string) $c->v != '') {
514✔
899
                                                    $value = $sharedStrings[(int) ($c->v)];
514✔
900

901
                                                    if ($value instanceof RichText) {
514✔
902
                                                        $value = clone $value;
37✔
903
                                                    }
904
                                                } else {
905
                                                    $value = '';
17✔
906
                                                }
907

908
                                                break;
514✔
909
                                            case DataType::TYPE_BOOL:
18✔
910
                                                if (!$useFormula) {
22✔
911
                                                    if (isset($c->v)) {
16✔
912
                                                        $value = self::castToBoolean($c);
16✔
913
                                                    } else {
914
                                                        $value = null;
1✔
915
                                                        $cellDataType = DataType::TYPE_NULL;
1✔
916
                                                    }
917
                                                } else {
918
                                                    // Formula
919
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToBoolean');
6✔
920
                                                    self::storeFormulaAttributes($c->f, $docSheet, $r);
6✔
921
                                                }
922

923
                                                break;
22✔
924
                                            case DataType::TYPE_STRING2:
18✔
925
                                                if ($useFormula) {
225✔
926
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToString');
223✔
927
                                                    self::storeFormulaAttributes($c->f, $docSheet, $r);
223✔
928
                                                } else {
929
                                                    $value = self::castToString($c);
3✔
930
                                                }
931

932
                                                break;
225✔
933
                                            case DataType::TYPE_INLINE:
18✔
934
                                                if ($useFormula) {
15✔
935
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError');
×
936
                                                    self::storeFormulaAttributes($c->f, $docSheet, $r);
×
937
                                                } else {
938
                                                    $value = $this->parseRichText($c->is);
15✔
939
                                                }
940

941
                                                break;
15✔
942
                                            case DataType::TYPE_ERROR:
18✔
943
                                                if (!$useFormula) {
189✔
944
                                                    $value = self::castToError($c);
×
945
                                                } else {
946
                                                    // Formula
947
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToError');
189✔
948
                                                    $eattr = $c->attributes();
189✔
949
                                                    if (isset($eattr['vm'])) {
189✔
950
                                                        if ($calculatedValue === ExcelError::VALUE()) {
1✔
951
                                                            $calculatedValue = ExcelError::SPILL();
1✔
952
                                                        }
953
                                                    }
954
                                                }
955

956
                                                break;
189✔
957
                                            default:
958
                                                if (!$useFormula) {
540✔
959
                                                    $value = self::castToString($c);
531✔
960
                                                    if (is_numeric($value)) {
531✔
961
                                                        $value += 0;
505✔
962
                                                        $cellDataType = DataType::TYPE_NUMERIC;
505✔
963
                                                    }
964
                                                } else {
965
                                                    // Formula
966
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, 'castToString');
349✔
967
                                                    if (is_numeric($calculatedValue)) {
349✔
968
                                                        $calculatedValue += 0;
346✔
969
                                                    }
970
                                                    self::storeFormulaAttributes($c->f, $docSheet, $r);
349✔
971
                                                }
972

973
                                                break;
540✔
974
                                        }
975

976
                                        // read empty cells or the cells are not empty
977
                                        if ($this->readEmptyCells || ($value !== null && $value !== '')) {
653✔
978
                                            // Rich text?
979
                                            if ($value instanceof RichText && $this->readDataOnly) {
653✔
980
                                                $value = $value->getPlainText();
1✔
981
                                            }
982

983
                                            $cell = $docSheet->getCell($r);
653✔
984
                                            // Assign value
985
                                            if ($cellDataType != '') {
653✔
986
                                                // it is possible, that datatype is numeric but with an empty string, which result in an error
987
                                                if ($cellDataType === DataType::TYPE_NUMERIC && ($value === '' || $value === null)) {
645✔
988
                                                    $cellDataType = DataType::TYPE_NULL;
1✔
989
                                                }
990
                                                if ($cellDataType !== DataType::TYPE_NULL) {
645✔
991
                                                    $cell->setValueExplicit($value, $cellDataType);
645✔
992
                                                }
993
                                            } else {
994
                                                $cell->setValue($value);
297✔
995
                                            }
996
                                            if ($calculatedValue !== null) {
653✔
997
                                                $cell->setCalculatedValue($calculatedValue, $originalCellDataTypeNumeric);
364✔
998
                                            }
999

1000
                                            // Style information?
1001
                                            if (!$this->readDataOnly) {
653✔
1002
                                                $cAttrS = (int) ($cAttr['s'] ?? 0);
650✔
1003
                                                // no style index means 0, it seems
1004
                                                $cAttrS = isset($styles[$cAttrS]) ? $cAttrS : 0;
650✔
1005
                                                $cell->setXfIndex($cAttrS);
650✔
1006
                                                // issue 3495
1007
                                                if ($cellDataType === DataType::TYPE_FORMULA && $styles[$cAttrS]->quotePrefix === true) { //* @phpstan-ignore-line
650✔
1008
                                                    $holdSelected = $docSheet->getSelectedCells();
2✔
1009
                                                    $cell->getStyle()->setQuotePrefix(false);
2✔
1010
                                                    $docSheet->setSelectedCells($holdSelected);
2✔
1011
                                                }
1012
                                            }
1013
                                        }
1014
                                        ++$rowIndex;
653✔
1015
                                    }
1016
                                    ++$cIndex;
654✔
1017
                                }
1018
                            }
1019
                            $docSheet->setSelectedCells($holdSelectedCells);
702✔
1020
                            if (!$this->readDataOnly && $xmlSheetNS && $xmlSheetNS->ignoredErrors) {
702✔
1021
                                foreach ($xmlSheetNS->ignoredErrors->ignoredError as $ignoredError) {
4✔
1022
                                    $this->processIgnoredErrors($ignoredError, $docSheet);
4✔
1023
                                }
1024
                            }
1025

1026
                            if (!$this->readDataOnly && $xmlSheetNS && $xmlSheetNS->sheetProtection) {
702✔
1027
                                $protAttr = $xmlSheetNS->sheetProtection->attributes() ?? [];
70✔
1028
                                foreach ($protAttr as $key => $value) {
70✔
1029
                                    $method = 'set' . ucfirst($key);
70✔
1030
                                    $docSheet->getProtection()->$method(self::boolean((string) $value));
70✔
1031
                                }
1032
                            }
1033

1034
                            if ($xmlSheet) {
702✔
1035
                                $this->readSheetProtection($docSheet, $xmlSheet);
692✔
1036
                            }
1037

1038
                            if ($this->readDataOnly === false) {
702✔
1039
                                $this->readAutoFilter($xmlSheetNS, $docSheet);
699✔
1040
                                $this->readBackgroundImage($xmlSheetNS, $docSheet, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels');
699✔
1041
                            }
1042

1043
                            $this->readTables($xmlSheetNS, $docSheet, $dir, $fileWorksheet, $zip, $mainNS, $tableStyles, $dxfs);
702✔
1044

1045
                            if ($xmlSheetNS && $xmlSheetNS->mergeCells && $xmlSheetNS->mergeCells->mergeCell && !$this->readDataOnly) {
702✔
1046
                                foreach ($xmlSheetNS->mergeCells->mergeCell as $mergeCellx) {
67✔
1047
                                    $mergeCell = $mergeCellx->attributes();
67✔
1048
                                    $mergeRef = (string) ($mergeCell['ref'] ?? '');
67✔
1049
                                    if (str_contains($mergeRef, ':')) {
67✔
1050
                                        $docSheet->mergeCells($mergeRef, Worksheet::MERGE_CELL_CONTENT_HIDE);
67✔
1051
                                    }
1052
                                }
1053
                            }
1054

1055
                            if ($xmlSheet && !$this->readDataOnly) {
702✔
1056
                                $unparsedLoadedData = (new PageSetup($docSheet, $xmlSheet))->load($unparsedLoadedData);
689✔
1057
                            }
1058

1059
                            if (isset($xmlSheet->extLst->ext)) {
702✔
1060
                                foreach ($xmlSheet->extLst->ext as $extlst) {
202✔
1061
                                    $extAttrs = $extlst->attributes() ?? [];
202✔
1062
                                    $extUri = (string) ($extAttrs['uri'] ?? '');
202✔
1063
                                    if ($extUri !== '{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}') {
202✔
1064
                                        continue;
196✔
1065
                                    }
1066
                                    // Create dataValidations node if does not exists, maybe is better inside the foreach ?
1067
                                    if (!$xmlSheet->dataValidations) {
6✔
1068
                                        $xmlSheet->addChild('dataValidations');
1✔
1069
                                    }
1070

1071
                                    foreach ($extlst->children(Namespaces::DATA_VALIDATIONS1)->dataValidations->dataValidation as $item) {
6✔
1072
                                        $item = self::testSimpleXml($item);
6✔
1073
                                        $node = self::testSimpleXml($xmlSheet->dataValidations)->addChild('dataValidation');
6✔
1074
                                        foreach ($item->attributes() ?? [] as $attr) {
6✔
1075
                                            $node->addAttribute($attr->getName(), $attr);
6✔
1076
                                        }
1077
                                        $node->addAttribute('sqref', $item->children(Namespaces::DATA_VALIDATIONS2)->sqref);
6✔
1078
                                        if (isset($item->formula1)) {
6✔
1079
                                            $childNode = $node->addChild('formula1');
6✔
1080
                                            if ($childNode !== null) { // null should never happen
6✔
1081
                                                // see https://github.com/phpstan/phpstan/issues/8236
1082
                                                // resolved with Phpstan 2.1.23
1083
                                                $childNode[0] = (string) $item->formula1->children(Namespaces::DATA_VALIDATIONS2)->f;
6✔
1084
                                            }
1085
                                        }
1086
                                    }
1087
                                }
1088
                            }
1089

1090
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
702✔
1091
                                (new DataValidations($docSheet, $xmlSheet))->load();
22✔
1092
                            }
1093

1094
                            // unparsed sheet AlternateContent
1095
                            if ($xmlSheet && !$this->readDataOnly) {
702✔
1096
                                $mc = $xmlSheet->children(Namespaces::COMPATIBILITY);
689✔
1097
                                if ($mc->AlternateContent) {
689✔
1098
                                    foreach ($mc->AlternateContent as $alternateContent) {
4✔
1099
                                        $alternateContent = self::testSimpleXml($alternateContent);
4✔
1100
                                        /** @var mixed[][][][] $unparsedLoadedData */
1101
                                        $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
4✔
1102
                                    }
1103
                                }
1104
                            }
1105

1106
                            // Add hyperlinks
1107
                            if (!$this->readDataOnly) {
702✔
1108
                                $hyperlinkReader = new Hyperlinks($docSheet);
699✔
1109
                                // Locate hyperlink relations
1110
                                $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
699✔
1111
                                if ($zip->locateName($relationsFileName) !== false) {
699✔
1112
                                    $relsWorksheet = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS);
575✔
1113
                                    $hyperlinkReader->readHyperlinks($relsWorksheet);
575✔
1114
                                }
1115

1116
                                // Loop through hyperlinks
1117
                                if ($xmlSheetNS && $xmlSheetNS->children($mainNS)->hyperlinks) {
699✔
1118
                                    $hyperlinkReader->setHyperlinks($xmlSheetNS->children($mainNS)->hyperlinks);
19✔
1119
                                }
1120
                            }
1121

1122
                            // Add comments
1123
                            $comments = [];
702✔
1124
                            $vmlComments = [];
702✔
1125
                            if (!$this->readDataOnly) {
702✔
1126
                                // Locate comment relations
1127
                                $commentRelations = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
699✔
1128
                                if ($zip->locateName($commentRelations) !== false) {
699✔
1129
                                    $relsWorksheet = $this->loadZip($commentRelations, Namespaces::RELATIONSHIPS);
575✔
1130
                                    foreach ($relsWorksheet->Relationship as $elex) {
575✔
1131
                                        $ele = self::getAttributes($elex);
404✔
1132
                                        if ($ele['Type'] == Namespaces::COMMENTS) {
404✔
1133
                                            $comments[(string) $ele['Id']] = (string) $ele['Target'];
34✔
1134
                                        }
1135
                                        if ($ele['Type'] == Namespaces::VML) {
404✔
1136
                                            $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
38✔
1137
                                        }
1138
                                    }
1139
                                }
1140

1141
                                // Loop through comments
1142
                                foreach ($comments as $relName => $relPath) {
699✔
1143
                                    // Load comments file
1144
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
34✔
1145
                                    // okay to ignore namespace - using xpath
1146
                                    $commentsFile = $this->loadZip($relPath, '');
34✔
1147

1148
                                    // Utility variables
1149
                                    $authors = [];
34✔
1150
                                    $commentsFile->registerXpathNamespace('com', $mainNS);
34✔
1151
                                    $authorPath = self::xpathNoFalse($commentsFile, 'com:authors/com:author');
34✔
1152
                                    foreach ($authorPath as $author) {
34✔
1153
                                        /** @var SimpleXMLElement $author */
1154
                                        $authors[] = (string) $author;
34✔
1155
                                    }
1156

1157
                                    // Loop through contents
1158
                                    $contentPath = self::xpathNoFalse($commentsFile, 'com:commentList/com:comment');
34✔
1159
                                    foreach ($contentPath as $comment) {
34✔
1160
                                        /** @var SimpleXMLElement $comment */
1161
                                        $commentx = $comment->attributes();
34✔
1162
                                        /** @var array{ref: scalar, authorId?: scalar}  $commentx */
1163
                                        $commentModel = $docSheet->getComment((string) $commentx['ref']);
34✔
1164
                                        if (isset($commentx['authorId'])) {
34✔
1165
                                            $commentModel->setAuthor($authors[(int) $commentx['authorId']]);
34✔
1166
                                        }
1167
                                        /** @var SimpleXMLElement */
1168
                                        $temp = $comment->children($mainNS);
34✔
1169
                                        $commentModel->setText($this->parseRichText($temp->text));
34✔
1170
                                    }
1171
                                }
1172

1173
                                // later we will remove from it real vmlComments
1174
                                $unparsedVmlDrawings = $vmlComments;
699✔
1175
                                $vmlDrawingContents = [];
699✔
1176

1177
                                // Loop through VML comments
1178
                                foreach ($vmlComments as $relName => $relPath) {
699✔
1179
                                    // Load VML comments file
1180
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
38✔
1181

1182
                                    try {
1183
                                        // no namespace okay - processed with Xpath
1184
                                        $vmlCommentsFile = $this->loadZip($relPath, '', true);
38✔
1185
                                        $vmlCommentsFile->registerXPathNamespace('v', Namespaces::URN_VML);
38✔
1186
                                    } catch (Throwable) {
×
1187
                                        //Ignore unparsable vmlDrawings. Later they will be moved from $unparsedVmlDrawings to $unparsedLoadedData
1188
                                        continue;
×
1189
                                    }
1190

1191
                                    // Locate VML drawings image relations
1192
                                    $drowingImages = [];
38✔
1193
                                    $VMLDrawingsRelations = dirname($relPath) . '/_rels/' . basename($relPath) . '.rels';
38✔
1194
                                    $vmlDrawingContents[$relName] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $relPath));
38✔
1195
                                    if ($zip->locateName($VMLDrawingsRelations) !== false) {
38✔
1196
                                        $relsVMLDrawing = $this->loadZip($VMLDrawingsRelations, Namespaces::RELATIONSHIPS);
18✔
1197
                                        foreach ($relsVMLDrawing->Relationship as $elex) {
18✔
1198
                                            $ele = self::getAttributes($elex);
9✔
1199
                                            if ($ele['Type'] == Namespaces::IMAGE) {
9✔
1200
                                                $drowingImages[(string) $ele['Id']] = (string) $ele['Target'];
9✔
1201
                                            }
1202
                                        }
1203
                                    }
1204

1205
                                    $shapes = self::xpathNoFalse($vmlCommentsFile, '//v:shape');
38✔
1206
                                    foreach ($shapes as $shape) {
38✔
1207
                                        /** @var SimpleXMLElement $shape */
1208
                                        $shape->registerXPathNamespace('v', Namespaces::URN_VML);
37✔
1209

1210
                                        if (isset($shape['style'])) {
37✔
1211
                                            $style = (string) $shape['style'];
37✔
1212
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
37✔
1213
                                            $column = null;
37✔
1214
                                            $row = null;
37✔
1215
                                            $textHAlign = null;
37✔
1216
                                            $fillImageRelId = null;
37✔
1217
                                            $fillImageTitle = '';
37✔
1218

1219
                                            $clientData = $shape->xpath('.//x:ClientData');
37✔
1220
                                            $textboxDirection = '';
37✔
1221
                                            $textboxPath = $shape->xpath('.//v:textbox');
37✔
1222
                                            $textbox = (string) ($textboxPath[0]['style'] ?? '');
37✔
1223
                                            if (preg_match('/rtl/i', $textbox) === 1) {
37✔
1224
                                                $textboxDirection = Comment::TEXTBOX_DIRECTION_RTL;
1✔
1225
                                            } elseif (preg_match('/ltr/i', $textbox) === 1) {
36✔
1226
                                                $textboxDirection = Comment::TEXTBOX_DIRECTION_LTR;
1✔
1227
                                            }
1228
                                            if (is_array($clientData) && !empty($clientData)) {
37✔
1229
                                                /** @var SimpleXMLElement */
1230
                                                $clientData = $clientData[0];
35✔
1231

1232
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
35✔
1233
                                                    $temp = $clientData->xpath('.//x:Row');
33✔
1234
                                                    if (is_array($temp)) {
33✔
1235
                                                        $row = $temp[0];
33✔
1236
                                                    }
1237

1238
                                                    $temp = $clientData->xpath('.//x:Column');
33✔
1239
                                                    if (is_array($temp)) {
33✔
1240
                                                        $column = $temp[0];
33✔
1241
                                                    }
1242
                                                    $temp = $clientData->xpath('.//x:TextHAlign');
33✔
1243
                                                    if (!empty($temp)) {
33✔
1244
                                                        $textHAlign = strtolower($temp[0]);
2✔
1245
                                                    }
1246
                                                }
1247
                                            }
1248
                                            $rowx = (string) $row;
37✔
1249
                                            $colx = (string) $column;
37✔
1250
                                            if (is_numeric($rowx) && is_numeric($colx) && $textHAlign !== null) {
37✔
1251
                                                $docSheet->getComment([1 + (int) $colx, 1 + (int) $rowx], false)->setAlignment((string) $textHAlign);
2✔
1252
                                            }
1253
                                            if (is_numeric($rowx) && is_numeric($colx) && $textboxDirection !== '') {
37✔
1254
                                                $docSheet->getComment([1 + (int) $colx, 1 + (int) $rowx], false)->setTextboxDirection($textboxDirection);
2✔
1255
                                            }
1256

1257
                                            $fillImageRelNode = $shape->xpath('.//v:fill/@o:relid');
37✔
1258
                                            if (is_array($fillImageRelNode) && !empty($fillImageRelNode)) {
37✔
1259
                                                /** @var SimpleXMLElement */
1260
                                                $fillImageRelNode = $fillImageRelNode[0];
5✔
1261

1262
                                                if (isset($fillImageRelNode['relid'])) {
5✔
1263
                                                    $fillImageRelId = (string) $fillImageRelNode['relid'];
5✔
1264
                                                }
1265
                                            }
1266

1267
                                            $fillImageTitleNode = $shape->xpath('.//v:fill/@o:title');
37✔
1268
                                            if (is_array($fillImageTitleNode) && !empty($fillImageTitleNode)) {
37✔
1269
                                                /** @var SimpleXMLElement */
1270
                                                $fillImageTitleNode = $fillImageTitleNode[0];
3✔
1271

1272
                                                if (isset($fillImageTitleNode['title'])) {
3✔
1273
                                                    $fillImageTitle = (string) $fillImageTitleNode['title'];
3✔
1274
                                                }
1275
                                            }
1276

1277
                                            if (($column !== null) && ($row !== null)) {
37✔
1278
                                                // Set comment properties
1279
                                                $comment = $docSheet->getComment([(int) $column + 1, (int) $row + 1]);
33✔
1280
                                                $comment->getFillColor()->setRGB($fillColor);
33✔
1281
                                                if (isset($fillImageRelId, $drowingImages[$fillImageRelId])) {
33✔
1282
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
5✔
1283
                                                    $objDrawing->setName($fillImageTitle);
5✔
1284
                                                    $imagePath = str_replace(['../', '/xl/'], 'xl/', $drowingImages[$fillImageRelId]);
5✔
1285
                                                    $objDrawing->setPath(
5✔
1286
                                                        'zip://' . File::realpath($filename) . '#' . $imagePath,
5✔
1287
                                                        true,
5✔
1288
                                                        $zip
5✔
1289
                                                    );
5✔
1290
                                                    $comment->setBackgroundImage($objDrawing);
5✔
1291
                                                }
1292

1293
                                                // Parse style
1294
                                                $styleArray = explode(';', str_replace(' ', '', $style));
33✔
1295
                                                foreach ($styleArray as $stylePair) {
33✔
1296
                                                    $stylePair = explode(':', $stylePair);
33✔
1297

1298
                                                    if ($stylePair[0] == 'margin-left') {
33✔
1299
                                                        $comment->setMarginLeft($stylePair[1]);
29✔
1300
                                                    }
1301
                                                    if ($stylePair[0] == 'margin-top') {
33✔
1302
                                                        $comment->setMarginTop($stylePair[1]);
29✔
1303
                                                    }
1304
                                                    if ($stylePair[0] == 'width') {
33✔
1305
                                                        $comment->setWidth($stylePair[1]);
29✔
1306
                                                    }
1307
                                                    if ($stylePair[0] == 'height') {
33✔
1308
                                                        $comment->setHeight($stylePair[1]);
29✔
1309
                                                    }
1310
                                                    if ($stylePair[0] == 'visibility') {
33✔
1311
                                                        $comment->setVisible($stylePair[1] == 'visible');
33✔
1312
                                                    }
1313
                                                }
1314

1315
                                                unset($unparsedVmlDrawings[$relName]);
33✔
1316
                                            }
1317
                                        }
1318
                                    }
1319
                                }
1320

1321
                                // unparsed vmlDrawing
1322
                                if ($unparsedVmlDrawings) {
699✔
1323
                                    foreach ($unparsedVmlDrawings as $rId => $relPath) {
7✔
1324
                                        /** @var mixed[][][] $unparsedLoadedData */
1325
                                        $rId = substr($rId, 3); // rIdXXX
7✔
1326
                                        /** @var mixed[][] */
1327
                                        $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
7✔
1328
                                        $unparsedVmlDrawing[$rId] = [];
7✔
1329
                                        $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
7✔
1330
                                        $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
7✔
1331
                                        $unparsedVmlDrawing[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
7✔
1332
                                        unset($unparsedVmlDrawing);
7✔
1333
                                    }
1334
                                }
1335

1336
                                // Header/footer images
1337
                                if ($xmlSheetNS && $xmlSheetNS->legacyDrawingHF) {
699✔
1338
                                    $vmlHfRid = '';
3✔
1339
                                    $vmlHfRidAttr = $xmlSheetNS->legacyDrawingHF->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT);
3✔
1340
                                    if ($vmlHfRidAttr !== null && isset($vmlHfRidAttr['id'])) {
3✔
1341
                                        $vmlHfRid = (string) $vmlHfRidAttr['id'][0];
3✔
1342
                                    }
1343
                                    if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') !== false) {
3✔
1344
                                        $relsWorksheet = $this->loadZipNoNamespace(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels', Namespaces::RELATIONSHIPS);
3✔
1345
                                        $vmlRelationship = '';
3✔
1346

1347
                                        foreach ($relsWorksheet->Relationship as $ele) {
3✔
1348
                                            if ((string) $ele['Type'] == Namespaces::VML && (string) $ele['Id'] === $vmlHfRid) {
3✔
1349
                                                $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
3✔
1350

1351
                                                break;
3✔
1352
                                            }
1353
                                        }
1354

1355
                                        if ($vmlRelationship != '') {
3✔
1356
                                            // Fetch linked images
1357
                                            $relsVML = $this->loadZipNoNamespace(dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels', Namespaces::RELATIONSHIPS);
3✔
1358
                                            $drawings = [];
3✔
1359
                                            if (isset($relsVML->Relationship)) {
3✔
1360
                                                foreach ($relsVML->Relationship as $ele) {
3✔
1361
                                                    if ($ele['Type'] == Namespaces::IMAGE) {
3✔
1362
                                                        $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
3✔
1363
                                                    }
1364
                                                }
1365
                                            }
1366
                                            // Fetch VML document
1367
                                            $vmlDrawing = $this->loadZipNoNamespace($vmlRelationship, '');
3✔
1368
                                            $vmlDrawing->registerXPathNamespace('v', Namespaces::URN_VML);
3✔
1369

1370
                                            $hfImages = [];
3✔
1371

1372
                                            $shapes = self::xpathNoFalse($vmlDrawing, '//v:shape');
3✔
1373
                                            foreach ($shapes as $idx => $shape) {
3✔
1374
                                                /** @var SimpleXMLElement $shape */
1375
                                                $shape->registerXPathNamespace('v', Namespaces::URN_VML);
3✔
1376
                                                $imageData = $shape->xpath('//v:imagedata');
3✔
1377

1378
                                                if (empty($imageData)) {
3✔
1379
                                                    continue;
×
1380
                                                }
1381

1382
                                                $imageData = $imageData[$idx];
3✔
1383

1384
                                                $imageData = self::getAttributes($imageData, Namespaces::URN_MSOFFICE);
3✔
1385
                                                /** @var array{width: int, height: int, margin-left?: int, margin-top: int} */
1386
                                                $style = self::toCSSArray((string) $shape['style']);
3✔
1387

1388
                                                if (array_key_exists((string) $imageData['relid'], $drawings)) {
3✔
1389
                                                    $shapeId = (string) $shape['id'];
3✔
1390
                                                    $hfImages[$shapeId] = new HeaderFooterDrawing();
3✔
1391
                                                    if (isset($imageData['title'])) {
3✔
1392
                                                        $hfImages[$shapeId]->setName((string) $imageData['title']);
3✔
1393
                                                    }
1394

1395
                                                    $hfImages[$shapeId]->setPath('zip://' . File::realpath($filename) . '#' . $drawings[(string) $imageData['relid']], false, $zip);
3✔
1396
                                                    $hfImages[$shapeId]->setResizeProportional(false);
3✔
1397
                                                    $hfImages[$shapeId]->setWidth($style['width']);
3✔
1398
                                                    $hfImages[$shapeId]->setHeight($style['height']);
3✔
1399
                                                    if (isset($style['margin-left'])) {
3✔
1400
                                                        $hfImages[$shapeId]->setOffsetX($style['margin-left']);
3✔
1401
                                                    }
1402
                                                    $hfImages[$shapeId]->setOffsetY($style['margin-top']);
3✔
1403
                                                    $hfImages[$shapeId]->setResizeProportional(true);
3✔
1404
                                                }
1405
                                            }
1406

1407
                                            $docSheet->getHeaderFooter()->setImages($hfImages);
3✔
1408
                                        }
1409
                                    }
1410
                                }
1411
                            }
1412

1413
                            // TODO: Autoshapes from twoCellAnchors!
1414
                            $drawingFilename = dirname("$dir/$fileWorksheet")
702✔
1415
                                . '/_rels/'
702✔
1416
                                . basename($fileWorksheet)
702✔
1417
                                . '.rels';
702✔
1418
                            if (str_starts_with($drawingFilename, 'xl//xl/')) {
702✔
1419
                                $drawingFilename = substr($drawingFilename, 4);
×
1420
                            }
1421
                            if (str_starts_with($drawingFilename, '/xl//xl/')) {
702✔
1422
                                $drawingFilename = substr($drawingFilename, 5);
×
1423
                            }
1424
                            if ($zip->locateName($drawingFilename) !== false) {
702✔
1425
                                $relsWorksheet = $this->loadZip($drawingFilename, Namespaces::RELATIONSHIPS);
578✔
1426
                                $drawings = [];
578✔
1427
                                foreach ($relsWorksheet->Relationship as $elex) {
578✔
1428
                                    $ele = self::getAttributes($elex);
406✔
1429
                                    if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
406✔
1430
                                        $eleTarget = (string) $ele['Target'];
135✔
1431
                                        if (str_starts_with($eleTarget, '/xl/')) {
135✔
1432
                                            $drawings[(string) $ele['Id']] = substr($eleTarget, 1);
4✔
1433
                                        } else {
1434
                                            $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
132✔
1435
                                        }
1436
                                    }
1437
                                }
1438

1439
                                if ($xmlSheetNS->drawing && !$this->readDataOnly) {
578✔
1440
                                    $unparsedDrawings = [];
134✔
1441
                                    $fileDrawing = null;
134✔
1442
                                    foreach ($xmlSheetNS->drawing as $drawing) {
134✔
1443
                                        $drawingRelId = self::getArrayItemString(self::getAttributes($drawing, $xmlNamespaceBase), 'id');
134✔
1444
                                        $fileDrawing = $drawings[$drawingRelId];
134✔
1445
                                        $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels';
134✔
1446
                                        $relsDrawing = $this->loadZip($drawingFilename, Namespaces::RELATIONSHIPS);
134✔
1447

1448
                                        $images = [];
134✔
1449
                                        $hyperlinks = [];
134✔
1450
                                        if ($relsDrawing && $relsDrawing->Relationship) {
134✔
1451
                                            foreach ($relsDrawing->Relationship as $elex) {
113✔
1452
                                                $ele = self::getAttributes($elex);
113✔
1453
                                                $eleType = (string) $ele['Type'];
113✔
1454
                                                if ($eleType === Namespaces::HYPERLINK) {
113✔
1455
                                                    $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
3✔
1456
                                                }
1457
                                                if ($eleType === "$xmlNamespaceBase/image") {
113✔
1458
                                                    $eleTarget = (string) $ele['Target'];
63✔
1459
                                                    if (str_starts_with($eleTarget, '/xl/')) {
63✔
1460
                                                        $eleTarget = substr($eleTarget, 1);
1✔
1461
                                                        $images[(string) $ele['Id']] = $eleTarget;
1✔
1462
                                                    } else {
1463
                                                        $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $eleTarget);
62✔
1464
                                                    }
1465
                                                } elseif ($eleType === "$xmlNamespaceBase/chart") {
74✔
1466
                                                    if ($this->includeCharts) {
70✔
1467
                                                        $eleTarget = (string) $ele['Target'];
69✔
1468
                                                        if (str_starts_with($eleTarget, '/xl/')) {
69✔
1469
                                                            $index = substr($eleTarget, 1);
3✔
1470
                                                        } else {
1471
                                                            $index = self::dirAdd($fileDrawing, $eleTarget);
67✔
1472
                                                        }
1473
                                                        $charts[$index] = [
69✔
1474
                                                            'id' => (string) $ele['Id'],
69✔
1475
                                                            'sheet' => $docSheet->getTitle(),
69✔
1476
                                                        ];
69✔
1477
                                                    }
1478
                                                }
1479
                                            }
1480
                                        }
1481

1482
                                        $xmlDrawing = $this->loadZipNoNamespace($fileDrawing, '');
134✔
1483
                                        $xmlDrawingChildren = $xmlDrawing->children(Namespaces::SPREADSHEET_DRAWING);
134✔
1484

1485
                                        if ($xmlDrawingChildren->oneCellAnchor) {
134✔
1486
                                            foreach ($xmlDrawingChildren->oneCellAnchor as $oneCellAnchor) {
23✔
1487
                                                $oneCellAnchor = self::testSimpleXml($oneCellAnchor);
23✔
1488
                                                if ($oneCellAnchor->pic->blipFill) {
23✔
1489
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
16✔
1490
                                                    $blip = $oneCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip;
16✔
1491
                                                    if (isset($blip, $blip->alphaModFix)) {
16✔
1492
                                                        $temp = (string) $blip->alphaModFix->attributes()->amt;
1✔
1493
                                                        if (is_numeric($temp)) {
1✔
1494
                                                            $objDrawing->setOpacity((int) $temp);
1✔
1495
                                                        }
1496
                                                    }
1497
                                                    $xfrm = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm;
16✔
1498
                                                    $outerShdw = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw;
16✔
1499

1500
                                                    $objDrawing->setName(self::getArrayItemString(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'name'));
16✔
1501
                                                    $objDrawing->setDescription(self::getArrayItemString(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'descr'));
16✔
1502
                                                    $embedImageKey = self::getArrayItemString(
16✔
1503
                                                        self::getAttributes($blip, $xmlNamespaceBase),
16✔
1504
                                                        'embed'
16✔
1505
                                                    );
16✔
1506
                                                    if (isset($images[$embedImageKey])) {
16✔
1507
                                                        $objDrawing->setPath(
16✔
1508
                                                            'zip://' . File::realpath($filename) . '#'
16✔
1509
                                                            . $images[$embedImageKey],
16✔
1510
                                                            false,
16✔
1511
                                                            $zip
16✔
1512
                                                        );
16✔
1513
                                                    } else {
1514
                                                        $linkImageKey = self::getArrayItemString(
×
1515
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
×
1516
                                                            'link'
×
1517
                                                        );
×
1518
                                                        if (isset($images[$linkImageKey])) {
×
1519
                                                            $url = str_replace('xl/drawings/', '', $images[$linkImageKey]);
×
1520
                                                            $objDrawing->setPath($url, false, allowExternal: $this->allowExternalImages);
×
1521
                                                        }
1522
                                                        if ($objDrawing->getPath() === '') {
×
1523
                                                            continue;
×
1524
                                                        }
1525
                                                    }
1526
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
16✔
1527

1528
                                                    $objDrawing->setOffsetX((int) Drawing::EMUToPixels($oneCellAnchor->from->colOff));
16✔
1529
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
16✔
1530
                                                    $objDrawing->setResizeProportional(false);
16✔
1531
                                                    $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cx')));
16✔
1532
                                                    $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cy')));
16✔
1533
                                                    if ($xfrm) {
16✔
1534
                                                        $objDrawing->setRotation((int) Drawing::angleToDegrees(self::getArrayItemIntOrSxml(self::getAttributes($xfrm), 'rot')));
16✔
1535
                                                        $objDrawing->setFlipVertical((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipV'));
16✔
1536
                                                        $objDrawing->setFlipHorizontal((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipH'));
16✔
1537
                                                    }
1538
                                                    if ($outerShdw) {
16✔
1539
                                                        $shadow = $objDrawing->getShadow();
3✔
1540
                                                        $shadow->setVisible(true);
3✔
1541
                                                        $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'blurRad')));
3✔
1542
                                                        $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'dist')));
3✔
1543
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'dir')));
3✔
1544
                                                        $shadow->setAlignment(self::getArrayItemString(self::getAttributes($outerShdw), 'algn'));
3✔
1545
                                                        $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr;
3✔
1546
                                                        $shadow->getColor()->setRGB(self::getArrayItemString(self::getAttributes($clr), 'val'));
3✔
1547
                                                        if ($clr->alpha) {
3✔
1548
                                                            $alpha = StringHelper::convertToString(self::getArrayItem(self::getAttributes($clr->alpha), 'val'));
3✔
1549
                                                            if (is_numeric($alpha)) {
3✔
1550
                                                                $alpha = (int) ($alpha / 1000);
3✔
1551
                                                                $shadow->setAlpha($alpha);
3✔
1552
                                                            }
1553
                                                        }
1554
                                                    }
1555

1556
                                                    $this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks);
16✔
1557

1558
                                                    $objDrawing->setWorksheet($docSheet);
16✔
1559
                                                } elseif ($this->includeCharts && $oneCellAnchor->graphicFrame) {
7✔
1560
                                                    // Exported XLSX from Google Sheets positions charts with a oneCellAnchor
1561
                                                    $coordinates = Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1);
4✔
1562
                                                    $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff);
4✔
1563
                                                    $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
4✔
1564
                                                    $width = Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cx'));
4✔
1565
                                                    $height = Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cy'));
4✔
1566

1567
                                                    $graphic = $oneCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic;
4✔
1568
                                                    $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart;
4✔
1569
                                                    $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase);
4✔
1570

1571
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
4✔
1572
                                                        'fromCoordinate' => $coordinates,
4✔
1573
                                                        'fromOffsetX' => $offsetX,
4✔
1574
                                                        'fromOffsetY' => $offsetY,
4✔
1575
                                                        'width' => $width,
4✔
1576
                                                        'height' => $height,
4✔
1577
                                                        'worksheetTitle' => $docSheet->getTitle(),
4✔
1578
                                                        'oneCellAnchor' => true,
4✔
1579
                                                    ];
4✔
1580
                                                }
1581
                                            }
1582
                                        }
1583
                                        if ($xmlDrawingChildren->twoCellAnchor) {
134✔
1584
                                            foreach ($xmlDrawingChildren->twoCellAnchor as $twoCellAnchor) {
96✔
1585
                                                $twoCellAnchor = self::testSimpleXml($twoCellAnchor);
96✔
1586
                                                if ($twoCellAnchor->pic->blipFill) {
96✔
1587
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
49✔
1588
                                                    $blip = $twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip;
49✔
1589
                                                    if (isset($blip, $blip->alphaModFix)) {
49✔
1590
                                                        $temp = (string) $blip->alphaModFix->attributes()->amt;
3✔
1591
                                                        if (is_numeric($temp)) {
3✔
1592
                                                            $objDrawing->setOpacity((int) $temp);
3✔
1593
                                                        }
1594
                                                    }
1595
                                                    if (isset($twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->srcRect)) {
49✔
1596
                                                        $objDrawing->setSrcRect($twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->srcRect->attributes());
11✔
1597
                                                    }
1598
                                                    $xfrm = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm;
49✔
1599
                                                    $outerShdw = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw;
49✔
1600
                                                    $editAs = $twoCellAnchor->attributes();
49✔
1601
                                                    if (isset($editAs, $editAs['editAs'])) {
49✔
1602
                                                        $objDrawing->setEditAs($editAs['editAs']);
44✔
1603
                                                    }
1604
                                                    $objDrawing->setName((string) self::getArrayItemString(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'name'));
49✔
1605
                                                    $objDrawing->setDescription(self::getArrayItemString(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'descr'));
49✔
1606
                                                    $embedImageKey = self::getArrayItemString(
49✔
1607
                                                        self::getAttributes($blip, $xmlNamespaceBase),
49✔
1608
                                                        'embed'
49✔
1609
                                                    );
49✔
1610
                                                    if (isset($images[$embedImageKey])) {
49✔
1611
                                                        $objDrawing->setPath(
42✔
1612
                                                            'zip://' . File::realpath($filename) . '#'
42✔
1613
                                                            . $images[$embedImageKey],
42✔
1614
                                                            false,
42✔
1615
                                                            $zip
42✔
1616
                                                        );
42✔
1617
                                                    } else {
1618
                                                        $linkImageKey = self::getArrayItemString(
7✔
1619
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
7✔
1620
                                                            'link'
7✔
1621
                                                        );
7✔
1622
                                                        if (isset($images[$linkImageKey])) {
7✔
1623
                                                            $url = str_replace('xl/drawings/', '', $images[$linkImageKey]);
7✔
1624
                                                            $objDrawing->setPath($url, false, allowExternal: $this->allowExternalImages);
7✔
1625
                                                        }
1626
                                                        if ($objDrawing->getPath() === '') {
6✔
1627
                                                            continue;
4✔
1628
                                                        }
1629
                                                    }
1630
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1));
44✔
1631

1632
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff));
44✔
1633
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
44✔
1634

1635
                                                    $objDrawing->setCoordinates2(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1));
44✔
1636

1637
                                                    $objDrawing->setOffsetX2(Drawing::EMUToPixels($twoCellAnchor->to->colOff));
44✔
1638
                                                    $objDrawing->setOffsetY2(Drawing::EMUToPixels($twoCellAnchor->to->rowOff));
44✔
1639

1640
                                                    $objDrawing->setResizeProportional(false);
44✔
1641

1642
                                                    if ($xfrm) {
44✔
1643
                                                        $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($xfrm->ext), 'cx')));
44✔
1644
                                                        $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($xfrm->ext), 'cy')));
44✔
1645
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItemIntOrSxml(self::getAttributes($xfrm), 'rot')));
44✔
1646
                                                        $objDrawing->setFlipVertical((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipV'));
44✔
1647
                                                        $objDrawing->setFlipHorizontal((bool) self::getArrayItem(self::getAttributes($xfrm), 'flipH'));
44✔
1648
                                                    }
1649
                                                    if ($outerShdw) {
44✔
1650
                                                        $shadow = $objDrawing->getShadow();
1✔
1651
                                                        $shadow->setVisible(true);
1✔
1652
                                                        $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'blurRad')));
1✔
1653
                                                        $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'dist')));
1✔
1654
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItemIntOrSxml(self::getAttributes($outerShdw), 'dir')));
1✔
1655
                                                        $shadow->setAlignment(self::getArrayItemString(self::getAttributes($outerShdw), 'algn'));
1✔
1656
                                                        $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr;
1✔
1657
                                                        $shadow->getColor()->setRGB(self::getArrayItemString(self::getAttributes($clr), 'val'));
1✔
1658
                                                        if ($clr->alpha) {
1✔
1659
                                                            $alpha = StringHelper::convertToString(self::getArrayItem(self::getAttributes($clr->alpha), 'val'));
1✔
1660
                                                            if (is_numeric($alpha)) {
1✔
1661
                                                                $alpha = (int) ($alpha / 1000);
1✔
1662
                                                                $shadow->setAlpha($alpha);
1✔
1663
                                                            }
1664
                                                        }
1665
                                                    }
1666

1667
                                                    $this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks);
44✔
1668

1669
                                                    $objDrawing->setWorksheet($docSheet);
44✔
1670
                                                } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
71✔
1671
                                                    $fromCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
65✔
1672
                                                    $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff);
65✔
1673
                                                    $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
65✔
1674
                                                    $toCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
65✔
1675
                                                    $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff);
65✔
1676
                                                    $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
65✔
1677
                                                    $graphic = $twoCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic;
65✔
1678
                                                    $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart;
65✔
1679
                                                    $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase);
65✔
1680

1681
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
65✔
1682
                                                        'fromCoordinate' => $fromCoordinate,
65✔
1683
                                                        'fromOffsetX' => $fromOffsetX,
65✔
1684
                                                        'fromOffsetY' => $fromOffsetY,
65✔
1685
                                                        'toCoordinate' => $toCoordinate,
65✔
1686
                                                        'toOffsetX' => $toOffsetX,
65✔
1687
                                                        'toOffsetY' => $toOffsetY,
65✔
1688
                                                        'worksheetTitle' => $docSheet->getTitle(),
65✔
1689
                                                    ];
65✔
1690
                                                }
1691
                                            }
1692
                                        }
1693
                                        if ($xmlDrawingChildren->absoluteAnchor) {
133✔
1694
                                            foreach ($xmlDrawingChildren->absoluteAnchor as $absoluteAnchor) {
1✔
1695
                                                if (($this->includeCharts) && ($absoluteAnchor->graphicFrame)) {
1✔
1696
                                                    $graphic = $absoluteAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic;
1✔
1697
                                                    $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart;
1✔
1698
                                                    $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase);
1✔
1699
                                                    $width = Drawing::EMUToPixels((int) self::getArrayItemString(self::getAttributes($absoluteAnchor->ext), 'cx')[0]);
1✔
1700
                                                    $height = Drawing::EMUToPixels((int) self::getArrayItemString(self::getAttributes($absoluteAnchor->ext), 'cy')[0]);
1✔
1701

1702
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1✔
1703
                                                        'fromCoordinate' => 'A1',
1✔
1704
                                                        'fromOffsetX' => 0,
1✔
1705
                                                        'fromOffsetY' => 0,
1✔
1706
                                                        'width' => $width,
1✔
1707
                                                        'height' => $height,
1✔
1708
                                                        'worksheetTitle' => $docSheet->getTitle(),
1✔
1709
                                                    ];
1✔
1710
                                                }
1711
                                            }
1712
                                        }
1713
                                        if (empty($relsDrawing) && $xmlDrawing->count() == 0) {
133✔
1714
                                            // Save Drawing without rels and children as unparsed
1715
                                            $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML();
26✔
1716
                                        }
1717
                                    }
1718

1719
                                    // store original rId of drawing files
1720
                                    /** @var mixed[][][][] $unparsedLoadedData */
1721
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = [];
133✔
1722
                                    foreach ($relsWorksheet->Relationship as $elex) {
133✔
1723
                                        $ele = self::getAttributes($elex);
133✔
1724
                                        if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
133✔
1725
                                            $drawingRelId = (string) $ele['Id'];
133✔
1726
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = $drawingRelId;
133✔
1727
                                            if (isset($unparsedDrawings[$drawingRelId])) {
133✔
1728
                                                $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['Drawings'][$drawingRelId] = $unparsedDrawings[$drawingRelId];
26✔
1729
                                            }
1730
                                        }
1731
                                    }
1732
                                    if ($xmlSheet->legacyDrawing && !$this->readDataOnly) {
133✔
1733
                                        foreach ($xmlSheet->legacyDrawing as $drawing) {
13✔
1734
                                            $drawingRelId = self::getArrayItemString(self::getAttributes($drawing, $xmlNamespaceBase), 'id');
13✔
1735
                                            if (isset($vmlDrawingContents[$drawingRelId])) {
13✔
1736
                                                if (self::onlyNoteVml($vmlDrawingContents[$drawingRelId]) === false) {
13✔
1737
                                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['legacyDrawing'] = $vmlDrawingContents[$drawingRelId];
5✔
1738
                                                }
1739
                                            }
1740
                                        }
1741
                                    }
1742

1743
                                    // unparsed drawing AlternateContent
1744
                                    $xmlAltDrawing = $this->loadZip((string) $fileDrawing, Namespaces::COMPATIBILITY);
133✔
1745

1746
                                    if ($xmlAltDrawing->AlternateContent) {
133✔
1747
                                        foreach ($xmlAltDrawing->AlternateContent as $alternateContent) {
4✔
1748
                                            $alternateContent = self::testSimpleXml($alternateContent);
4✔
1749
                                            /** @var mixed[][][][][] $unparsedLoadedData */
1750
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML();
4✔
1751
                                        }
1752
                                    }
1753
                                }
1754
                            }
1755

1756
                            /** @var mixed[][][][] $unparsedLoadedData */
1757
                            $this->readFormControlProperties($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
701✔
1758
                            $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
701✔
1759

1760
                            // Loop through definedNames
1761
                            if ($xmlWorkbook->definedNames) {
701✔
1762
                                foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
384✔
1763
                                    // Extract range
1764
                                    $extractedRange = (string) $definedName;
108✔
1765
                                    if (($spos = strpos($extractedRange, '!')) !== false) {
108✔
1766
                                        $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
89✔
1767
                                    } else {
1768
                                        $extractedRange = str_replace('$', '', $extractedRange);
34✔
1769
                                    }
1770

1771
                                    // Valid range?
1772
                                    if ($extractedRange == '') {
108✔
1773
                                        continue;
×
1774
                                    }
1775

1776
                                    // Some definedNames are only applicable if we are on the same sheet...
1777
                                    if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) {
108✔
1778
                                        // Switch on type
1779
                                        switch ((string) $definedName['name']) {
50✔
1780
                                            case '_xlnm._FilterDatabase':
50✔
1781
                                                if ((string) $definedName['hidden'] !== '1') {
20✔
1782
                                                    $extractedRange = explode(',', $extractedRange);
×
1783
                                                    foreach ($extractedRange as $range) {
×
1784
                                                        $autoFilterRange = $range;
×
1785
                                                        if (str_contains($autoFilterRange, ':')) {
×
1786
                                                            $docSheet->getAutoFilter()->setRange($autoFilterRange);
×
1787
                                                        }
1788
                                                    }
1789
                                                }
1790

1791
                                                break;
20✔
1792
                                            case '_xlnm.Print_Titles':
30✔
1793
                                                // Split $extractedRange
1794
                                                $extractedRange = explode(',', $extractedRange);
3✔
1795

1796
                                                // Set print titles
1797
                                                foreach ($extractedRange as $range) {
3✔
1798
                                                    $matches = [];
3✔
1799
                                                    $range = str_replace('$', '', $range);
3✔
1800

1801
                                                    // check for repeating columns, e g. 'A:A' or 'A:D'
1802
                                                    if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
3✔
1803
                                                        $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]);
×
1804
                                                    } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
3✔
1805
                                                        // check for repeating rows, e.g. '1:1' or '1:5'
1806
                                                        $docSheet->getPageSetup()->setRowsToRepeatAtTop([(int) $matches[1], (int) $matches[2]]);
3✔
1807
                                                    }
1808
                                                }
1809

1810
                                                break;
3✔
1811
                                            case '_xlnm.Print_Area':
29✔
1812
                                                $rangeSets = preg_split("/('?(?:.*?)'?(?:![A-Z0-9]+:[A-Z0-9]+)),?/", $extractedRange, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) ?: [];
11✔
1813
                                                $newRangeSets = [];
11✔
1814
                                                foreach ($rangeSets as $rangeSet) {
11✔
1815
                                                    [, $rangeSet] = Worksheet::extractSheetTitle($rangeSet, true);
11✔
1816
                                                    if (empty($rangeSet)) {
11✔
1817
                                                        continue;
×
1818
                                                    }
1819
                                                    if (!str_contains($rangeSet, ':')) {
11✔
1820
                                                        $rangeSet = $rangeSet . ':' . $rangeSet;
×
1821
                                                    }
1822
                                                    $newRangeSets[] = str_replace('$', '', $rangeSet);
11✔
1823
                                                }
1824
                                                if (count($newRangeSets) > 0) {
11✔
1825
                                                    $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
11✔
1826
                                                }
1827

1828
                                                break;
11✔
1829
                                            default:
1830
                                                break;
19✔
1831
                                        }
1832
                                    }
1833
                                }
1834
                            }
1835

1836
                            // Next sheet id
1837
                            ++$sheetId;
701✔
1838
                        }
1839

1840
                        // Loop through definedNames
1841
                        if ($xmlWorkbook->definedNames) {
705✔
1842
                            foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
384✔
1843
                                // Extract range
1844
                                $extractedRange = (string) $definedName;
108✔
1845

1846
                                // Valid range?
1847
                                if ($extractedRange == '') {
108✔
1848
                                    continue;
×
1849
                                }
1850

1851
                                // Some definedNames are only applicable if we are on the same sheet...
1852
                                if ((string) $definedName['localSheetId'] != '') {
108✔
1853
                                    // Local defined name
1854
                                    // Switch on type
1855
                                    switch ((string) $definedName['name']) {
50✔
1856
                                        case '_xlnm._FilterDatabase':
50✔
1857
                                        case '_xlnm.Print_Titles':
30✔
1858
                                        case '_xlnm.Print_Area':
29✔
1859
                                            break;
33✔
1860
                                        default:
1861
                                            if ($mapSheetId[(int) $definedName['localSheetId']] !== null) {
19✔
1862
                                                $range = Worksheet::extractSheetTitle($extractedRange, true);
19✔
1863
                                                $scope = $excel->getSheet($mapSheetId[(int) $definedName['localSheetId']]);
19✔
1864
                                                if (str_contains((string) $definedName, '!')) {
19✔
1865
                                                    $range[0] = str_replace("''", "'", $range[0]);
19✔
1866
                                                    $range[0] = str_replace("'", '', $range[0]);
19✔
1867
                                                    if ($worksheet = $excel->getSheetByName($range[0])) {
19✔
1868
                                                        $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $worksheet, $extractedRange, true, $scope));
19✔
1869
                                                    } else {
1870
                                                        $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true, $scope));
14✔
1871
                                                    }
1872
                                                } else {
1873
                                                    $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true));
×
1874
                                                }
1875
                                            }
1876

1877
                                            break;
19✔
1878
                                    }
1879
                                } elseif (!isset($definedName['localSheetId'])) {
78✔
1880
                                    // "Global" definedNames
1881
                                    $locatedSheet = null;
78✔
1882
                                    if (str_contains((string) $definedName, '!')) {
78✔
1883
                                        // Modify range, and extract the first worksheet reference
1884
                                        // Need to split on a comma or a space if not in quotes, and extract the first part.
1885
                                        $definedNameValueParts = preg_split("/[ ,](?=([^']*'[^']*')*[^']*$)/miuU", $extractedRange);
58✔
1886
                                        if (is_array($definedNameValueParts)) {
58✔
1887
                                            // Extract sheet name
1888
                                            [$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true, true);
58✔
1889

1890
                                            // Locate sheet
1891
                                            $locatedSheet = $excel->getSheetByName("$extractedSheetName");
58✔
1892
                                        }
1893
                                    }
1894

1895
                                    if ($locatedSheet === null && !DefinedName::testIfFormula($extractedRange)) {
78✔
1896
                                        $extractedRange = '#REF!';
2✔
1897
                                    }
1898
                                    $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $locatedSheet, $extractedRange, false));
78✔
1899
                                }
1900
                            }
1901
                        }
1902
                    }
1903
                    if ($this->createBlankSheetIfNoneRead && !$sheetCreated) {
705✔
1904
                        $excel->createSheet();
2✔
1905
                    }
1906

1907
                    (new WorkbookView($excel))->viewSettings($xmlWorkbook, $mainNS, $mapSheetId, $this->readDataOnly);
705✔
1908

1909
                    break;
703✔
1910
            }
1911
        }
1912

1913
        if (!$this->readDataOnly) {
703✔
1914
            $contentTypes = $this->loadZip('[Content_Types].xml');
700✔
1915

1916
            // Default content types
1917
            foreach ($contentTypes->Default as $contentType) {
700✔
1918
                switch ($contentType['ContentType']) {
698✔
1919
                    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings':
698✔
1920
                        $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType'];
294✔
1921

1922
                        break;
294✔
1923
                }
1924
            }
1925

1926
            // Override content types
1927
            foreach ($contentTypes->Override as $contentType) {
700✔
1928
                switch ($contentType['ContentType']) {
699✔
1929
                    case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
699✔
1930
                        if ($this->includeCharts) {
71✔
1931
                            $chartEntryRef = ltrim((string) $contentType['PartName'], '/');
69✔
1932
                            $chartElements = $this->loadZip($chartEntryRef);
69✔
1933
                            $chartReader = new Chart($chartNS, $drawingNS);
69✔
1934
                            $objChart = $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml'));
69✔
1935
                            if (isset($charts[$chartEntryRef])) {
69✔
1936
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
69✔
1937
                                if (isset($chartDetails[$chartPositionRef]) && $excel->getSheetByName($charts[$chartEntryRef]['sheet']) !== null) {
69✔
1938
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
69✔
1939
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
69✔
1940
                                    // For oneCellAnchor or absoluteAnchor positioned charts,
1941
                                    //     toCoordinate is not in the data. Does it need to be calculated?
1942
                                    if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) {
69✔
1943
                                        // twoCellAnchor
1944
                                        $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
65✔
1945
                                        $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
65✔
1946
                                    } else {
1947
                                        // oneCellAnchor or absoluteAnchor (e.g. Chart sheet)
1948
                                        $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
5✔
1949
                                        $objChart->setBottomRightPosition('', $chartDetails[$chartPositionRef]['width'], $chartDetails[$chartPositionRef]['height']);
5✔
1950
                                        if (array_key_exists('oneCellAnchor', $chartDetails[$chartPositionRef])) {
5✔
1951
                                            $objChart->setOneCellAnchor($chartDetails[$chartPositionRef]['oneCellAnchor']);
4✔
1952
                                        }
1953
                                    }
1954
                                }
1955
                            }
1956
                        }
1957

1958
                        break;
71✔
1959

1960
                        // unparsed
1961
                    case 'application/vnd.ms-excel.controlproperties+xml':
699✔
1962
                        $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
4✔
1963

1964
                        break;
4✔
1965
                }
1966
            }
1967
        }
1968

1969
        /** @var array<array<array<array<string>|string>>> $unparsedLoadedData */
1970
        $excel->setUnparsedLoadedData($unparsedLoadedData);
703✔
1971

1972
        $zip->close();
703✔
1973

1974
        return $excel;
703✔
1975
    }
1976

1977
    private function parseRichText(?SimpleXMLElement $is): RichText
81✔
1978
    {
1979
        $value = new RichText();
81✔
1980

1981
        if (isset($is->t)) {
81✔
1982
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
22✔
1983
        } elseif ($is !== null) {
61✔
1984
            if (is_object($is->r)) {
61✔
1985
                foreach ($is->r as $run) {
61✔
1986
                    if (!isset($run->rPr)) {
58✔
1987
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
41✔
1988
                    } else {
1989
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
54✔
1990
                        $objFont = $objText->getFont() ?? new StyleFont();
54✔
1991

1992
                        if (isset($run->rPr->rFont)) {
54✔
1993
                            $attr = $run->rPr->rFont->attributes();
54✔
1994
                            if (isset($attr['val'])) {
54✔
1995
                                $objFont->setName((string) $attr['val']);
54✔
1996
                            }
1997
                        }
1998
                        if (isset($run->rPr->sz)) {
54✔
1999
                            $attr = $run->rPr->sz->attributes();
54✔
2000
                            if (isset($attr['val'])) {
54✔
2001
                                $objFont->setSize((float) $attr['val']);
54✔
2002
                            }
2003
                        }
2004
                        if (isset($run->rPr->color)) {
54✔
2005
                            $objFont->setColor(new Color($this->styleReader->readColor($run->rPr->color)));
52✔
2006
                        }
2007
                        if (isset($run->rPr->b)) {
54✔
2008
                            $attr = $run->rPr->b->attributes();
47✔
2009
                            if (
2010
                                (isset($attr['val']) && self::boolean((string) $attr['val']))
47✔
2011
                                || (!isset($attr['val']))
47✔
2012
                            ) {
2013
                                $objFont->setBold(true);
44✔
2014
                            }
2015
                        }
2016
                        if (isset($run->rPr->i)) {
54✔
2017
                            $attr = $run->rPr->i->attributes();
17✔
2018
                            if (
2019
                                (isset($attr['val']) && self::boolean((string) $attr['val']))
17✔
2020
                                || (!isset($attr['val']))
17✔
2021
                            ) {
2022
                                $objFont->setItalic(true);
9✔
2023
                            }
2024
                        }
2025
                        if (isset($run->rPr->vertAlign)) {
54✔
2026
                            $attr = $run->rPr->vertAlign->attributes();
×
2027
                            if (isset($attr['val'])) {
×
2028
                                $vertAlign = strtolower((string) $attr['val']);
×
2029
                                if ($vertAlign == 'superscript') {
×
2030
                                    $objFont->setSuperscript(true);
×
2031
                                }
2032
                                if ($vertAlign == 'subscript') {
×
2033
                                    $objFont->setSubscript(true);
×
2034
                                }
2035
                            }
2036
                        }
2037
                        if (isset($run->rPr->u)) {
54✔
2038
                            $attr = $run->rPr->u->attributes();
13✔
2039
                            if (!isset($attr['val'])) {
13✔
2040
                                $objFont->setUnderline(StyleFont::UNDERLINE_SINGLE);
1✔
2041
                            } else {
2042
                                $objFont->setUnderline((string) $attr['val']);
12✔
2043
                            }
2044
                        }
2045
                        if (isset($run->rPr->strike)) {
54✔
2046
                            $attr = $run->rPr->strike->attributes();
12✔
2047
                            if (
2048
                                (isset($attr['val']) && self::boolean((string) $attr['val']))
12✔
2049
                                || (!isset($attr['val']))
12✔
2050
                            ) {
2051
                                $objFont->setStrikethrough(true);
×
2052
                            }
2053
                        }
2054
                    }
2055
                }
2056
            }
2057
        }
2058

2059
        return $value;
81✔
2060
    }
2061

2062
    private function readRibbon(Spreadsheet $excel, string $customUITarget, ZipArchive $zip): void
2✔
2063
    {
2064
        $baseDir = dirname($customUITarget);
2✔
2065
        $nameCustomUI = basename($customUITarget);
2✔
2066
        // get the xml file (ribbon)
2067
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
2✔
2068
        $customUIImagesNames = [];
2✔
2069
        $customUIImagesBinaries = [];
2✔
2070
        // something like customUI/_rels/customUI.xml.rels
2071
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
2✔
2072
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
2✔
2073
        if ($dataRels) {
2✔
2074
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
2075
            $UIRels = simplexml_load_string(
×
2076
                $this->getSecurityScannerOrThrow()
×
2077
                    ->scan($dataRels),
×
2078
                SimpleXMLElement::class,
×
2079
                $this->parseHuge ? LIBXML_PARSEHUGE : 0
×
2080
            );
×
2081
            if (false !== $UIRels) {
×
2082
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
2083
                foreach ($UIRels->Relationship as $ele) {
×
2084
                    if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/image') {
×
2085
                        // an image ?
2086
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
×
2087
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
×
2088
                    }
2089
                }
2090
            }
2091
        }
2092
        if ($localRibbon) {
2✔
2093
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
2✔
2094
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2✔
2095
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
×
2096
            } else {
2097
                $excel->setRibbonBinObjects(null, null);
2✔
2098
            }
2099
        } else {
2100
            $excel->setRibbonXMLData(null, null);
×
2101
            $excel->setRibbonBinObjects(null, null);
×
2102
        }
2103
    }
2104

2105
    /** @param null|bool|mixed[]|SimpleXMLElement $array */
2106
    private static function getArrayItem(null|array|bool|SimpleXMLElement $array, int|string $key = 0): mixed
729✔
2107
    {
2108
        return ($array === null || is_bool($array)) ? null : ($array[$key] ?? null);
729✔
2109
    }
2110

2111
    /** @param null|bool|mixed[]|SimpleXMLElement $array */
2112
    private static function getArrayItemString(null|array|bool|SimpleXMLElement $array, int|string $key = 0): string
718✔
2113
    {
2114
        $retVal = self::getArrayItem($array, $key);
718✔
2115

2116
        return StringHelper::convertToString($retVal, false);
718✔
2117
    }
2118

2119
    /** @param null|bool|mixed[]|SimpleXMLElement $array */
2120
    private static function getArrayItemIntOrSxml(null|array|bool|SimpleXMLElement $array, int|string $key = 0): int|SimpleXMLElement
61✔
2121
    {
2122
        $retVal = self::getArrayItem($array, $key);
61✔
2123

2124
        return (is_int($retVal) || $retVal instanceof SimpleXMLElement) ? $retVal : 0;
61✔
2125
    }
2126

2127
    private static function dirAdd(null|SimpleXMLElement|string $base, null|SimpleXMLElement|string $add): string
377✔
2128
    {
2129
        $base = (string) $base;
377✔
2130
        $add = (string) $add;
377✔
2131

2132
        return (string) preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
377✔
2133
    }
2134

2135
    /** @return mixed[] */
2136
    private static function toCSSArray(string $style): array
3✔
2137
    {
2138
        $style = self::stripWhiteSpaceFromStyleString($style);
3✔
2139

2140
        $temp = explode(';', $style);
3✔
2141
        $style = [];
3✔
2142
        foreach ($temp as $item) {
3✔
2143
            $item = explode(':', $item);
3✔
2144

2145
            if (str_contains($item[1], 'px')) {
3✔
2146
                $item[1] = str_replace('px', '', $item[1]);
2✔
2147
            }
2148
            if (str_contains($item[1], 'pt')) {
3✔
2149
                $item[1] = str_replace('pt', '', $item[1]);
2✔
2150
                $item[1] = (string) Font::fontSizeToPixels((int) $item[1]);
2✔
2151
            }
2152
            if (str_contains($item[1], 'in')) {
3✔
2153
                $item[1] = str_replace('in', '', $item[1]);
×
2154
                $item[1] = (string) Font::inchSizeToPixels((int) $item[1]);
×
2155
            }
2156
            if (str_contains($item[1], 'cm')) {
3✔
2157
                $item[1] = str_replace('cm', '', $item[1]);
×
2158
                $item[1] = (string) Font::centimeterSizeToPixels((int) $item[1]);
×
2159
            }
2160

2161
            $style[$item[0]] = $item[1];
3✔
2162
        }
2163

2164
        return $style;
3✔
2165
    }
2166

2167
    public static function stripWhiteSpaceFromStyleString(string $string): string
6✔
2168
    {
2169
        return trim(str_replace(["\r", "\n", ' '], '', $string), ';');
6✔
2170
    }
2171

2172
    private static function boolean(string $value): bool
93✔
2173
    {
2174
        if (is_numeric($value)) {
93✔
2175
            return (bool) $value;
72✔
2176
        }
2177

2178
        return $value === 'true' || $value === 'TRUE';
34✔
2179
    }
2180

2181
    /** @param string[] $hyperlinks */
2182
    private function readHyperLinkDrawing(\PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing, SimpleXMLElement $cellAnchor, array $hyperlinks): void
58✔
2183
    {
2184
        $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick;
58✔
2185

2186
        if ($hlinkClick->count() === 0) {
58✔
2187
            return;
56✔
2188
        }
2189

2190
        $hlinkId = (string) self::getAttributes($hlinkClick, Namespaces::SCHEMA_OFFICE_DOCUMENT)['id'];
2✔
2191
        $hyperlink = new Hyperlink(
2✔
2192
            $hyperlinks[$hlinkId],
2✔
2193
            self::getArrayItemString(self::getAttributes($cellAnchor->pic->nvPicPr->cNvPr), 'name')
2✔
2194
        );
2✔
2195
        $objDrawing->setHyperlink($hyperlink);
2✔
2196
    }
2197

2198
    private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook): void
706✔
2199
    {
2200
        if (!$xmlWorkbook->workbookProtection) {
706✔
2201
            return;
686✔
2202
        }
2203

2204
        $excel->getSecurity()->setLockRevision(self::getLockValue($xmlWorkbook->workbookProtection, 'lockRevision'));
24✔
2205
        $excel->getSecurity()->setLockStructure(self::getLockValue($xmlWorkbook->workbookProtection, 'lockStructure'));
24✔
2206
        $excel->getSecurity()->setLockWindows(self::getLockValue($xmlWorkbook->workbookProtection, 'lockWindows'));
24✔
2207

2208
        if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
24✔
2209
            $excel->getSecurity()->setRevisionsPassword(
1✔
2210
                (string) $xmlWorkbook->workbookProtection['revisionsPassword'],
1✔
2211
                true
1✔
2212
            );
1✔
2213
        }
2214

2215
        if ($xmlWorkbook->workbookProtection['workbookPassword']) {
24✔
2216
            $excel->getSecurity()->setWorkbookPassword(
2✔
2217
                (string) $xmlWorkbook->workbookProtection['workbookPassword'],
2✔
2218
                true
2✔
2219
            );
2✔
2220
        }
2221
    }
2222

2223
    private static function getLockValue(SimpleXMLElement $protection, string $key): ?bool
24✔
2224
    {
2225
        $returnValue = null;
24✔
2226
        $protectKey = $protection[$key];
24✔
2227
        if (!empty($protectKey)) {
24✔
2228
            $protectKey = (string) $protectKey;
10✔
2229
            $returnValue = $protectKey !== 'false' && (bool) $protectKey;
10✔
2230
        }
2231

2232
        return $returnValue;
24✔
2233
    }
2234

2235
    /** @param mixed[][][][] $unparsedLoadedData */
2236
    private function readFormControlProperties(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void
701✔
2237
    {
2238
        $zip = $this->zip;
701✔
2239
        if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) {
701✔
2240
            return;
347✔
2241
        }
2242

2243
        $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
577✔
2244
        $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS);
577✔
2245
        $ctrlProps = [];
577✔
2246
        foreach ($relsWorksheet->Relationship as $ele) {
577✔
2247
            if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/ctrlProp') {
400✔
2248
                $ctrlProps[(string) $ele['Id']] = $ele;
4✔
2249
            }
2250
        }
2251

2252
        /** @var mixed[][] */
2253
        $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
577✔
2254
        foreach ($ctrlProps as $rId => $ctrlProp) {
577✔
2255
            $rId = substr($rId, 3); // rIdXXX
4✔
2256
            $unparsedCtrlProps[$rId] = [];
4✔
2257
            $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
4✔
2258
            $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
4✔
2259
            $unparsedCtrlProps[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
4✔
2260
        }
2261
        unset($unparsedCtrlProps);
577✔
2262
    }
2263

2264
    /** @param mixed[][][][] $unparsedLoadedData */
2265
    private function readPrinterSettings(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void
701✔
2266
    {
2267
        if ($this->readDataOnly) {
701✔
2268
            return;
3✔
2269
        }
2270
        $zip = $this->zip;
698✔
2271
        if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) {
698✔
2272
            return;
346✔
2273
        }
2274

2275
        $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
574✔
2276
        $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS);
574✔
2277
        $sheetPrinterSettings = [];
574✔
2278
        foreach ($relsWorksheet->Relationship as $ele) {
574✔
2279
            if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/printerSettings') {
398✔
2280
                $sheetPrinterSettings[(string) $ele['Id']] = $ele;
284✔
2281
            }
2282
        }
2283

2284
        /** @var mixed[][] */
2285
        $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
574✔
2286
        foreach ($sheetPrinterSettings as $rId => $printerSettings) {
574✔
2287
            $rId = substr($rId, 3); // rIdXXX
284✔
2288
            if (!str_ends_with($rId, 'ps')) {
284✔
2289
                $rId = $rId . 'ps'; // rIdXXX, add 'ps' suffix to avoid identical resource identifier collision with unparsed vmlDrawing
284✔
2290
            }
2291
            $unparsedPrinterSettings[$rId] = [];
284✔
2292
            $target = (string) str_replace('/xl/', '../', (string) $printerSettings['Target']);
284✔
2293
            $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $target);
284✔
2294
            $unparsedPrinterSettings[$rId]['relFilePath'] = $target;
284✔
2295
            $unparsedPrinterSettings[$rId]['content'] = $this->getSecurityScannerOrThrow()->scan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
284✔
2296
        }
2297
        unset($unparsedPrinterSettings);
574✔
2298
    }
2299

2300
    /** @return array{string, string} */
2301
    private function getWorkbookBaseName(): array
717✔
2302
    {
2303
        $workbookBasename = '';
717✔
2304
        $xmlNamespaceBase = '';
717✔
2305

2306
        // check if it is an OOXML archive
2307
        $rels = $this->loadZip(self::INITIAL_FILE);
717✔
2308
        foreach ($rels->children(Namespaces::RELATIONSHIPS)->Relationship as $rel) {
717✔
2309
            $rel = self::getAttributes($rel);
717✔
2310
            $type = (string) $rel['Type'];
717✔
2311
            switch ($type) {
2312
                case Namespaces::OFFICE_DOCUMENT:
709✔
2313
                case Namespaces::PURL_OFFICE_DOCUMENT:
695✔
2314
                    $basename = basename((string) $rel['Target']);
717✔
2315
                    $xmlNamespaceBase = dirname($type);
717✔
2316
                    if (preg_match('/workbook.*\.xml/', $basename)) {
717✔
2317
                        $workbookBasename = $basename;
717✔
2318
                    }
2319

2320
                    break;
717✔
2321
            }
2322
        }
2323

2324
        return [$workbookBasename, $xmlNamespaceBase];
717✔
2325
    }
2326

2327
    private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void
692✔
2328
    {
2329
        if ($this->readDataOnly || !$xmlSheet->sheetProtection) {
692✔
2330
            return;
634✔
2331
        }
2332

2333
        $algorithmName = (string) $xmlSheet->sheetProtection['algorithmName'];
69✔
2334
        $protection = $docSheet->getProtection();
69✔
2335
        $protection->setAlgorithm($algorithmName);
69✔
2336

2337
        if ($algorithmName) {
69✔
2338
            $protection->setPassword((string) $xmlSheet->sheetProtection['hashValue'], true);
2✔
2339
            $protection->setSalt((string) $xmlSheet->sheetProtection['saltValue']);
2✔
2340
            $protection->setSpinCount((int) $xmlSheet->sheetProtection['spinCount']);
2✔
2341
        } else {
2342
            $protection->setPassword((string) $xmlSheet->sheetProtection['password'], true);
68✔
2343
        }
2344

2345
        if ($xmlSheet->protectedRanges->protectedRange) {
69✔
2346
            foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
4✔
2347
                $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true, (string) $protectedRange['name'], (string) $protectedRange['securityDescriptor']);
4✔
2348
            }
2349
        }
2350
    }
2351

2352
    private function readAutoFilter(
699✔
2353
        SimpleXMLElement $xmlSheet,
2354
        Worksheet $docSheet
2355
    ): void {
2356
        if ($xmlSheet && $xmlSheet->autoFilter) {
699✔
2357
            (new AutoFilter($docSheet, $xmlSheet))->load();
18✔
2358
        }
2359
    }
2360

2361
    private function readBackgroundImage(
699✔
2362
        SimpleXMLElement $xmlSheet,
2363
        Worksheet $docSheet,
2364
        string $relsName
2365
    ): void {
2366
        if ($xmlSheet && $xmlSheet->picture) {
699✔
2367
            $id = (string) self::getArrayItemString(self::getAttributes($xmlSheet->picture, Namespaces::SCHEMA_OFFICE_DOCUMENT), 'id');
1✔
2368
            $rels = $this->loadZip($relsName);
1✔
2369
            foreach ($rels->Relationship as $rel) {
1✔
2370
                $attrs = $rel->attributes() ?? [];
1✔
2371
                $rid = (string) ($attrs['Id'] ?? '');
1✔
2372
                $target = (string) ($attrs['Target'] ?? '');
1✔
2373
                if ($rid === $id && substr($target, 0, 2) === '..') {
1✔
2374
                    $target = 'xl' . substr($target, 2);
1✔
2375
                    $content = $this->getFromZipArchive($this->zip, $target);
1✔
2376
                    $docSheet->setBackgroundImage($content);
1✔
2377
                }
2378
            }
2379
        }
2380
    }
2381

2382
    /**
2383
     * @param TableDxfsStyle[] $tableStyles
2384
     * @param Style[] $dxfs
2385
     */
2386
    private function readTables(
702✔
2387
        SimpleXMLElement $xmlSheet,
2388
        Worksheet $docSheet,
2389
        string $dir,
2390
        string $fileWorksheet,
2391
        ZipArchive $zip,
2392
        string $namespaceTable,
2393
        array $tableStyles,
2394
        array $dxfs
2395
    ): void {
2396
        if ($xmlSheet && $xmlSheet->tableParts) {
702✔
2397
            /** @var array{count: scalar} */
2398
            $attributes = $xmlSheet->tableParts->attributes() ?? ['count' => 0];
37✔
2399
            if (((int) $attributes['count']) > 0) {
37✔
2400
                $this->readTablesInTablesFile($xmlSheet, $dir, $fileWorksheet, $zip, $docSheet, $namespaceTable, $tableStyles, $dxfs);
33✔
2401
            }
2402
        }
2403
    }
2404

2405
    /**
2406
     * @param TableDxfsStyle[] $tableStyles
2407
     * @param Style[] $dxfs
2408
     */
2409
    private function readTablesInTablesFile(
33✔
2410
        SimpleXMLElement $xmlSheet,
2411
        string $dir,
2412
        string $fileWorksheet,
2413
        ZipArchive $zip,
2414
        Worksheet $docSheet,
2415
        string $namespaceTable,
2416
        array $tableStyles,
2417
        array $dxfs
2418
    ): void {
2419
        foreach ($xmlSheet->tableParts->tablePart as $tablePart) {
33✔
2420
            $relation = self::getAttributes($tablePart, Namespaces::SCHEMA_OFFICE_DOCUMENT);
33✔
2421
            $tablePartRel = (string) $relation['id'];
33✔
2422
            $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
33✔
2423

2424
            if ($zip->locateName($relationsFileName) !== false) {
33✔
2425
                $relsTableReferences = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS);
33✔
2426
                foreach ($relsTableReferences->Relationship as $relationship) {
33✔
2427
                    $relationshipAttributes = self::getAttributes($relationship, '');
33✔
2428

2429
                    if ((string) $relationshipAttributes['Id'] === $tablePartRel) {
33✔
2430
                        $relationshipFileName = (string) $relationshipAttributes['Target'];
33✔
2431
                        $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName;
33✔
2432
                        $relationshipFilePath = File::realpath($relationshipFilePath);
33✔
2433

2434
                        if ($this->fileExistsInArchive($this->zip, $relationshipFilePath)) {
33✔
2435
                            $tableXml = $this->loadZip($relationshipFilePath, $namespaceTable);
33✔
2436
                            (new TableReader($docSheet, $tableXml))->load($tableStyles, $dxfs);
33✔
2437
                        }
2438
                    }
2439
                }
2440
            }
2441
        }
2442
    }
2443

2444
    /** @return mixed[] */
2445
    private static function extractStyles(?SimpleXMLElement $sxml, string $node1, string $node2): array
713✔
2446
    {
2447
        $array = [];
713✔
2448
        if ($sxml && $sxml->{$node1}->{$node2}) {
713✔
2449
            /** @var SimpleXMLElement */
2450
            $temp = $sxml->{$node1}->{$node2};
713✔
2451
            foreach ($temp as $node) {
713✔
2452
                $array[] = $node;
713✔
2453
            }
2454
        }
2455

2456
        return $array;
713✔
2457
    }
2458

2459
    /** @return string[] */
2460
    private static function extractPalette(?SimpleXMLElement $sxml): array
713✔
2461
    {
2462
        $array = [];
713✔
2463
        if ($sxml && $sxml->colors->indexedColors) {
713✔
2464
            foreach ($sxml->colors->indexedColors->rgbColor as $node) {
16✔
2465
                $attr = $node->attributes();
16✔
2466
                if (isset($attr['rgb'])) {
16✔
2467
                    $array[] = (string) $attr['rgb'];
16✔
2468
                }
2469
            }
2470
        }
2471

2472
        return $array;
713✔
2473
    }
2474

2475
    private function processIgnoredErrors(SimpleXMLElement $xml, Worksheet $sheet): void
4✔
2476
    {
2477
        $cellCollection = $sheet->getCellCollection();
4✔
2478
        $attributes = self::getAttributes($xml);
4✔
2479
        $sqref = (string) ($attributes['sqref'] ?? '');
4✔
2480
        $numberStoredAsText = (string) ($attributes['numberStoredAsText'] ?? '');
4✔
2481
        $formula = (string) ($attributes['formula'] ?? '');
4✔
2482
        $formulaRange = (string) ($attributes['formulaRange'] ?? '');
4✔
2483
        $twoDigitTextYear = (string) ($attributes['twoDigitTextYear'] ?? '');
4✔
2484
        $evalError = (string) ($attributes['evalError'] ?? '');
4✔
2485
        if (!empty($sqref)) {
4✔
2486
            $explodedSqref = explode(' ', $sqref);
4✔
2487
            $pattern1 = '/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/';
4✔
2488
            foreach ($explodedSqref as $sqref1) {
4✔
2489
                if (preg_match($pattern1, $sqref1, $matches) === 1) {
4✔
2490
                    $firstRow = $matches[2];
4✔
2491
                    $firstCol = $matches[1];
4✔
2492
                    if (array_key_exists(3, $matches)) {
4✔
2493
                        $lastCol = $matches[4];
3✔
2494
                        $lastRow = $matches[5];
3✔
2495
                    } else {
2496
                        $lastCol = $firstCol;
3✔
2497
                        $lastRow = $firstRow;
3✔
2498
                    }
2499
                    StringHelper::stringIncrement($lastCol);
4✔
2500
                    for ($row = $firstRow; $row <= $lastRow; ++$row) {
4✔
2501
                        for ($col = $firstCol; $col !== $lastCol; StringHelper::stringIncrement($col)) {
4✔
2502
                            if (!$cellCollection->has2("$col$row")) {
4✔
2503
                                continue;
1✔
2504
                            }
2505
                            if ($numberStoredAsText === '1') {
4✔
2506
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setNumberStoredAsText(true);
4✔
2507
                            }
2508
                            if ($formula === '1') {
4✔
2509
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setFormula(true);
1✔
2510
                            }
2511
                            if ($formulaRange === '1') {
4✔
2512
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setFormulaRange(true);
1✔
2513
                            }
2514
                            if ($twoDigitTextYear === '1') {
4✔
2515
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setTwoDigitTextYear(true);
1✔
2516
                            }
2517
                            if ($evalError === '1') {
4✔
2518
                                $sheet->getCell("$col$row")->getIgnoredErrors()->setEvalError(true);
1✔
2519
                            }
2520
                        }
2521
                    }
2522
                }
2523
            }
2524
        }
2525
    }
2526

2527
    private static function storeFormulaAttributes(SimpleXMLElement $f, Worksheet $docSheet, string $r): void
372✔
2528
    {
2529
        $formulaAttributes = [];
372✔
2530
        $attributes = $f->attributes();
372✔
2531
        if (isset($attributes['t'])) {
372✔
2532
            $formulaAttributes['t'] = (string) $attributes['t'];
249✔
2533
        }
2534
        if (isset($attributes['ref'])) {
372✔
2535
            $formulaAttributes['ref'] = (string) $attributes['ref'];
249✔
2536
        }
2537
        if (!empty($formulaAttributes)) {
372✔
2538
            $docSheet->getCell($r)->setFormulaAttributes($formulaAttributes);
249✔
2539
        }
2540
    }
2541

2542
    private static function onlyNoteVml(string $data): bool
13✔
2543
    {
2544
        $data = str_replace('<br>', '<br/>', $data);
13✔
2545

2546
        try {
2547
            $sxml = @simplexml_load_string($data);
13✔
2548
        } catch (Throwable) {
×
2549
            $sxml = false;
×
2550
        }
2551

2552
        if ($sxml === false) {
13✔
2553
            return false;
1✔
2554
        }
2555
        $shapes = $sxml->children(Namespaces::URN_VML);
12✔
2556
        foreach ($shapes->shape as $shape) {
12✔
2557
            $clientData = $shape->children(Namespaces::URN_EXCEL);
12✔
2558
            if (!isset($clientData->ClientData)) {
12✔
2559
                return false;
×
2560
            }
2561
            $attrs = $clientData->ClientData->attributes();
12✔
2562
            if (!isset($attrs['ObjectType'])) {
12✔
2563
                return false;
×
2564
            }
2565
            $objectType = (string) $attrs['ObjectType'];
12✔
2566
            if ($objectType !== 'Note') {
12✔
2567
                return false;
4✔
2568
            }
2569
        }
2570

2571
        return true;
9✔
2572
    }
2573
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc