Completed
Push — master ( dfd9c5...ccebf0 )
by Mark
161:27 queued 155:49
created

src/PhpSpreadsheet/Reader/Xlsx.php (7 issues)

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
6
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
7
use PhpOffice\PhpSpreadsheet\Document\Properties;
8
use PhpOffice\PhpSpreadsheet\NamedRange;
9
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
10
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart;
11
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
12
use PhpOffice\PhpSpreadsheet\RichText\RichText;
13
use PhpOffice\PhpSpreadsheet\Settings;
14
use PhpOffice\PhpSpreadsheet\Shared\Date;
15
use PhpOffice\PhpSpreadsheet\Shared\Drawing;
16
use PhpOffice\PhpSpreadsheet\Shared\File;
17
use PhpOffice\PhpSpreadsheet\Shared\Font;
18
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
19
use PhpOffice\PhpSpreadsheet\Spreadsheet;
20
use PhpOffice\PhpSpreadsheet\Style\Border;
21
use PhpOffice\PhpSpreadsheet\Style\Borders;
22
use PhpOffice\PhpSpreadsheet\Style\Color;
23
use PhpOffice\PhpSpreadsheet\Style\Conditional;
24
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
25
use PhpOffice\PhpSpreadsheet\Style\Protection;
26
use PhpOffice\PhpSpreadsheet\Style\Style;
27
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
28
use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing;
29
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
30
use SimpleXMLElement;
31
use XMLReader;
32
use ZipArchive;
33
34
class Xlsx extends BaseReader
35
{
36
    /**
37
     * ReferenceHelper instance.
38
     *
39
     * @var ReferenceHelper
40
     */
41
    private $referenceHelper;
42
43
    /**
44
     * Xlsx\Theme instance.
45
     *
46
     * @var Xlsx\Theme
47
     */
48
    private static $theme = null;
49
50
    /**
51
     * Create a new Xlsx Reader instance.
52
     */
53 45
    public function __construct()
54
    {
55 45
        $this->readFilter = new DefaultReadFilter();
56 45
        $this->referenceHelper = ReferenceHelper::getInstance();
57 45
        $this->securityScanner = XmlScanner::getInstance($this);
58 45
    }
59
60
    /**
61
     * Can the current IReader read the file?
62
     *
63
     * @param string $pFilename
64
     *
65
     * @throws Exception
66
     *
67
     * @return bool
68
     */
69 6
    public function canRead($pFilename)
70
    {
71 6
        File::assertFile($pFilename);
72
73 6
        $xl = false;
74
        // Load file
75 6
        $zip = new ZipArchive();
76 6
        if ($zip->open($pFilename) === true) {
77
            // check if it is an OOXML archive
78 6
            $rels = simplexml_load_string(
79 6
                $this->securityScanner->scan(
80 6
                    $this->getFromZipArchive($zip, '_rels/.rels')
81
                ),
82 6
                'SimpleXMLElement',
83 6
                Settings::getLibXmlLoaderOptions()
84
            );
85 6
            if ($rels !== false) {
86 6
                foreach ($rels->Relationship as $rel) {
87 6
                    switch ($rel['Type']) {
88 6
                        case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
89 6
                            if (basename($rel['Target']) == 'workbook.xml') {
90 6
                                $xl = true;
91
                            }
92
93 6
                            break;
94
                    }
95
                }
96
            }
97 6
            $zip->close();
98
        }
99
100 6
        return $xl;
101
    }
102
103
    /**
104
     * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
105
     *
106
     * @param string $pFilename
107
     *
108
     * @throws Exception
109
     *
110
     * @return array
111
     */
112 1
    public function listWorksheetNames($pFilename)
113
    {
114 1
        File::assertFile($pFilename);
115
116 1
        $worksheetNames = [];
117
118 1
        $zip = new ZipArchive();
119 1
        $zip->open($pFilename);
120
121
        //    The files we're looking at here are small enough that simpleXML is more efficient than XMLReader
122
        //~ http://schemas.openxmlformats.org/package/2006/relationships");
123 1
        $rels = simplexml_load_string(
124 1
            $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels'))
125
        );
126 1
        foreach ($rels->Relationship as $rel) {
127 1
            switch ($rel['Type']) {
128 1
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
129
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
130 1
                    $xmlWorkbook = simplexml_load_string(
131 1
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}"))
132
                    );
133
134 1
                    if ($xmlWorkbook->sheets) {
135 1
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
136
                            // Check if sheet should be skipped
137 1
                            $worksheetNames[] = (string) $eleSheet['name'];
138
                        }
139
                    }
140
            }
141
        }
142
143 1
        $zip->close();
144
145 1
        return $worksheetNames;
146
    }
147
148
    /**
149
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
150
     *
151
     * @param string $pFilename
152
     *
153
     * @throws Exception
154
     *
155
     * @return array
156
     */
157 1
    public function listWorksheetInfo($pFilename)
158
    {
159 1
        File::assertFile($pFilename);
160
161 1
        $worksheetInfo = [];
162
163 1
        $zip = new ZipArchive();
164 1
        $zip->open($pFilename);
165
166
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
167 1
        $rels = simplexml_load_string(
168 1
            $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')),
169 1
            'SimpleXMLElement',
170 1
            Settings::getLibXmlLoaderOptions()
171
        );
172 1
        foreach ($rels->Relationship as $rel) {
173 1
            if ($rel['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument') {
174 1
                $dir = dirname($rel['Target']);
175
176
                //~ http://schemas.openxmlformats.org/package/2006/relationships"
177 1
                $relsWorkbook = simplexml_load_string(
178 1
                    $this->securityScanner->scan(
179 1
                        $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')
180
                    ),
181 1
                    'SimpleXMLElement',
182 1
                    Settings::getLibXmlLoaderOptions()
183
                );
184 1
                $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
185
186 1
                $worksheets = [];
187 1
                foreach ($relsWorkbook->Relationship as $ele) {
188 1
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet') {
189 1
                        $worksheets[(string) $ele['Id']] = $ele['Target'];
190
                    }
191
                }
192
193
                //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
194 1
                $xmlWorkbook = simplexml_load_string(
195 1
                    $this->securityScanner->scan(
196 1
                        $this->getFromZipArchive($zip, "{$rel['Target']}")
197
                    ),
198 1
                    'SimpleXMLElement',
199 1
                    Settings::getLibXmlLoaderOptions()
200
                );
201 1
                if ($xmlWorkbook->sheets) {
202 1
                    $dir = dirname($rel['Target']);
203
                    /** @var SimpleXMLElement $eleSheet */
204 1
                    foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
205
                        $tmpInfo = [
206 1
                            'worksheetName' => (string) $eleSheet['name'],
207 1
                            'lastColumnLetter' => 'A',
208 1
                            'lastColumnIndex' => 0,
209 1
                            'totalRows' => 0,
210 1
                            'totalColumns' => 0,
211
                        ];
212
213 1
                        $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
214
215 1
                        $xml = new XMLReader();
216 1
                        $xml->xml(
217 1
                            $this->securityScanner->scanFile(
218 1
                                'zip://' . File::realpath($pFilename) . '#' . "$dir/$fileWorksheet"
219
                            ),
220 1
                            null,
221 1
                            Settings::getLibXmlLoaderOptions()
222
                        );
223 1
                        $xml->setParserProperty(2, true);
224
225 1
                        $currCells = 0;
226 1
                        while ($xml->read()) {
227 1
                            if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) {
228 1
                                $row = $xml->getAttribute('r');
229 1
                                $tmpInfo['totalRows'] = $row;
230 1
                                $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
231 1
                                $currCells = 0;
232 1
                            } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) {
233 1
                                ++$currCells;
234
                            }
235
                        }
236 1
                        $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
237 1
                        $xml->close();
238
239 1
                        $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
240 1
                        $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
241
242 1
                        $worksheetInfo[] = $tmpInfo;
243
                    }
244
                }
245
            }
246
        }
247
248 1
        $zip->close();
249
250 1
        return $worksheetInfo;
251
    }
252
253 4
    private static function castToBoolean($c)
254
    {
255 4
        $value = isset($c->v) ? (string) $c->v : null;
256 4
        if ($value == '0') {
257
            return false;
258 4
        } elseif ($value == '1') {
259 4
            return true;
260
        }
261
262
        return (bool) $c->v;
263
    }
264
265
    private static function castToError($c)
266
    {
267
        return isset($c->v) ? (string) $c->v : null;
268
    }
269
270 20
    private static function castToString($c)
271
    {
272 20
        return isset($c->v) ? (string) $c->v : null;
273
    }
274
275 7
    private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType)
276
    {
277 7
        $cellDataType = 'f';
278 7
        $value = "={$c->f}";
279 7
        $calculatedValue = self::$castBaseType($c);
280
281
        // Shared formula?
282 7
        if (isset($c->f['t']) && strtolower((string) $c->f['t']) == 'shared') {
283 2
            $instance = (string) $c->f['si'];
284
285 2
            if (!isset($sharedFormulas[(string) $c->f['si']])) {
286 2
                $sharedFormulas[$instance] = ['master' => $r, 'formula' => $value];
287
            } else {
288 2
                $master = Coordinate::coordinateFromString($sharedFormulas[$instance]['master']);
289 2
                $current = Coordinate::coordinateFromString($r);
290
291 2
                $difference = [0, 0];
292 2
                $difference[0] = Coordinate::columnIndexFromString($current[0]) - Coordinate::columnIndexFromString($master[0]);
293 2
                $difference[1] = $current[1] - $master[1];
294
295 2
                $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], 'A1', $difference[0], $difference[1]);
296
            }
297
        }
298 7
    }
299
300
    /**
301
     * @param ZipArchive $archive
302
     * @param string $fileName
303
     *
304
     * @return string
305
     */
306 42
    private function getFromZipArchive(ZipArchive $archive, $fileName = '')
307
    {
308
        // Root-relative paths
309 42
        if (strpos($fileName, '//') !== false) {
310
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
311
        }
312 42
        $fileName = File::realpath($fileName);
313
314
        // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
315
        //    so we need to load case-insensitively from the zip file
316
317
        // Apache POI fixes
318 42
        $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
319 42
        if ($contents === false) {
320 1
            $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
321
        }
322
323 42
        return $contents;
324
    }
325
326
    /**
327
     * Set Worksheet column attributes by attributes array passed.
328
     *
329
     * @param Worksheet $docSheet
330
     * @param string $column A, B, ... DX, ...
331
     * @param array $columnAttributes array of attributes (indexes are attribute name, values are value)
332
     *                               'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'width', ... ?
333
     */
334 10
    private function setColumnAttributes(Worksheet $docSheet, $column, array $columnAttributes)
335
    {
336 10
        if (isset($columnAttributes['xfIndex'])) {
337 4
            $docSheet->getColumnDimension($column)->setXfIndex($columnAttributes['xfIndex']);
338
        }
339 10
        if (isset($columnAttributes['visible'])) {
340 1
            $docSheet->getColumnDimension($column)->setVisible($columnAttributes['visible']);
341
        }
342 10
        if (isset($columnAttributes['collapsed'])) {
343 1
            $docSheet->getColumnDimension($column)->setCollapsed($columnAttributes['collapsed']);
344
        }
345 10
        if (isset($columnAttributes['outlineLevel'])) {
346 1
            $docSheet->getColumnDimension($column)->setOutlineLevel($columnAttributes['outlineLevel']);
347
        }
348 10
        if (isset($columnAttributes['width'])) {
349 10
            $docSheet->getColumnDimension($column)->setWidth($columnAttributes['width']);
350
        }
351 10
    }
352
353
    /**
354
     * Set Worksheet row attributes by attributes array passed.
355
     *
356
     * @param Worksheet $docSheet
357
     * @param int $row 1, 2, 3, ... 99, ...
358
     * @param array $rowAttributes array of attributes (indexes are attribute name, values are value)
359
     *                               'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'rowHeight', ... ?
360
     */
361 3
    private function setRowAttributes(Worksheet $docSheet, $row, array $rowAttributes)
362
    {
363 3
        if (isset($rowAttributes['xfIndex'])) {
364
            $docSheet->getRowDimension($row)->setXfIndex($rowAttributes['xfIndex']);
365
        }
366 3
        if (isset($rowAttributes['visible'])) {
367
            $docSheet->getRowDimension($row)->setVisible($rowAttributes['visible']);
368
        }
369 3
        if (isset($rowAttributes['collapsed'])) {
370
            $docSheet->getRowDimension($row)->setCollapsed($rowAttributes['collapsed']);
371
        }
372 3
        if (isset($rowAttributes['outlineLevel'])) {
373
            $docSheet->getRowDimension($row)->setOutlineLevel($rowAttributes['outlineLevel']);
374
        }
375 3
        if (isset($rowAttributes['rowHeight'])) {
376 3
            $docSheet->getRowDimension($row)->setRowHeight($rowAttributes['rowHeight']);
377
        }
378 3
    }
379
380
    /**
381
     * Loads Spreadsheet from file.
382
     *
383
     * @param string $pFilename
384
     *
385
     * @throws Exception
386
     *
387
     * @return Spreadsheet
388
     */
389 39
    public function load($pFilename)
390
    {
391 39
        File::assertFile($pFilename);
392
393
        // Initialisations
394 39
        $excel = new Spreadsheet();
395 39
        $excel->removeSheetByIndex(0);
396 39
        if (!$this->readDataOnly) {
397 39
            $excel->removeCellStyleXfByIndex(0); // remove the default style
398 39
            $excel->removeCellXfByIndex(0); // remove the default style
399
        }
400 39
        $unparsedLoadedData = [];
401
402 39
        $zip = new ZipArchive();
403 39
        $zip->open($pFilename);
404
405
        //    Read the theme first, because we need the colour scheme when reading the styles
406
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
407 39
        $wbRels = simplexml_load_string(
408 39
            $this->securityScanner->scan($this->getFromZipArchive($zip, 'xl/_rels/workbook.xml.rels')),
409 39
            'SimpleXMLElement',
410 39
            Settings::getLibXmlLoaderOptions()
411
        );
412 39
        foreach ($wbRels->Relationship as $rel) {
413 39
            switch ($rel['Type']) {
414 39
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme':
415 39
                    $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
416 39
                    $themeOrderAdditional = count($themeOrderArray);
417
418 39
                    $xmlTheme = simplexml_load_string(
419 39
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")),
420 39
                        'SimpleXMLElement',
421 39
                        Settings::getLibXmlLoaderOptions()
422
                    );
423 39
                    if (is_object($xmlTheme)) {
424 39
                        $xmlThemeName = $xmlTheme->attributes();
425 39
                        $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
426 39
                        $themeName = (string) $xmlThemeName['name'];
427
428 39
                        $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
429 39
                        $colourSchemeName = (string) $colourScheme['name'];
430 39
                        $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
431
432 39
                        $themeColours = [];
433 39
                        foreach ($colourScheme as $k => $xmlColour) {
434 39
                            $themePos = array_search($k, $themeOrderArray);
435 39
                            if ($themePos === false) {
436 39
                                $themePos = $themeOrderAdditional++;
437
                            }
438 39
                            if (isset($xmlColour->sysClr)) {
439 39
                                $xmlColourData = $xmlColour->sysClr->attributes();
440 39
                                $themeColours[$themePos] = $xmlColourData['lastClr'];
441 39
                            } elseif (isset($xmlColour->srgbClr)) {
442 39
                                $xmlColourData = $xmlColour->srgbClr->attributes();
443 39
                                $themeColours[$themePos] = $xmlColourData['val'];
444
                            }
445
                        }
446 39
                        self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours);
447
                    }
448
449 39
                    break;
450
            }
451
        }
452
453
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
454 39
        $rels = simplexml_load_string(
455 39
            $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')),
456 39
            'SimpleXMLElement',
457 39
            Settings::getLibXmlLoaderOptions()
458
        );
459 39
        foreach ($rels->Relationship as $rel) {
460 39
            switch ($rel['Type']) {
461 39
                case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties':
462 37
                    $xmlCore = simplexml_load_string(
463 37
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")),
464 37
                        'SimpleXMLElement',
465 37
                        Settings::getLibXmlLoaderOptions()
466
                    );
467 37
                    if (is_object($xmlCore)) {
468 37
                        $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/');
469 37
                        $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/');
470 37
                        $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
471 37
                        $docProps = $excel->getProperties();
472 37
                        $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator')));
473 37
                        $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy')));
474 37
                        $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type
475 37
                        $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type
476 37
                        $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title')));
477 37
                        $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description')));
478 37
                        $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject')));
479 37
                        $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath('cp:keywords')));
480 37
                        $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath('cp:category')));
481
                    }
482
483 37
                    break;
484 39
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties':
485 37
                    $xmlCore = simplexml_load_string(
486 37
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")),
487 37
                        'SimpleXMLElement',
488 37
                        Settings::getLibXmlLoaderOptions()
489
                    );
490 37
                    if (is_object($xmlCore)) {
491 37
                        $docProps = $excel->getProperties();
492 37
                        if (isset($xmlCore->Company)) {
493 35
                            $docProps->setCompany((string) $xmlCore->Company);
494
                        }
495 37
                        if (isset($xmlCore->Manager)) {
496 32
                            $docProps->setManager((string) $xmlCore->Manager);
497
                        }
498
                    }
499
500 37
                    break;
501 39
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties':
502 3
                    $xmlCore = simplexml_load_string(
503 3
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")),
504 3
                        'SimpleXMLElement',
505 3
                        Settings::getLibXmlLoaderOptions()
506
                    );
507 3
                    if (is_object($xmlCore)) {
508 3
                        $docProps = $excel->getProperties();
509
                        /** @var SimpleXMLElement $xmlProperty */
510 3
                        foreach ($xmlCore as $xmlProperty) {
511 3
                            $cellDataOfficeAttributes = $xmlProperty->attributes();
512 3
                            if (isset($cellDataOfficeAttributes['name'])) {
513 3
                                $propertyName = (string) $cellDataOfficeAttributes['name'];
514 3
                                $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
515 3
                                $attributeType = $cellDataOfficeChildren->getName();
516 3
                                $attributeValue = (string) $cellDataOfficeChildren->{$attributeType};
517 3
                                $attributeValue = Properties::convertProperty($attributeValue, $attributeType);
518 3
                                $attributeType = Properties::convertPropertyType($attributeType);
519 3
                                $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType);
520
                            }
521
                        }
522
                    }
523
524 3
                    break;
525
                //Ribbon
526 39
                case 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility':
527
                    $customUI = $rel['Target'];
528
                    if ($customUI !== null) {
529
                        $this->readRibbon($excel, $customUI, $zip);
530
                    }
531
532
                    break;
533 39
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
534 39
                    $dir = dirname($rel['Target']);
535
                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
536 39
                    $relsWorkbook = simplexml_load_string(
537 39
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')),
538 39
                        'SimpleXMLElement',
539 39
                        Settings::getLibXmlLoaderOptions()
540
                    );
541 39
                    $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
542
543 39
                    $sharedStrings = [];
544 39
                    $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
545
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
546 39
                    $xmlStrings = simplexml_load_string(
547 39
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
548 39
                        'SimpleXMLElement',
549 39
                        Settings::getLibXmlLoaderOptions()
550
                    );
551 39
                    if (isset($xmlStrings, $xmlStrings->si)) {
552 19
                        foreach ($xmlStrings->si as $val) {
553 19
                            if (isset($val->t)) {
554 19
                                $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
555 3
                            } elseif (isset($val->r)) {
556 3
                                $sharedStrings[] = $this->parseRichText($val);
557
                            }
558
                        }
559
                    }
560
561 39
                    $worksheets = [];
562 39
                    $macros = $customUI = null;
563 39
                    foreach ($relsWorkbook->Relationship as $ele) {
564 39
                        switch ($ele['Type']) {
565 39
                            case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet':
566 39
                                $worksheets[(string) $ele['Id']] = $ele['Target'];
567
568 39
                                break;
569
                            // a vbaProject ? (: some macros)
570 39
                            case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject':
571 1
                                $macros = $ele['Target'];
572
573 1
                                break;
574
                        }
575
                    }
576
577 39
                    if ($macros !== null) {
578 1
                        $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin
579 1
                        if ($macrosCode !== false) {
580 1
                            $excel->setMacrosCode($macrosCode);
581 1
                            $excel->setHasMacros(true);
582
                            //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir
583 1
                            $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin');
584 1
                            if ($Certificate !== false) {
585
                                $excel->setMacrosCertificate($Certificate);
586
                            }
587
                        }
588
                    }
589 39
                    $styles = [];
590 39
                    $cellStyles = [];
591 39
                    $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
592
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
593 39
                    $xmlStyles = simplexml_load_string(
594 39
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
595 39
                        'SimpleXMLElement',
596 39
                        Settings::getLibXmlLoaderOptions()
597
                    );
598 39
                    $numFmts = null;
599 39
                    if ($xmlStyles && $xmlStyles->numFmts[0]) {
600 32
                        $numFmts = $xmlStyles->numFmts[0];
601
                    }
602 39
                    if (isset($numFmts) && ($numFmts !== null)) {
603 32
                        $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
604
                    }
605 39
                    if (!$this->readDataOnly && $xmlStyles) {
606 39
                        foreach ($xmlStyles->cellXfs->xf as $xf) {
607 39
                            $numFmt = NumberFormat::FORMAT_GENERAL;
608
609 39
                            if ($xf['numFmtId']) {
610 39
                                if (isset($numFmts)) {
611 32
                                    $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
612
613 32
                                    if (isset($tmpNumFmt['formatCode'])) {
614 4
                                        $numFmt = (string) $tmpNumFmt['formatCode'];
615
                                    }
616
                                }
617
618
                                // We shouldn't override any of the built-in MS Excel values (values below id 164)
619
                                //  But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used
620
                                //  So we make allowance for them rather than lose formatting masks
621 39
                                if ((int) $xf['numFmtId'] < 164 &&
622 39
                                    NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '') {
623 39
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
624
                                }
625
                            }
626 39
                            $quotePrefix = false;
627 39
                            if (isset($xf['quotePrefix'])) {
628
                                $quotePrefix = (bool) $xf['quotePrefix'];
629
                            }
630
631
                            $style = (object) [
632 39
                                'numFmt' => $numFmt,
633 39
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
634 39
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
635 39
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
636 39
                                'alignment' => $xf->alignment,
637 39
                                'protection' => $xf->protection,
638 39
                                'quotePrefix' => $quotePrefix,
639
                            ];
640 39
                            $styles[] = $style;
641
642
                            // add style to cellXf collection
643 39
                            $objStyle = new Style();
644 39
                            self::readStyle($objStyle, $style);
645 39
                            $excel->addCellXf($objStyle);
646
                        }
647
648 39
                        foreach (isset($xmlStyles->cellStyleXfs->xf) ? $xmlStyles->cellStyleXfs->xf : [] as $xf) {
649 39
                            $numFmt = NumberFormat::FORMAT_GENERAL;
650 39
                            if ($numFmts && $xf['numFmtId']) {
651 32
                                $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
652 32
                                if (isset($tmpNumFmt['formatCode'])) {
653 2
                                    $numFmt = (string) $tmpNumFmt['formatCode'];
654 32
                                } elseif ((int) $xf['numFmtId'] < 165) {
655 32
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
656
                                }
657
                            }
658
659
                            $cellStyle = (object) [
660 39
                                'numFmt' => $numFmt,
661 39
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
662 39
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
663 39
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
664 39
                                'alignment' => $xf->alignment,
665 39
                                'protection' => $xf->protection,
666 39
                                'quotePrefix' => $quotePrefix,
667
                            ];
668 39
                            $cellStyles[] = $cellStyle;
669
670
                            // add style to cellStyleXf collection
671 39
                            $objStyle = new Style();
672 39
                            self::readStyle($objStyle, $cellStyle);
673 39
                            $excel->addCellStyleXf($objStyle);
674
                        }
675
                    }
676
677 39
                    $dxfs = [];
678 39
                    if (!$this->readDataOnly && $xmlStyles) {
679
                        //    Conditional Styles
680 39
                        if ($xmlStyles->dxfs) {
681 39
                            foreach ($xmlStyles->dxfs->dxf as $dxf) {
682 1
                                $style = new Style(false, true);
683 1
                                self::readStyle($style, $dxf);
684 1
                                $dxfs[] = $style;
685
                            }
686
                        }
687
                        //    Cell Styles
688 39
                        if ($xmlStyles->cellStyles) {
689 39
                            foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) {
690 39
                                if ((int) ($cellStyle['builtinId']) == 0) {
691 39
                                    if (isset($cellStyles[(int) ($cellStyle['xfId'])])) {
692
                                        // Set default style
693 39
                                        $style = new Style();
694 39
                                        self::readStyle($style, $cellStyles[(int) ($cellStyle['xfId'])]);
695
696
                                        // normal style, currently not using it for anything
697
                                    }
698
                                }
699
                            }
700
                        }
701
                    }
702
703
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
704 39
                    $xmlWorkbook = simplexml_load_string(
705 39
                        $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")),
706 39
                        'SimpleXMLElement',
707 39
                        Settings::getLibXmlLoaderOptions()
708
                    );
709
710
                    // Set base date
711 39
                    if ($xmlWorkbook->workbookPr) {
712 37
                        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
713 37
                        if (isset($xmlWorkbook->workbookPr['date1904'])) {
714
                            if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) {
715
                                Date::setExcelCalendar(Date::CALENDAR_MAC_1904);
716
                            }
717
                        }
718
                    }
719
720
                    // Set protection
721 39
                    $this->readProtection($excel, $xmlWorkbook);
722
723 39
                    $sheetId = 0; // keep track of new sheet id in final workbook
724 39
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
725 39
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
726 39
                    $mapSheetId = []; // mapping of sheet ids from old to new
727
728 39
                    $charts = $chartDetails = [];
729
730 39
                    if ($xmlWorkbook->sheets) {
731
                        /** @var SimpleXMLElement $eleSheet */
732 39
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
733 39
                            ++$oldSheetId;
734
735
                            // Check if sheet should be skipped
736 39
                            if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) {
737 1
                                ++$countSkippedSheets;
738 1
                                $mapSheetId[$oldSheetId] = null;
739
740 1
                                continue;
741
                            }
742
743
                            // Map old sheet id in original workbook to new sheet id.
744
                            // They will differ if loadSheetsOnly() is being used
745 39
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
746
747
                            // Load sheet
748 39
                            $docSheet = $excel->createSheet();
749
                            //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet
750
                            //        references in formula cells... during the load, all formulae should be correct,
751
                            //        and we're simply bringing the worksheet name in line with the formula, not the
752
                            //        reverse
753 39
                            $docSheet->setTitle((string) $eleSheet['name'], false, false);
754 39
                            $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
755
                            //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
756 39
                            $xmlSheet = simplexml_load_string(
757 39
                                $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")),
758 39
                                'SimpleXMLElement',
759 39
                                Settings::getLibXmlLoaderOptions()
760
                            );
761
762 39
                            $sharedFormulas = [];
763
764 39
                            if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') {
765 1
                                $docSheet->setSheetState((string) $eleSheet['state']);
766
                            }
767
768 39
                            if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) {
769 39
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) {
770
                                    $zoomScale = (int) ($xmlSheet->sheetViews->sheetView['zoomScale']);
771
                                    if ($zoomScale <= 0) {
772
                                        // setZoomScale will throw an Exception if the scale is less than or equals 0
773
                                        // that is OK when manually creating documents, but we should be able to read all documents
774
                                        $zoomScale = 100;
775
                                    }
776
777
                                    $docSheet->getSheetView()->setZoomScale($zoomScale);
778
                                }
779 39
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) {
780
                                    $zoomScaleNormal = (int) ($xmlSheet->sheetViews->sheetView['zoomScaleNormal']);
781
                                    if ($zoomScaleNormal <= 0) {
782
                                        // setZoomScaleNormal will throw an Exception if the scale is less than or equals 0
783
                                        // that is OK when manually creating documents, but we should be able to read all documents
784
                                        $zoomScaleNormal = 100;
785
                                    }
786
787
                                    $docSheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal);
788
                                }
789 39
                                if (isset($xmlSheet->sheetViews->sheetView['view'])) {
790
                                    $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']);
791
                                }
792 39
                                if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
793 30
                                    $docSheet->setShowGridLines(self::boolean((string) $xmlSheet->sheetViews->sheetView['showGridLines']));
794
                                }
795 39
                                if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
796 30
                                    $docSheet->setShowRowColHeaders(self::boolean((string) $xmlSheet->sheetViews->sheetView['showRowColHeaders']));
797
                                }
798 39
                                if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
799
                                    $docSheet->setRightToLeft(self::boolean((string) $xmlSheet->sheetViews->sheetView['rightToLeft']));
800
                                }
801 39
                                if (isset($xmlSheet->sheetViews->sheetView->pane)) {
802 3
                                    $xSplit = 0;
803 3
                                    $ySplit = 0;
804 3
                                    $topLeftCell = null;
805
806 3
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
807 1
                                        $xSplit = (int) ($xmlSheet->sheetViews->sheetView->pane['xSplit']);
808
                                    }
809
810 3
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
811 3
                                        $ySplit = (int) ($xmlSheet->sheetViews->sheetView->pane['ySplit']);
812
                                    }
813
814 3
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
815 3
                                        $topLeftCell = (string) $xmlSheet->sheetViews->sheetView->pane['topLeftCell'];
816
                                    }
817
818 3
                                    $docSheet->freezePane(Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1), $topLeftCell);
819
                                }
820
821 39
                                if (isset($xmlSheet->sheetViews->sheetView->selection)) {
822 37
                                    if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
823 36
                                        $sqref = (string) $xmlSheet->sheetViews->sheetView->selection['sqref'];
824 36
                                        $sqref = explode(' ', $sqref);
825 36
                                        $sqref = $sqref[0];
826 36
                                        $docSheet->setSelectedCells($sqref);
827
                                    }
828
                                }
829
                            }
830
831 39
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->tabColor)) {
832 2
                                if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
833 2
                                    $docSheet->getTabColor()->setARGB((string) $xmlSheet->sheetPr->tabColor['rgb']);
834
                                }
835
                            }
836 39
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr['codeName'])) {
837 1
                                $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName'], false);
838
                            }
839 39
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->outlinePr)) {
840 30
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) &&
841 30
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) {
842
                                    $docSheet->setShowSummaryRight(false);
843
                                } else {
844 30
                                    $docSheet->setShowSummaryRight(true);
845
                                }
846
847 30
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) &&
848 30
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) {
849
                                    $docSheet->setShowSummaryBelow(false);
850
                                } else {
851 30
                                    $docSheet->setShowSummaryBelow(true);
852
                                }
853
                            }
854
855 39
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->pageSetUpPr)) {
856
                                if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) &&
857
                                    !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) {
858
                                    $docSheet->getPageSetup()->setFitToPage(false);
859
                                } else {
860
                                    $docSheet->getPageSetup()->setFitToPage(true);
861
                                }
862
                            }
863
864 39
                            if (isset($xmlSheet->sheetFormatPr)) {
865 39
                                if (isset($xmlSheet->sheetFormatPr['customHeight']) &&
866 39
                                    self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) &&
867 39
                                    isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
868 2
                                    $docSheet->getDefaultRowDimension()->setRowHeight((float) $xmlSheet->sheetFormatPr['defaultRowHeight']);
869
                                }
870 39
                                if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
871 2
                                    $docSheet->getDefaultColumnDimension()->setWidth((float) $xmlSheet->sheetFormatPr['defaultColWidth']);
872
                                }
873 39
                                if (isset($xmlSheet->sheetFormatPr['zeroHeight']) &&
874 39
                                    ((string) $xmlSheet->sheetFormatPr['zeroHeight'] == '1')) {
875
                                    $docSheet->getDefaultRowDimension()->setZeroHeight(true);
876
                                }
877
                            }
878
879 39
                            if (isset($xmlSheet->printOptions) && !$this->readDataOnly) {
880 30
                                if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) {
881 30
                                    $docSheet->setShowGridlines(true);
882
                                }
883 30
                                if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) {
884
                                    $docSheet->setPrintGridlines(true);
885
                                }
886 30
                                if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) {
887
                                    $docSheet->getPageSetup()->setHorizontalCentered(true);
888
                                }
889 30
                                if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) {
890
                                    $docSheet->getPageSetup()->setVerticalCentered(true);
891
                                }
892
                            }
893
894 39
                            $this->readColumnsAndRowsAttributes($xmlSheet, $docSheet);
895
896 39
                            if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
897 33
                                $cIndex = 1; // Cell Start from 1
898 33
                                foreach ($xmlSheet->sheetData->row as $row) {
899 33
                                    $rowIndex = 1;
900 33
                                    foreach ($row->c as $c) {
901 33
                                        $r = (string) $c['r'];
902 33
                                        if ($r == '') {
903 2
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
904
                                        }
905 33
                                        $cellDataType = (string) $c['t'];
906 33
                                        $value = null;
907 33
                                        $calculatedValue = null;
908
909
                                        // Read cell?
910 33
                                        if ($this->getReadFilter() !== null) {
911 33
                                            $coordinates = Coordinate::coordinateFromString($r);
912
913 33
                                            if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) {
914 3
                                                $rowIndex += 1;
915
916 3
                                                continue;
917
                                            }
918
                                        }
919
920
                                        // Read cell!
921 33
                                        switch ($cellDataType) {
922 33
                                            case 's':
923 19
                                                if ((string) $c->v != '') {
924 19
                                                    $value = $sharedStrings[(int) ($c->v)];
925
926 19
                                                    if ($value instanceof RichText) {
927 19
                                                        $value = clone $value;
928
                                                    }
929
                                                } else {
930
                                                    $value = '';
931
                                                }
932
933 19
                                                break;
934 23
                                            case 'b':
935 4
                                                if (!isset($c->f)) {
936 2
                                                    $value = self::castToBoolean($c);
937
                                                } else {
938
                                                    // Formula
939 2
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean');
940 2
                                                    if (isset($c->f['t'])) {
941
                                                        $att = $c->f;
942
                                                        $docSheet->getCell($r)->setFormulaAttributes($att);
943
                                                    }
944
                                                }
945
946 4
                                                break;
947 20
                                            case 'inlineStr':
948 2
                                                if (isset($c->f)) {
949
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
950
                                                } else {
951 2
                                                    $value = $this->parseRichText($c->is);
952
                                                }
953
954 2
                                                break;
955 20
                                            case 'e':
956
                                                if (!isset($c->f)) {
957
                                                    $value = self::castToError($c);
958
                                                } else {
959
                                                    // Formula
960
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
961
                                                }
962
963
                                                break;
964
                                            default:
965 20
                                                if (!isset($c->f)) {
966 18
                                                    $value = self::castToString($c);
967
                                                } else {
968
                                                    // Formula
969 6
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
970
                                                }
971
972 20
                                                break;
973
                                        }
974
975
                                        // Check for numeric values
976 33
                                        if (is_numeric($value) && $cellDataType != 's') {
977 16
                                            if ($value == (int) $value) {
978 15
                                                $value = (int) $value;
979 1
                                            } elseif ($value == (float) $value) {
980 1
                                                $value = (float) $value;
981
                                            } elseif ($value == (float) $value) {
982
                                                $value = (float) $value;
983
                                            }
984
                                        }
985
986
                                        // Rich text?
987 33
                                        if ($value instanceof RichText && $this->readDataOnly) {
988
                                            $value = $value->getPlainText();
989
                                        }
990
991 33
                                        $cell = $docSheet->getCell($r);
992
                                        // Assign value
993 33
                                        if ($cellDataType != '') {
994 23
                                            $cell->setValueExplicit($value, $cellDataType);
995
                                        } else {
996 18
                                            $cell->setValue($value);
997
                                        }
998 33
                                        if ($calculatedValue !== null) {
999 7
                                            $cell->setCalculatedValue($calculatedValue);
1000
                                        }
1001
1002
                                        // Style information?
1003 33
                                        if ($c['s'] && !$this->readDataOnly) {
1004
                                            // no style index means 0, it seems
1005 8
                                            $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
1006 8
                                                (int) ($c['s']) : 0);
1007
                                        }
1008 33
                                        $rowIndex += 1;
1009
                                    }
1010 33
                                    $cIndex += 1;
1011
                                }
1012
                            }
1013
1014 39
                            $conditionals = [];
1015 39
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
1016 1
                                foreach ($xmlSheet->conditionalFormatting as $conditional) {
1017 1
                                    foreach ($conditional->cfRule as $cfRule) {
1018 1
                                        if (((string) $cfRule['type'] == Conditional::CONDITION_NONE || (string) $cfRule['type'] == Conditional::CONDITION_CELLIS || (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSTEXT || (string) $cfRule['type'] == Conditional::CONDITION_EXPRESSION) && isset($dxfs[(int) ($cfRule['dxfId'])])) {
1019 1
                                            $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
1020
                                        }
1021
                                    }
1022
                                }
1023
1024 1
                                foreach ($conditionals as $ref => $cfRules) {
1025 1
                                    ksort($cfRules);
1026 1
                                    $conditionalStyles = [];
1027 1
                                    foreach ($cfRules as $cfRule) {
1028 1
                                        $objConditional = new Conditional();
1029 1
                                        $objConditional->setConditionType((string) $cfRule['type']);
1030 1
                                        $objConditional->setOperatorType((string) $cfRule['operator']);
1031
1032 1
                                        if ((string) $cfRule['text'] != '') {
1033
                                            $objConditional->setText((string) $cfRule['text']);
1034
                                        }
1035
1036 1
                                        if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
1037 1
                                            $objConditional->setStopIfTrue(true);
1038
                                        }
1039
1040 1
                                        if (count($cfRule->formula) > 1) {
1041
                                            foreach ($cfRule->formula as $formula) {
1042
                                                $objConditional->addCondition((string) $formula);
1043
                                            }
1044
                                        } else {
1045 1
                                            $objConditional->addCondition((string) $cfRule->formula);
1046
                                        }
1047 1
                                        $objConditional->setStyle(clone $dxfs[(int) ($cfRule['dxfId'])]);
1048 1
                                        $conditionalStyles[] = $objConditional;
1049
                                    }
1050
1051
                                    // Extract all cell references in $ref
1052 1
                                    $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
1053 1
                                    foreach ($cellBlocks as $cellBlock) {
1054 1
                                        $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
1055
                                    }
1056
                                }
1057
                            }
1058
1059 39
                            $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
1060 39
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1061 33
                                foreach ($aKeys as $key) {
1062 33
                                    $method = 'set' . ucfirst($key);
1063 33
                                    $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
1064
                                }
1065
                            }
1066
1067 39
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1068 33
                                $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true);
1069 33
                                if ($xmlSheet->protectedRanges->protectedRange) {
1070 2
                                    foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
1071 2
                                        $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
1072
                                    }
1073
                                }
1074
                            }
1075
1076 39
                            if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
1077
                                $autoFilterRange = (string) $xmlSheet->autoFilter['ref'];
1078
                                if (strpos($autoFilterRange, ':') !== false) {
1079
                                    $autoFilter = $docSheet->getAutoFilter();
1080
                                    $autoFilter->setRange($autoFilterRange);
1081
1082
                                    foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
1083
                                        $column = $autoFilter->getColumnByOffset((int) $filterColumn['colId']);
1084
                                        //    Check for standard filters
1085
                                        if ($filterColumn->filters) {
1086
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
1087
                                            $filters = $filterColumn->filters;
1088
                                            if ((isset($filters['blank'])) && ($filters['blank'] == 1)) {
1089
                                                //    Operator is undefined, but always treated as EQUAL
1090
                                                $column->createRule()->setRule(null, '')->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1091
                                            }
1092
                                            //    Standard filters are always an OR join, so no join rule needs to be set
1093
                                            //    Entries can be either filter elements
1094
                                            foreach ($filters->filter as $filterRule) {
1095
                                                //    Operator is undefined, but always treated as EQUAL
1096
                                                $column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1097
                                            }
1098
                                            //    Or Date Group elements
1099
                                            foreach ($filters->dateGroupItem as $dateGroupItem) {
1100
                                                //    Operator is undefined, but always treated as EQUAL
1101
                                                $column->createRule()->setRule(
1102
                                                    null,
1103
                                                    [
1104
                                                        'year' => (string) $dateGroupItem['year'],
1105
                                                        'month' => (string) $dateGroupItem['month'],
1106
                                                        'day' => (string) $dateGroupItem['day'],
1107
                                                        'hour' => (string) $dateGroupItem['hour'],
1108
                                                        'minute' => (string) $dateGroupItem['minute'],
1109
                                                        'second' => (string) $dateGroupItem['second'],
1110
                                                    ],
1111
                                                    (string) $dateGroupItem['dateTimeGrouping']
1112
                                                )
1113
                                                    ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP);
1114
                                            }
1115
                                        }
1116
                                        //    Check for custom filters
1117
                                        if ($filterColumn->customFilters) {
1118
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
1119
                                            $customFilters = $filterColumn->customFilters;
1120
                                            //    Custom filters can an AND or an OR join;
1121
                                            //        and there should only ever be one or two entries
1122
                                            if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
1123
                                                $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
1124
                                            }
1125
                                            foreach ($customFilters->customFilter as $filterRule) {
1126
                                                $column->createRule()->setRule(
1127
                                                    (string) $filterRule['operator'],
1128
                                                    (string) $filterRule['val']
1129
                                                )
1130
                                                    ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
1131
                                            }
1132
                                        }
1133
                                        //    Check for dynamic filters
1134
                                        if ($filterColumn->dynamicFilter) {
1135
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
1136
                                            //    We should only ever have one dynamic filter
1137
                                            foreach ($filterColumn->dynamicFilter as $filterRule) {
1138
                                                //    Operator is undefined, but always treated as EQUAL
1139
                                                $column->createRule()->setRule(
1140
                                                    null,
1141
                                                    (string) $filterRule['val'],
1142
                                                    (string) $filterRule['type']
1143
                                                )
1144
                                                    ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
1145
                                                if (isset($filterRule['val'])) {
1146
                                                    $column->setAttribute('val', (string) $filterRule['val']);
1147
                                                }
1148
                                                if (isset($filterRule['maxVal'])) {
1149
                                                    $column->setAttribute('maxVal', (string) $filterRule['maxVal']);
1150
                                                }
1151
                                            }
1152
                                        }
1153
                                        //    Check for dynamic filters
1154
                                        if ($filterColumn->top10) {
1155
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
1156
                                            //    We should only ever have one top10 filter
1157
                                            foreach ($filterColumn->top10 as $filterRule) {
1158
                                                $column->createRule()->setRule(
1159
                                                    (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
1160
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
1161
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
1162
                                                    ),
1163
                                                    (string) $filterRule['val'],
1164
                                                    (((isset($filterRule['top'])) && ($filterRule['top'] == 1))
1165
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
1166
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
1167
                                                    )
1168
                                                )
1169
                                                    ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
1170
                                            }
1171
                                        }
1172
                                    }
1173
                                }
1174
                            }
1175
1176 39
                            if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
1177 6
                                foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
1178 6
                                    $mergeRef = (string) $mergeCell['ref'];
1179 6
                                    if (strpos($mergeRef, ':') !== false) {
1180 6
                                        $docSheet->mergeCells((string) $mergeCell['ref']);
1181
                                    }
1182
                                }
1183
                            }
1184
1185 39
                            if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) {
1186 37
                                $docPageMargins = $docSheet->getPageMargins();
1187 37
                                $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
1188 37
                                $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
1189 37
                                $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
1190 37
                                $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
1191 37
                                $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
1192 37
                                $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
1193
                            }
1194
1195 39
                            if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) {
1196 37
                                $docPageSetup = $docSheet->getPageSetup();
1197
1198 37
                                if (isset($xmlSheet->pageSetup['orientation'])) {
1199 37
                                    $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
1200
                                }
1201 37
                                if (isset($xmlSheet->pageSetup['paperSize'])) {
1202 34
                                    $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
1203
                                }
1204 37
                                if (isset($xmlSheet->pageSetup['scale'])) {
1205 30
                                    $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
1206
                                }
1207 37
                                if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
1208 30
                                    $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
1209
                                }
1210 37
                                if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
1211 30
                                    $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
1212
                                }
1213 37
                                if (isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) &&
1214 37
                                    self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) {
1215
                                    $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
1216
                                }
1217
1218 37
                                $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1219 37
                                if (isset($relAttributes['id'])) {
1220 7
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id'];
1221
                                }
1222
                            }
1223
1224 39
                            if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) {
1225 32
                                $docHeaderFooter = $docSheet->getHeaderFooter();
1226
1227 32
                                if (isset($xmlSheet->headerFooter['differentOddEven']) &&
1228 32
                                    self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) {
1229
                                    $docHeaderFooter->setDifferentOddEven(true);
1230
                                } else {
1231 32
                                    $docHeaderFooter->setDifferentOddEven(false);
1232
                                }
1233 32
                                if (isset($xmlSheet->headerFooter['differentFirst']) &&
1234 32
                                    self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) {
1235
                                    $docHeaderFooter->setDifferentFirst(true);
1236
                                } else {
1237 32
                                    $docHeaderFooter->setDifferentFirst(false);
1238
                                }
1239 32
                                if (isset($xmlSheet->headerFooter['scaleWithDoc']) &&
1240 32
                                    !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) {
1241
                                    $docHeaderFooter->setScaleWithDocument(false);
1242
                                } else {
1243 32
                                    $docHeaderFooter->setScaleWithDocument(true);
1244
                                }
1245 32
                                if (isset($xmlSheet->headerFooter['alignWithMargins']) &&
1246 32
                                    !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) {
1247 3
                                    $docHeaderFooter->setAlignWithMargins(false);
1248
                                } else {
1249 29
                                    $docHeaderFooter->setAlignWithMargins(true);
1250
                                }
1251
1252 32
                                $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
1253 32
                                $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
1254 32
                                $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
1255 32
                                $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
1256 32
                                $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
1257 32
                                $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
1258
                            }
1259
1260 39
                            if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) {
1261
                                foreach ($xmlSheet->rowBreaks->brk as $brk) {
1262
                                    if ($brk['man']) {
1263
                                        $docSheet->setBreak("A$brk[id]", Worksheet::BREAK_ROW);
1264
                                    }
1265
                                }
1266
                            }
1267 39
                            if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) {
1268
                                foreach ($xmlSheet->colBreaks->brk as $brk) {
1269
                                    if ($brk['man']) {
1270
                                        $docSheet->setBreak(Coordinate::stringFromColumnIndex((string) $brk['id'] + 1) . '1', Worksheet::BREAK_COLUMN);
1271
                                    }
1272
                                }
1273
                            }
1274
1275 39
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
1276
                                foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
1277
                                    // Uppercase coordinate
1278
                                    $range = strtoupper($dataValidation['sqref']);
1279
                                    $rangeSet = explode(' ', $range);
1280
                                    foreach ($rangeSet as $range) {
1281
                                        $stRange = $docSheet->shrinkRangeToFit($range);
1282
1283
                                        // Extract all cell references in $range
1284
                                        foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) {
1285
                                            // Create validation
1286
                                            $docValidation = $docSheet->getCell($reference)->getDataValidation();
1287
                                            $docValidation->setType((string) $dataValidation['type']);
1288
                                            $docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
1289
                                            $docValidation->setOperator((string) $dataValidation['operator']);
1290
                                            $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
1291
                                            $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
1292
                                            $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
1293
                                            $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
1294
                                            $docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
1295
                                            $docValidation->setError((string) $dataValidation['error']);
1296
                                            $docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
1297
                                            $docValidation->setPrompt((string) $dataValidation['prompt']);
1298
                                            $docValidation->setFormula1((string) $dataValidation->formula1);
1299
                                            $docValidation->setFormula2((string) $dataValidation->formula2);
1300
                                        }
1301
                                    }
1302
                                }
1303
                            }
1304
1305
                            // unparsed sheet AlternateContent
1306 39
                            if ($xmlSheet && !$this->readDataOnly) {
1307 39
                                $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
1308 39
                                if ($mc->AlternateContent) {
1309 1
                                    foreach ($mc->AlternateContent as $alternateContent) {
1310 1
                                        $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
1311
                                    }
1312
                                }
1313
                            }
1314
1315
                            // Add hyperlinks
1316 39
                            $hyperlinks = [];
1317 39
                            if (!$this->readDataOnly) {
1318
                                // Locate hyperlink relations
1319 39
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1320
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1321 37
                                    $relsWorksheet = simplexml_load_string(
1322 37
                                        $this->securityScanner->scan(
1323 37
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1324
                                        ),
1325 37
                                        'SimpleXMLElement',
1326 37
                                        Settings::getLibXmlLoaderOptions()
1327
                                    );
1328 37
                                    foreach ($relsWorksheet->Relationship as $ele) {
1329 12
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1330 2
                                            $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1331
                                        }
1332
                                    }
1333
                                }
1334
1335
                                // Loop through hyperlinks
1336 39
                                if ($xmlSheet && $xmlSheet->hyperlinks) {
1337
                                    /** @var SimpleXMLElement $hyperlink */
1338 2
                                    foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
1339
                                        // Link url
1340 2
                                        $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1341
1342 2
                                        foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
1343 2
                                            $cell = $docSheet->getCell($cellReference);
1344 2
                                            if (isset($linkRel['id'])) {
1345 2
                                                $hyperlinkUrl = $hyperlinks[(string) $linkRel['id']];
1346 2
                                                if (isset($hyperlink['location'])) {
1347
                                                    $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
1348
                                                }
1349 2
                                                $cell->getHyperlink()->setUrl($hyperlinkUrl);
1350 2
                                            } elseif (isset($hyperlink['location'])) {
1351 2
                                                $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
1352
                                            }
1353
1354
                                            // Tooltip
1355 2
                                            if (isset($hyperlink['tooltip'])) {
1356 2
                                                $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
1357
                                            }
1358
                                        }
1359
                                    }
1360
                                }
1361
                            }
1362
1363
                            // Add comments
1364 39
                            $comments = [];
1365 39
                            $vmlComments = [];
1366 39
                            if (!$this->readDataOnly) {
1367
                                // Locate comment relations
1368 39
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1369
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1370 37
                                    $relsWorksheet = simplexml_load_string(
1371 37
                                        $this->securityScanner->scan(
1372 37
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1373
                                        ),
1374 37
                                        'SimpleXMLElement',
1375 37
                                        Settings::getLibXmlLoaderOptions()
1376
                                    );
1377 37
                                    foreach ($relsWorksheet->Relationship as $ele) {
1378 12
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
1379 3
                                            $comments[(string) $ele['Id']] = (string) $ele['Target'];
1380
                                        }
1381 12
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1382 4
                                            $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
1383
                                        }
1384
                                    }
1385
                                }
1386
1387
                                // Loop through comments
1388 39
                                foreach ($comments as $relName => $relPath) {
1389
                                    // Load comments file
1390 3
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1391 3
                                    $commentsFile = simplexml_load_string(
1392 3
                                        $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)),
1393 3
                                        'SimpleXMLElement',
1394 3
                                        Settings::getLibXmlLoaderOptions()
1395
                                    );
1396
1397
                                    // Utility variables
1398 3
                                    $authors = [];
1399
1400
                                    // Loop through authors
1401 3
                                    foreach ($commentsFile->authors->author as $author) {
1402 3
                                        $authors[] = (string) $author;
1403
                                    }
1404
1405
                                    // Loop through contents
1406 3
                                    foreach ($commentsFile->commentList->comment as $comment) {
1407 3
                                        if (!empty($comment['authorId'])) {
1408
                                            $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]);
1409
                                        }
1410 3
                                        $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text));
1411
                                    }
1412
                                }
1413
1414
                                // later we will remove from it real vmlComments
1415 39
                                $unparsedVmlDrawings = $vmlComments;
1416
1417
                                // Loop through VML comments
1418 39
                                foreach ($vmlComments as $relName => $relPath) {
1419
                                    // Load VML comments file
1420 4
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1421 4
                                    $vmlCommentsFile = simplexml_load_string(
1422 4
                                        $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)),
1423 4
                                        'SimpleXMLElement',
1424 4
                                        Settings::getLibXmlLoaderOptions()
1425
                                    );
1426 4
                                    $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1427
1428 4
                                    $shapes = $vmlCommentsFile->xpath('//v:shape');
1429 4
                                    foreach ($shapes as $shape) {
1430 4
                                        $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1431
1432 4
                                        if (isset($shape['style'])) {
1433 4
                                            $style = (string) $shape['style'];
1434 4
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
1435 4
                                            $column = null;
1436 4
                                            $row = null;
1437
1438 4
                                            $clientData = $shape->xpath('.//x:ClientData');
1439 4
                                            if (is_array($clientData) && !empty($clientData)) {
1440 4
                                                $clientData = $clientData[0];
1441
1442 4
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
1443 3
                                                    $temp = $clientData->xpath('.//x:Row');
1444 3
                                                    if (is_array($temp)) {
1445 3
                                                        $row = $temp[0];
1446
                                                    }
1447
1448 3
                                                    $temp = $clientData->xpath('.//x:Column');
1449 3
                                                    if (is_array($temp)) {
1450 3
                                                        $column = $temp[0];
1451
                                                    }
1452
                                                }
1453
                                            }
1454
1455 4
                                            if (($column !== null) && ($row !== null)) {
1456
                                                // Set comment properties
1457 3
                                                $comment = $docSheet->getCommentByColumnAndRow($column + 1, $row + 1);
1458 3
                                                $comment->getFillColor()->setRGB($fillColor);
1459
1460
                                                // Parse style
1461 3
                                                $styleArray = explode(';', str_replace(' ', '', $style));
1462 3
                                                foreach ($styleArray as $stylePair) {
1463 3
                                                    $stylePair = explode(':', $stylePair);
1464
1465 3
                                                    if ($stylePair[0] == 'margin-left') {
1466 3
                                                        $comment->setMarginLeft($stylePair[1]);
1467
                                                    }
1468 3
                                                    if ($stylePair[0] == 'margin-top') {
1469 3
                                                        $comment->setMarginTop($stylePair[1]);
1470
                                                    }
1471 3
                                                    if ($stylePair[0] == 'width') {
1472 3
                                                        $comment->setWidth($stylePair[1]);
1473
                                                    }
1474 3
                                                    if ($stylePair[0] == 'height') {
1475 3
                                                        $comment->setHeight($stylePair[1]);
1476
                                                    }
1477 3
                                                    if ($stylePair[0] == 'visibility') {
1478 3
                                                        $comment->setVisible($stylePair[1] == 'visible');
1479
                                                    }
1480
                                                }
1481
1482 3
                                                unset($unparsedVmlDrawings[$relName]);
1483
                                            }
1484
                                        }
1485
                                    }
1486
                                }
1487
1488
                                // unparsed vmlDrawing
1489 39
                                if ($unparsedVmlDrawings) {
1490 1
                                    foreach ($unparsedVmlDrawings as $rId => $relPath) {
1491 1
                                        $rId = substr($rId, 3); // rIdXXX
1492 1
                                        $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
1493 1
                                        $unparsedVmlDrawing[$rId] = [];
1494 1
                                        $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
1495 1
                                        $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
1496 1
                                        $unparsedVmlDrawing[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
1497 1
                                        unset($unparsedVmlDrawing);
1498
                                    }
1499
                                }
1500
1501
                                // Header/footer images
1502 39
                                if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
1503
                                    if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1504
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1505
                                        $relsWorksheet = simplexml_load_string(
1506
                                            $this->securityScanner->scan(
1507
                                                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1508
                                            ),
1509
                                            'SimpleXMLElement',
1510
                                            Settings::getLibXmlLoaderOptions()
1511
                                        );
1512
                                        $vmlRelationship = '';
1513
1514
                                        foreach ($relsWorksheet->Relationship as $ele) {
1515
                                            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1516
                                                $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1517
                                            }
1518
                                        }
1519
1520
                                        if ($vmlRelationship != '') {
1521
                                            // Fetch linked images
1522
                                            //~ http://schemas.openxmlformats.org/package/2006/relationships"
1523
                                            $relsVML = simplexml_load_string(
1524
                                                $this->securityScanner->scan(
1525
                                                    $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
1526
                                                ),
1527
                                                'SimpleXMLElement',
1528
                                                Settings::getLibXmlLoaderOptions()
1529
                                            );
1530
                                            $drawings = [];
1531
                                            foreach ($relsVML->Relationship as $ele) {
1532
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1533
                                                    $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
1534
                                                }
1535
                                            }
1536
1537
                                            // Fetch VML document
1538
                                            $vmlDrawing = simplexml_load_string(
1539
                                                $this->securityScanner->scan($this->getFromZipArchive($zip, $vmlRelationship)),
1540
                                                'SimpleXMLElement',
1541
                                                Settings::getLibXmlLoaderOptions()
1542
                                            );
1543
                                            $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1544
1545
                                            $hfImages = [];
1546
1547
                                            $shapes = $vmlDrawing->xpath('//v:shape');
1548
                                            foreach ($shapes as $idx => $shape) {
1549
                                                $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1550
                                                $imageData = $shape->xpath('//v:imagedata');
1551
1552
                                                if (!$imageData) {
1553
                                                    continue;
1554
                                                }
1555
1556
                                                $imageData = $imageData[$idx];
1557
1558
                                                $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
1559
                                                $style = self::toCSSArray((string) $shape['style']);
1560
1561
                                                $hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
1562
                                                if (isset($imageData['title'])) {
1563
                                                    $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
1564
                                                }
1565
1566
                                                $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
1567
                                                $hfImages[(string) $shape['id']]->setResizeProportional(false);
1568
                                                $hfImages[(string) $shape['id']]->setWidth($style['width']);
1569
                                                $hfImages[(string) $shape['id']]->setHeight($style['height']);
1570
                                                if (isset($style['margin-left'])) {
1571
                                                    $hfImages[(string) $shape['id']]->setOffsetX($style['margin-left']);
1572
                                                }
1573
                                                $hfImages[(string) $shape['id']]->setOffsetY($style['margin-top']);
1574
                                                $hfImages[(string) $shape['id']]->setResizeProportional(true);
1575
                                            }
1576
1577
                                            $docSheet->getHeaderFooter()->setImages($hfImages);
1578
                                        }
1579
                                    }
1580
                                }
1581
                            }
1582
1583
                            // TODO: Autoshapes from twoCellAnchors!
1584 39
                            if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1585
                                //~ http://schemas.openxmlformats.org/package/2006/relationships"
1586 37
                                $relsWorksheet = simplexml_load_string(
1587 37
                                    $this->securityScanner->scan(
1588 37
                                        $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1589
                                    ),
1590 37
                                    'SimpleXMLElement',
1591 37
                                    Settings::getLibXmlLoaderOptions()
1592
                                );
1593 37
                                $drawings = [];
1594 37
                                foreach ($relsWorksheet->Relationship as $ele) {
1595 12
                                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1596 7
                                        $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1597
                                    }
1598
                                }
1599 37
                                if ($xmlSheet->drawing && !$this->readDataOnly) {
1600 7
                                    foreach ($xmlSheet->drawing as $drawing) {
1601 7
                                        $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
1602
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1603 7
                                        $relsDrawing = simplexml_load_string(
1604 7
                                            $this->securityScanner->scan(
1605 7
                                                $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
1606
                                            ),
1607 7
                                            'SimpleXMLElement',
1608 7
                                            Settings::getLibXmlLoaderOptions()
1609
                                        );
1610 7
                                        $images = [];
1611 7
                                        $hyperlinks = [];
1612 7
                                        if ($relsDrawing && $relsDrawing->Relationship) {
1613 6
                                            foreach ($relsDrawing->Relationship as $ele) {
1614 6
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1615 2
                                                    $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1616
                                                }
1617 6
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1618 6
                                                    $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
1619 4
                                                } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
1620 2
                                                    if ($this->includeCharts) {
1621 2
                                                        $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
1622 2
                                                            'id' => (string) $ele['Id'],
1623 2
                                                            'sheet' => $docSheet->getTitle(),
1624
                                                        ];
1625
                                                    }
1626
                                                }
1627
                                            }
1628
                                        }
1629 7
                                        $xmlDrawing = simplexml_load_string(
1630 7
                                            $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)),
1631 7
                                            'SimpleXMLElement',
1632 7
                                            Settings::getLibXmlLoaderOptions()
1633 7
                                        )->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
1634
1635 7
                                        if ($xmlDrawing->oneCellAnchor) {
1636 4
                                            foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
1637 4
                                                if ($oneCellAnchor->pic->blipFill) {
1638
                                                    /** @var SimpleXMLElement $blip */
1639 4
                                                    $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1640
                                                    /** @var SimpleXMLElement $xfrm */
1641 4
                                                    $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1642
                                                    /** @var SimpleXMLElement $outerShdw */
1643 4
                                                    $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1644
                                                    /** @var \SimpleXMLElement $hlinkClick */
1645 4
                                                    $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
1646
1647 4
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1648 4
                                                    $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1649 4
                                                    $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1650 4
                                                    $objDrawing->setPath(
1651 4
                                                        'zip://' . File::realpath($pFilename) . '#' .
1652 4
                                                        $images[(string) self::getArrayItem(
1653 4
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1654 4
                                                            'embed'
1655
                                                        )],
1656 4
                                                        false
1657
                                                    );
1658 4
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
1659 4
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
1660 4
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
1661 4
                                                    $objDrawing->setResizeProportional(false);
1662 4
                                                    $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
1663 4
                                                    $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
1664 4
                                                    if ($xfrm) {
1665 4
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
1 ignored issue
show
It seems like self::getArrayItem($xfrm->attributes(), 'rot') can also be of type SimpleXMLElement; however, parameter $pValue of PhpOffice\PhpSpreadsheet...awing::angleToDegrees() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1665
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(/** @scrutinizer ignore-type */ self::getArrayItem($xfrm->attributes(), 'rot')));
Loading history...
1666
                                                    }
1667 4
                                                    if ($outerShdw) {
1668 2
                                                        $shadow = $objDrawing->getShadow();
1669 2
                                                        $shadow->setVisible(true);
1670 2
                                                        $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
1 ignored issue
show
It seems like self::getArrayItem($oute...ttributes(), 'blurRad') can also be of type SimpleXMLElement; however, parameter $pValue of PhpOffice\PhpSpreadsheet...\Drawing::EMUToPixels() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1670
                                                        $shadow->setBlurRadius(Drawing::EMUToPixels(/** @scrutinizer ignore-type */ self::getArrayItem($outerShdw->attributes(), 'blurRad')));
Loading history...
1671 2
                                                        $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
1672 2
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
1673 2
                                                        $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
1674 2
                                                        $clr = isset($outerShdw->srgbClr) ? $outerShdw->srgbClr : $outerShdw->prstClr;
1675 2
                                                        $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val'));
1676 2
                                                        $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000);
1677
                                                    }
1678
1679 4
                                                    $this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks);
1680
1681 4
                                                    $objDrawing->setWorksheet($docSheet);
1682
                                                } else {
1683
                                                    //    ? Can charts be positioned with a oneCellAnchor ?
1684
                                                    $coordinates = Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1);
1685
                                                    $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff);
0 ignored issues
show
The assignment to $offsetX is dead and can be removed.
Loading history...
1686
                                                    $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
0 ignored issues
show
The assignment to $offsetY is dead and can be removed.
Loading history...
1687
                                                    $width = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx'));
0 ignored issues
show
The assignment to $width is dead and can be removed.
Loading history...
1688
                                                    $height = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy'));
0 ignored issues
show
The assignment to $height is dead and can be removed.
Loading history...
1689
                                                }
1690
                                            }
1691
                                        }
1692 7
                                        if ($xmlDrawing->twoCellAnchor) {
1693 2
                                            foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) {
1694 2
                                                if ($twoCellAnchor->pic->blipFill) {
1695 2
                                                    $blip = $twoCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1696 2
                                                    $xfrm = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1697 2
                                                    $outerShdw = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1698 2
                                                    $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
1699 2
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1700 2
                                                    $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1701 2
                                                    $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1702 2
                                                    $objDrawing->setPath(
1703 2
                                                        'zip://' . File::realpath($pFilename) . '#' .
1704 2
                                                        $images[(string) self::getArrayItem(
1705 2
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1706 2
                                                            'embed'
1707
                                                        )],
1708 2
                                                        false
1709
                                                    );
1710 2
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1));
1711 2
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff));
1712 2
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
1713 2
                                                    $objDrawing->setResizeProportional(false);
1714
1715 2
                                                    if ($xfrm) {
1716 2
                                                        $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cx')));
1717 2
                                                        $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cy')));
1718 2
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
1719
                                                    }
1720 2
                                                    if ($outerShdw) {
1721
                                                        $shadow = $objDrawing->getShadow();
1722
                                                        $shadow->setVisible(true);
1723
                                                        $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
1724
                                                        $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
1725
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
1726
                                                        $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
1727
                                                        $clr = isset($outerShdw->srgbClr) ? $outerShdw->srgbClr : $outerShdw->prstClr;
1728
                                                        $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val'));
1729
                                                        $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000);
1730
                                                    }
1731
1732 2
                                                    $this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks);
1733
1734 2
                                                    $objDrawing->setWorksheet($docSheet);
1735 2
                                                } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
1736 2
                                                    $fromCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
1737 2
                                                    $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff);
1738 2
                                                    $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
1739 2
                                                    $toCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
1740 2
                                                    $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff);
1741 2
                                                    $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
1742 2
                                                    $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic;
1743
                                                    /** @var SimpleXMLElement $chartRef */
1744 2
                                                    $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart;
1745 2
                                                    $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1746
1747 2
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1748 2
                                                        'fromCoordinate' => $fromCoordinate,
1749 2
                                                        'fromOffsetX' => $fromOffsetX,
1750 2
                                                        'fromOffsetY' => $fromOffsetY,
1751 2
                                                        'toCoordinate' => $toCoordinate,
1752 2
                                                        'toOffsetX' => $toOffsetX,
1753 2
                                                        'toOffsetY' => $toOffsetY,
1754 2
                                                        'worksheetTitle' => $docSheet->getTitle(),
1755
                                                    ];
1756
                                                }
1757
                                            }
1758
                                        }
1759
                                    }
1760
1761
                                    // store original rId of drawing files
1762 7
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = [];
1763 7
                                    foreach ($relsWorksheet->Relationship as $ele) {
1764 7
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1765 7
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = (string) $ele['Id'];
1766
                                        }
1767
                                    }
1768
1769
                                    // unparsed drawing AlternateContent
1770 7
                                    $xmlAltDrawing = simplexml_load_string(
1771 7
                                        $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)),
1772 7
                                        'SimpleXMLElement',
1773 7
                                        Settings::getLibXmlLoaderOptions()
1774 7
                                    )->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
1775
1776 7
                                    if ($xmlAltDrawing->AlternateContent) {
1777 1
                                        foreach ($xmlAltDrawing->AlternateContent as $alternateContent) {
1778 1
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML();
1779
                                        }
1780
                                    }
1781
                                }
1782
                            }
1783
1784 39
                            $this->readFormControlProperties($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1785 39
                            $this->readPrinterSettings($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1786
1787
                            // Loop through definedNames
1788 39
                            if ($xmlWorkbook->definedNames) {
1789 30
                                foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1790
                                    // Extract range
1791 2
                                    $extractedRange = (string) $definedName;
1792 2
                                    if (($spos = strpos($extractedRange, '!')) !== false) {
1793 2
                                        $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1794
                                    } else {
1795
                                        $extractedRange = str_replace('$', '', $extractedRange);
1796
                                    }
1797
1798
                                    // Valid range?
1799 2
                                    if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') {
1800
                                        continue;
1801
                                    }
1802
1803
                                    // Some definedNames are only applicable if we are on the same sheet...
1804 2
                                    if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) {
1805
                                        // Switch on type
1806 2
                                        switch ((string) $definedName['name']) {
1807 2
                                            case '_xlnm._FilterDatabase':
1808
                                                if ((string) $definedName['hidden'] !== '1') {
1809
                                                    $extractedRange = explode(',', $extractedRange);
1810
                                                    foreach ($extractedRange as $range) {
1811
                                                        $autoFilterRange = $range;
1812
                                                        if (strpos($autoFilterRange, ':') !== false) {
1813
                                                            $docSheet->getAutoFilter()->setRange($autoFilterRange);
1814
                                                        }
1815
                                                    }
1816
                                                }
1817
1818
                                                break;
1819 2
                                            case '_xlnm.Print_Titles':
1820
                                                // Split $extractedRange
1821 1
                                                $extractedRange = explode(',', $extractedRange);
1822
1823
                                                // Set print titles
1824 1
                                                foreach ($extractedRange as $range) {
1825 1
                                                    $matches = [];
1826 1
                                                    $range = str_replace('$', '', $range);
1827
1828
                                                    // check for repeating columns, e g. 'A:A' or 'A:D'
1829 1
                                                    if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
1830
                                                        $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]);
1831 1
                                                    } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
1832
                                                        // check for repeating rows, e.g. '1:1' or '1:5'
1833 1
                                                        $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]);
1834
                                                    }
1835
                                                }
1836
1837 1
                                                break;
1838 1
                                            case '_xlnm.Print_Area':
1839 1
                                                $rangeSets = preg_split("/('?(?:.*?)'?(?:![A-Z0-9]+:[A-Z0-9]+)),?/", $extractedRange, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
1840 1
                                                $newRangeSets = [];
1841 1
                                                foreach ($rangeSets as $rangeSet) {
1842 1
                                                    list($sheetName, $rangeSet) = Worksheet::extractSheetTitle($rangeSet, true);
1843 1
                                                    if (strpos($rangeSet, ':') === false) {
1844
                                                        $rangeSet = $rangeSet . ':' . $rangeSet;
1845
                                                    }
1846 1
                                                    $newRangeSets[] = str_replace('$', '', $rangeSet);
1847
                                                }
1848 1
                                                $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
1849
1850 1
                                                break;
1851
                                            default:
1852
                                                break;
1853
                                        }
1854
                                    }
1855
                                }
1856
                            }
1857
1858
                            // Next sheet id
1859 39
                            ++$sheetId;
1860
                        }
1861
1862
                        // Loop through definedNames
1863 39
                        if ($xmlWorkbook->definedNames) {
1864 30
                            foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1865
                                // Extract range
1866 2
                                $extractedRange = (string) $definedName;
1867 2
                                if (($spos = strpos($extractedRange, '!')) !== false) {
1868 2
                                    $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1869
                                } else {
1870
                                    $extractedRange = str_replace('$', '', $extractedRange);
1871
                                }
1872
1873
                                // Valid range?
1874 2
                                if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') {
1875
                                    continue;
1876
                                }
1877
1878
                                // Some definedNames are only applicable if we are on the same sheet...
1879 2
                                if ((string) $definedName['localSheetId'] != '') {
1880
                                    // Local defined name
1881
                                    // Switch on type
1882 2
                                    switch ((string) $definedName['name']) {
1883 2
                                        case '_xlnm._FilterDatabase':
1884 2
                                        case '_xlnm.Print_Titles':
1885 1
                                        case '_xlnm.Print_Area':
1886 2
                                            break;
1887
                                        default:
1888
                                            if ($mapSheetId[(int) $definedName['localSheetId']] !== null) {
1889
                                                if (strpos((string) $definedName, '!') !== false) {
1890
                                                    $range = Worksheet::extractSheetTitle((string) $definedName, true);
1891
                                                    $range[0] = str_replace("''", "'", $range[0]);
1892
                                                    $range[0] = str_replace("'", '', $range[0]);
1893
                                                    if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) {
1894
                                                        $extractedRange = str_replace('$', '', $range[1]);
1895
                                                        $scope = $docSheet->getParent()->getSheet($mapSheetId[(int) $definedName['localSheetId']]);
1896
                                                        $excel->addNamedRange(new NamedRange((string) $definedName['name'], $worksheet, $extractedRange, true, $scope));
1897
                                                    }
1898
                                                }
1899
                                            }
1900
1901 2
                                            break;
1902
                                    }
1903
                                } elseif (!isset($definedName['localSheetId'])) {
1904
                                    // "Global" definedNames
1905
                                    $locatedSheet = null;
1906
                                    $extractedSheetName = '';
1907
                                    if (strpos((string) $definedName, '!') !== false) {
1908
                                        // Extract sheet name
1909
                                        $extractedSheetName = Worksheet::extractSheetTitle((string) $definedName, true);
1910
                                        $extractedSheetName = $extractedSheetName[0];
1911
1912
                                        // Locate sheet
1913
                                        $locatedSheet = $excel->getSheetByName($extractedSheetName);
1914
1915
                                        // Modify range
1916
                                        list($worksheetName, $extractedRange) = Worksheet::extractSheetTitle($extractedRange, true);
1917
                                    }
1918
1919
                                    if ($locatedSheet !== null) {
1920
                                        $excel->addNamedRange(new NamedRange((string) $definedName['name'], $locatedSheet, $extractedRange, false));
1921
                                    }
1922
                                }
1923
                            }
1924
                        }
1925
                    }
1926
1927 39
                    if ((!$this->readDataOnly) || (!empty($this->loadSheetsOnly))) {
1928 39
                        $workbookView = $xmlWorkbook->bookViews->workbookView;
1929
1930
                        // active sheet index
1931 39
                        $activeTab = (int) ($workbookView['activeTab']); // refers to old sheet index
1932
1933
                        // keep active sheet index if sheet is still loaded, else first sheet is set as the active
1934 39
                        if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
1935 39
                            $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
1936
                        } else {
1937
                            if ($excel->getSheetCount() == 0) {
1938
                                $excel->createSheet();
1939
                            }
1940
                            $excel->setActiveSheetIndex(0);
1941
                        }
1942
1943 39
                        if (isset($workbookView['showHorizontalScroll'])) {
1944 30
                            $showHorizontalScroll = (string) $workbookView['showHorizontalScroll'];
1945 30
                            $excel->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll));
1946
                        }
1947
1948 39
                        if (isset($workbookView['showVerticalScroll'])) {
1949 30
                            $showVerticalScroll = (string) $workbookView['showVerticalScroll'];
1950 30
                            $excel->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll));
1951
                        }
1952
1953 39
                        if (isset($workbookView['showSheetTabs'])) {
1954 30
                            $showSheetTabs = (string) $workbookView['showSheetTabs'];
1955 30
                            $excel->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs));
1956
                        }
1957
1958 39
                        if (isset($workbookView['minimized'])) {
1959 30
                            $minimized = (string) $workbookView['minimized'];
1960 30
                            $excel->setMinimized($this->castXsdBooleanToBool($minimized));
1961
                        }
1962
1963 39
                        if (isset($workbookView['autoFilterDateGrouping'])) {
1964 30
                            $autoFilterDateGrouping = (string) $workbookView['autoFilterDateGrouping'];
1965 30
                            $excel->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping));
1966
                        }
1967
1968 39
                        if (isset($workbookView['firstSheet'])) {
1969 30
                            $firstSheet = (string) $workbookView['firstSheet'];
1970 30
                            $excel->setFirstSheetIndex((int) $firstSheet);
1971
                        }
1972
1973 39
                        if (isset($workbookView['visibility'])) {
1974 30
                            $visibility = (string) $workbookView['visibility'];
1975 30
                            $excel->setVisibility($visibility);
1976
                        }
1977
1978 39
                        if (isset($workbookView['tabRatio'])) {
1979 30
                            $tabRatio = (string) $workbookView['tabRatio'];
1980 30
                            $excel->setTabRatio((int) $tabRatio);
1981
                        }
1982
                    }
1983
1984 39
                    break;
1985
            }
1986
        }
1987
1988 39
        if (!$this->readDataOnly) {
1989 39
            $contentTypes = simplexml_load_string(
1990 39
                $this->securityScanner->scan(
1991 39
                    $this->getFromZipArchive($zip, '[Content_Types].xml')
1992
                ),
1993 39
                'SimpleXMLElement',
1994 39
                Settings::getLibXmlLoaderOptions()
1995
            );
1996
1997
            // Default content types
1998 39
            foreach ($contentTypes->Default as $contentType) {
1999 39
                switch ($contentType['ContentType']) {
2000 39
                    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings':
2001 9
                        $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType'];
2002
2003 9
                        break;
2004
                }
2005
            }
2006
2007
            // Override content types
2008 39
            foreach ($contentTypes->Override as $contentType) {
2009 39
                switch ($contentType['ContentType']) {
2010 39
                    case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
2011 2
                        if ($this->includeCharts) {
2012 2
                            $chartEntryRef = ltrim($contentType['PartName'], '/');
2013 2
                            $chartElements = simplexml_load_string(
2014 2
                                $this->securityScanner->scan(
2015 2
                                    $this->getFromZipArchive($zip, $chartEntryRef)
2016
                                ),
2017 2
                                'SimpleXMLElement',
2018 2
                                Settings::getLibXmlLoaderOptions()
2019
                            );
2020 2
                            $objChart = Chart::readChart($chartElements, basename($chartEntryRef, '.xml'));
1 ignored issue
show
It seems like $chartElements can also be of type false; however, parameter $chartElements of PhpOffice\PhpSpreadsheet...Xlsx\Chart::readChart() does only seem to accept SimpleXMLElement, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2020
                            $objChart = Chart::readChart(/** @scrutinizer ignore-type */ $chartElements, basename($chartEntryRef, '.xml'));
Loading history...
2021
2022 2
                            if (isset($charts[$chartEntryRef])) {
2023 2
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
2024 2
                                if (isset($chartDetails[$chartPositionRef])) {
2025 2
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
2026 2
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
2027 2
                                    $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
2028 2
                                    $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
2029
                                }
2030
                            }
2031
                        }
2032
2033 2
                        break;
2034
2035
                    // unparsed
2036 39
                    case 'application/vnd.ms-excel.controlproperties+xml':
2037 1
                        $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
2038
2039 1
                        break;
2040
                }
2041
            }
2042
        }
2043
2044 39
        $excel->setUnparsedLoadedData($unparsedLoadedData);
2045
2046 39
        $zip->close();
2047
2048 39
        return $excel;
2049
    }
2050
2051 39
    private static function readColor($color, $background = false)
2052
    {
2053 39
        if (isset($color['rgb'])) {
2054 34
            return (string) $color['rgb'];
2055 11
        } elseif (isset($color['indexed'])) {
2056 8
            return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
2057 8
        } elseif (isset($color['theme'])) {
2058 7
            if (self::$theme !== null) {
2059 7
                $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
2060 7
                if (isset($color['tint'])) {
2061 2
                    $tintAdjust = (float) $color['tint'];
2062 2
                    $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
2063
                }
2064
2065 7
                return 'FF' . $returnColour;
2066
            }
2067
        }
2068
2069 3
        if ($background) {
2070
            return 'FFFFFFFF';
2071
        }
2072
2073 3
        return 'FF000000';
2074
    }
2075
2076
    /**
2077
     * @param Style $docStyle
2078
     * @param SimpleXMLElement|\stdClass $style
2079
     */
2080 39
    private static function readStyle(Style $docStyle, $style)
2081
    {
2082 39
        $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
2083
2084
        // font
2085 39
        if (isset($style->font)) {
2086 39
            $docStyle->getFont()->setName((string) $style->font->name['val']);
2087 39
            $docStyle->getFont()->setSize((string) $style->font->sz['val']);
2088 39
            if (isset($style->font->b)) {
2089 35
                $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val']));
2090
            }
2091 39
            if (isset($style->font->i)) {
2092 32
                $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val']));
2093
            }
2094 39
            if (isset($style->font->strike)) {
2095 30
                $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val']));
2096
            }
2097 39
            $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color));
2098
2099 39
            if (isset($style->font->u) && !isset($style->font->u['val'])) {
2100
                $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2101 39
            } elseif (isset($style->font->u, $style->font->u['val'])) {
2102 30
                $docStyle->getFont()->setUnderline((string) $style->font->u['val']);
2103
            }
2104
2105 39
            if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) {
2106
                $vertAlign = strtolower((string) $style->font->vertAlign['val']);
2107
                if ($vertAlign == 'superscript') {
2108
                    $docStyle->getFont()->setSuperscript(true);
2109
                }
2110
                if ($vertAlign == 'subscript') {
2111
                    $docStyle->getFont()->setSubscript(true);
2112
                }
2113
            }
2114
        }
2115
2116
        // fill
2117 39
        if (isset($style->fill)) {
2118 39
            if ($style->fill->gradientFill) {
2119
                /** @var SimpleXMLElement $gradientFill */
2120 2
                $gradientFill = $style->fill->gradientFill[0];
2121 2
                if (!empty($gradientFill['type'])) {
2122 2
                    $docStyle->getFill()->setFillType((string) $gradientFill['type']);
2123
                }
2124 2
                $docStyle->getFill()->setRotation((float) ($gradientFill['degree']));
2125 2
                $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
2126 2
                $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
2127 2
                $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
2128 39
            } elseif ($style->fill->patternFill) {
2129 39
                $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid';
2130 39
                $docStyle->getFill()->setFillType($patternType);
2131 39
                if ($style->fill->patternFill->fgColor) {
2132 5
                    $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true));
2133
                } else {
2134 39
                    $docStyle->getFill()->getStartColor()->setARGB('FF000000');
2135
                }
2136 39
                if ($style->fill->patternFill->bgColor) {
2137 6
                    $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true));
2138
                }
2139
            }
2140
        }
2141
2142
        // border
2143 39
        if (isset($style->border)) {
2144 39
            $diagonalUp = self::boolean((string) $style->border['diagonalUp']);
2145 39
            $diagonalDown = self::boolean((string) $style->border['diagonalDown']);
2146 39
            if (!$diagonalUp && !$diagonalDown) {
2147 39
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
2148
            } elseif ($diagonalUp && !$diagonalDown) {
2149
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
2150
            } elseif (!$diagonalUp && $diagonalDown) {
2151
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
2152
            } else {
2153
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
2154
            }
2155 39
            self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
2156 39
            self::readBorder($docStyle->getBorders()->getRight(), $style->border->right);
2157 39
            self::readBorder($docStyle->getBorders()->getTop(), $style->border->top);
2158 39
            self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
2159 39
            self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
2160
        }
2161
2162
        // alignment
2163 39
        if (isset($style->alignment)) {
2164 39
            $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']);
2165 39
            $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']);
2166
2167 39
            $textRotation = 0;
2168 39
            if ((int) $style->alignment['textRotation'] <= 90) {
2169 39
                $textRotation = (int) $style->alignment['textRotation'];
2170
            } elseif ((int) $style->alignment['textRotation'] > 90) {
2171
                $textRotation = 90 - (int) $style->alignment['textRotation'];
2172
            }
2173
2174 39
            $docStyle->getAlignment()->setTextRotation((int) $textRotation);
2175 39
            $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText']));
2176 39
            $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit']));
2177 39
            $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0);
2178 39
            $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0);
2179
        }
2180
2181
        // protection
2182 39
        if (isset($style->protection)) {
2183 39
            if (isset($style->protection['locked'])) {
2184 2
                if (self::boolean((string) $style->protection['locked'])) {
2185
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
2186
                } else {
2187 2
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
2188
                }
2189
            }
2190
2191 39
            if (isset($style->protection['hidden'])) {
2192
                if (self::boolean((string) $style->protection['hidden'])) {
2193
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
2194
                } else {
2195
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
2196
                }
2197
            }
2198
        }
2199
2200
        // top-level style settings
2201 39
        if (isset($style->quotePrefix)) {
2202 39
            $docStyle->setQuotePrefix($style->quotePrefix);
2203
        }
2204 39
    }
2205
2206
    /**
2207
     * @param Border $docBorder
2208
     * @param SimpleXMLElement $eleBorder
2209
     */
2210 39
    private static function readBorder(Border $docBorder, $eleBorder)
2211
    {
2212 39
        if (isset($eleBorder['style'])) {
2213 4
            $docBorder->setBorderStyle((string) $eleBorder['style']);
2214
        }
2215 39
        if (isset($eleBorder->color)) {
2216 4
            $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
2217
        }
2218 39
    }
2219
2220
    /**
2221
     * @param SimpleXMLElement | null $is
2222
     *
2223
     * @return RichText
2224
     */
2225 4
    private function parseRichText($is)
2226
    {
2227 4
        $value = new RichText();
2228
2229 4
        if (isset($is->t)) {
2230
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
2231
        } else {
2232 4
            if (is_object($is->r)) {
2233 4
                foreach ($is->r as $run) {
2234 4
                    if (!isset($run->rPr)) {
2235 4
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2236
                    } else {
2237 3
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2238
2239 3
                        if (isset($run->rPr->rFont['val'])) {
2240 3
                            $objText->getFont()->setName((string) $run->rPr->rFont['val']);
2241
                        }
2242 3
                        if (isset($run->rPr->sz['val'])) {
2243 3
                            $objText->getFont()->setSize((float) $run->rPr->sz['val']);
2244
                        }
2245 3
                        if (isset($run->rPr->color)) {
2246 3
                            $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
2247
                        }
2248 3
                        if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
2249 3
                            (isset($run->rPr->b) && !isset($run->rPr->b['val']))) {
2250 3
                            $objText->getFont()->setBold(true);
2251
                        }
2252 3
                        if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
2253 3
                            (isset($run->rPr->i) && !isset($run->rPr->i['val']))) {
2254 2
                            $objText->getFont()->setItalic(true);
2255
                        }
2256 3
                        if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
2257
                            $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
2258
                            if ($vertAlign == 'superscript') {
2259
                                $objText->getFont()->setSuperscript(true);
2260
                            }
2261
                            if ($vertAlign == 'subscript') {
2262
                                $objText->getFont()->setSubscript(true);
2263
                            }
2264
                        }
2265 3
                        if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
2266
                            $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2267 3
                        } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
2268 2
                            $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
2269
                        }
2270 3
                        if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
2271 3
                            (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) {
2272
                            $objText->getFont()->setStrikethrough(true);
2273
                        }
2274
                    }
2275
                }
2276
            }
2277
        }
2278
2279 4
        return $value;
2280
    }
2281
2282
    /**
2283
     * @param Spreadsheet $excel
2284
     * @param mixed $customUITarget
2285
     * @param mixed $zip
2286
     */
2287
    private function readRibbon(Spreadsheet $excel, $customUITarget, $zip)
2288
    {
2289
        $baseDir = dirname($customUITarget);
2290
        $nameCustomUI = basename($customUITarget);
2291
        // get the xml file (ribbon)
2292
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
2293
        $customUIImagesNames = [];
2294
        $customUIImagesBinaries = [];
2295
        // something like customUI/_rels/customUI.xml.rels
2296
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
2297
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
2298
        if ($dataRels) {
2299
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
2300
            $UIRels = simplexml_load_string(
2301
                $this->securityScanner->scan($dataRels),
2302
                'SimpleXMLElement',
2303
                Settings::getLibXmlLoaderOptions()
2304
            );
2305
            if (false !== $UIRels) {
2306
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
2307
                foreach ($UIRels->Relationship as $ele) {
2308
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
2309
                        // an image ?
2310
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
2311
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
2312
                    }
2313
                }
2314
            }
2315
        }
2316
        if ($localRibbon) {
2317
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
2318
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2319
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
2320
            } else {
2321
                $excel->setRibbonBinObjects(null, null);
2322
            }
2323
        } else {
2324
            $excel->setRibbonXMLData(null, null);
2325
            $excel->setRibbonBinObjects(null, null);
2326
        }
2327
    }
2328
2329 40
    private static function getArrayItem($array, $key = 0)
2330
    {
2331 40
        return isset($array[$key]) ? $array[$key] : null;
2332
    }
2333
2334 11
    private static function dirAdd($base, $add)
2335
    {
2336 11
        return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
2337
    }
2338
2339
    private static function toCSSArray($style)
2340
    {
2341
        $style = trim(str_replace(["\r", "\n"], '', $style), ';');
2342
2343
        $temp = explode(';', $style);
2344
        $style = [];
2345
        foreach ($temp as $item) {
2346
            $item = explode(':', $item);
2347
2348
            if (strpos($item[1], 'px') !== false) {
2349
                $item[1] = str_replace('px', '', $item[1]);
2350
            }
2351
            if (strpos($item[1], 'pt') !== false) {
2352
                $item[1] = str_replace('pt', '', $item[1]);
2353
                $item[1] = Font::fontSizeToPixels($item[1]);
2354
            }
2355
            if (strpos($item[1], 'in') !== false) {
2356
                $item[1] = str_replace('in', '', $item[1]);
2357
                $item[1] = Font::inchSizeToPixels($item[1]);
2358
            }
2359
            if (strpos($item[1], 'cm') !== false) {
2360
                $item[1] = str_replace('cm', '', $item[1]);
2361
                $item[1] = Font::centimeterSizeToPixels($item[1]);
2362
            }
2363
2364
            $style[$item[0]] = $item[1];
2365
        }
2366
2367
        return $style;
2368
    }
2369
2370 39
    private static function boolean($value)
2371
    {
2372 39
        if (is_object($value)) {
2373 1
            $value = (string) $value;
2374
        }
2375 39
        if (is_numeric($value)) {
2376 36
            return (bool) $value;
2377
        }
2378
2379 39
        return $value === 'true' || $value === 'TRUE';
2380
    }
2381
2382
    /**
2383
     * @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing
2384
     * @param \SimpleXMLElement $cellAnchor
2385
     * @param array $hyperlinks
2386
     */
2387 6
    private function readHyperLinkDrawing($objDrawing, $cellAnchor, $hyperlinks)
2388
    {
2389 6
        $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
2390
2391 6
        if ($hlinkClick->count() === 0) {
2392 4
            return;
2393
        }
2394
2395 2
        $hlinkId = (string) $hlinkClick->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id'];
2396 2
        $hyperlink = new Hyperlink(
2397 2
            $hyperlinks[$hlinkId],
2398 2
            (string) self::getArrayItem($cellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')
2399
        );
2400 2
        $objDrawing->setHyperlink($hyperlink);
2401 2
    }
2402
2403 39
    private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook)
2404
    {
2405 39
        if (!$xmlWorkbook->workbookProtection) {
2406 38
            return;
2407
        }
2408
2409 1
        if ($xmlWorkbook->workbookProtection['lockRevision']) {
2410
            $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']);
2411
        }
2412
2413 1
        if ($xmlWorkbook->workbookProtection['lockStructure']) {
2414 1
            $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']);
2415
        }
2416
2417 1
        if ($xmlWorkbook->workbookProtection['lockWindows']) {
2418
            $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']);
2419
        }
2420
2421 1
        if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
2422
            $excel->getSecurity()->setRevisionsPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true);
2423
        }
2424
2425 1
        if ($xmlWorkbook->workbookProtection['workbookPassword']) {
2426 1
            $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true);
2427
        }
2428 1
    }
2429
2430 39
    private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2431
    {
2432 39
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2433 5
            return;
2434
        }
2435
2436
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2437 37
        $relsWorksheet = simplexml_load_string(
2438 37
            $this->securityScanner->scan(
2439 37
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2440
            ),
2441 37
            'SimpleXMLElement',
2442 37
            Settings::getLibXmlLoaderOptions()
2443
        );
2444 37
        $ctrlProps = [];
2445 37
        foreach ($relsWorksheet->Relationship as $ele) {
2446 12
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') {
2447 1
                $ctrlProps[(string) $ele['Id']] = $ele;
2448
            }
2449
        }
2450
2451 37
        $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
2452 37
        foreach ($ctrlProps as $rId => $ctrlProp) {
2453 1
            $rId = substr($rId, 3); // rIdXXX
2454 1
            $unparsedCtrlProps[$rId] = [];
2455 1
            $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
2456 1
            $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
2457 1
            $unparsedCtrlProps[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
2458
        }
2459 37
        unset($unparsedCtrlProps);
2460 37
    }
2461
2462 39
    private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2463
    {
2464 39
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2465 5
            return;
2466
        }
2467
2468
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2469 37
        $relsWorksheet = simplexml_load_string(
2470 37
            $this->securityScanner->scan(
2471 37
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2472
            ),
2473 37
            'SimpleXMLElement',
2474 37
            Settings::getLibXmlLoaderOptions()
2475
        );
2476 37
        $sheetPrinterSettings = [];
2477 37
        foreach ($relsWorksheet->Relationship as $ele) {
2478 12
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') {
2479 7
                $sheetPrinterSettings[(string) $ele['Id']] = $ele;
2480
            }
2481
        }
2482
2483 37
        $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
2484 37
        foreach ($sheetPrinterSettings as $rId => $printerSettings) {
2485 7
            $rId = substr($rId, 3); // rIdXXX
2486 7
            $unparsedPrinterSettings[$rId] = [];
2487 7
            $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']);
2488 7
            $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target'];
2489 7
            $unparsedPrinterSettings[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
2490
        }
2491 37
        unset($unparsedPrinterSettings);
2492 37
    }
2493
2494
    /**
2495
     * Convert an 'xsd:boolean' XML value to a PHP boolean value.
2496
     * A valid 'xsd:boolean' XML value can be one of the following
2497
     * four values: 'true', 'false', '1', '0'.  It is case sensitive.
2498
     *
2499
     * Note that just doing '(bool) $xsdBoolean' is not safe,
2500
     * since '(bool) "false"' returns true.
2501
     *
2502
     * @see https://www.w3.org/TR/xmlschema11-2/#boolean
2503
     *
2504
     * @param string $xsdBoolean An XML string value of type 'xsd:boolean'
2505
     *
2506
     * @return bool  Boolean value
2507
     */
2508 30
    private function castXsdBooleanToBool($xsdBoolean)
2509
    {
2510 30
        if ($xsdBoolean === 'false') {
2511 30
            return false;
2512
        }
2513
2514 30
        return (bool) $xsdBoolean;
2515
    }
2516
2517
    /**
2518
     * Read columns and rows attributes from XML and set them on the worksheet.
2519
     *
2520
     * @param SimpleXMLElement $xmlSheet
2521
     * @param Worksheet $docSheet
2522
     */
2523 39
    private function readColumnsAndRowsAttributes(SimpleXMLElement $xmlSheet, Worksheet $docSheet)
2524
    {
2525 39
        $columnsAttributes = [];
2526 39
        $rowsAttributes = [];
2527 39
        if (isset($xmlSheet->cols) && !$this->readDataOnly) {
2528 10
            foreach ($xmlSheet->cols->col as $col) {
2529 10
                for ($i = (int) ($col['min']); $i <= (int) ($col['max']); ++$i) {
2530 10
                    if ($col['style'] && !$this->readDataOnly) {
2531 4
                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['xfIndex'] = (int) $col['style'];
2532
                    }
2533 10
                    if (self::boolean($col['hidden'])) {
2534 1
                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['visible'] = false;
2535
                    }
2536 10
                    if (self::boolean($col['collapsed'])) {
2537 1
                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['collapsed'] = true;
2538
                    }
2539 10
                    if ($col['outlineLevel'] > 0) {
2540 1
                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['outlineLevel'] = (int) $col['outlineLevel'];
2541
                    }
2542 10
                    $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['width'] = (float) $col['width'];
2543
2544 10
                    if ((int) ($col['max']) == 16384) {
2545
                        break;
2546
                    }
2547
                }
2548
            }
2549
        }
2550
2551 39
        if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
2552 33
            foreach ($xmlSheet->sheetData->row as $row) {
2553 33
                if ($row['ht'] && !$this->readDataOnly) {
2554 4
                    $rowsAttributes[(int) $row['r']]['rowHeight'] = (float) $row['ht'];
2555
                }
2556 33
                if (self::boolean($row['hidden']) && !$this->readDataOnly) {
2557
                    $rowsAttributes[(int) $row['r']]['visible'] = false;
2558
                }
2559 33
                if (self::boolean($row['collapsed'])) {
2560
                    $rowsAttributes[(int) $row['r']]['collapsed'] = true;
2561
                }
2562 33
                if ($row['outlineLevel'] > 0) {
2563
                    $rowsAttributes[(int) $row['r']]['outlineLevel'] = (int) $row['outlineLevel'];
2564
                }
2565 33
                if ($row['s'] && !$this->readDataOnly) {
2566
                    $rowsAttributes[(int) $row['r']]['xfIndex'] = (int) $row['s'];
2567
                }
2568
            }
2569
        }
2570
2571 39
        $readFilter = (\get_class($this->getReadFilter()) !== DefaultReadFilter::class ? $this->getReadFilter() : null);
2572
2573
        // set columns/rows attributes
2574 39
        $columnsAttributesSet = [];
2575 39
        $rowsAttributesSet = [];
2576 39
        foreach ($columnsAttributes as $coordColumn => $columnAttributes) {
2577 10
            if ($readFilter !== null) {
2578 2
                foreach ($rowsAttributes as $coordRow => $rowAttributes) {
2579 1
                    if (!$readFilter->readCell($coordColumn, $coordRow, $docSheet->getTitle())) {
2580 1
                        continue 2;
2581
                    }
2582
                }
2583
            }
2584
2585 10
            if (!isset($columnsAttributesSet[$coordColumn])) {
2586 10
                $this->setColumnAttributes($docSheet, $coordColumn, $columnAttributes);
2587 10
                $columnsAttributesSet[$coordColumn] = true;
2588
            }
2589
        }
2590
2591 39
        foreach ($rowsAttributes as $coordRow => $rowAttributes) {
2592 4
            if ($readFilter !== null) {
2593 1
                foreach ($columnsAttributes as $coordColumn => $columnAttributes) {
2594 1
                    if (!$readFilter->readCell($coordColumn, $coordRow, $docSheet->getTitle())) {
2595 1
                        continue 2;
2596
                    }
2597
                }
2598
            }
2599
2600 3
            if (!isset($rowsAttributesSet[$coordRow])) {
2601 3
                $this->setRowAttributes($docSheet, $coordRow, $rowAttributes);
2602 3
                $rowsAttributesSet[$coordRow] = true;
2603
            }
2604
        }
2605 39
    }
2606
}
2607