Passed
Push — develop ( 7a4cbd...edb68c )
by Adrien
34:56
created

Xlsx::castXsdBooleanToBool()   A

Complexity

Conditions 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
6
use PhpOffice\PhpSpreadsheet\Document\Properties;
7
use PhpOffice\PhpSpreadsheet\NamedRange;
8
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart;
9
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
10
use PhpOffice\PhpSpreadsheet\RichText\RichText;
11
use PhpOffice\PhpSpreadsheet\Settings;
12
use PhpOffice\PhpSpreadsheet\Shared\Date;
13
use PhpOffice\PhpSpreadsheet\Shared\Drawing;
14
use PhpOffice\PhpSpreadsheet\Shared\File;
15
use PhpOffice\PhpSpreadsheet\Shared\Font;
16
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
17
use PhpOffice\PhpSpreadsheet\Spreadsheet;
18
use PhpOffice\PhpSpreadsheet\Style\Border;
19
use PhpOffice\PhpSpreadsheet\Style\Borders;
20
use PhpOffice\PhpSpreadsheet\Style\Color;
21
use PhpOffice\PhpSpreadsheet\Style\Conditional;
22
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
23
use PhpOffice\PhpSpreadsheet\Style\Protection;
24
use PhpOffice\PhpSpreadsheet\Style\Style;
25
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
26
use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing;
27
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
28
use SimpleXMLElement;
29
use XMLReader;
30
use ZipArchive;
31
32
class Xlsx extends BaseReader
33
{
34
    /**
35
     * ReferenceHelper instance.
36
     *
37
     * @var ReferenceHelper
38
     */
39
    private $referenceHelper;
40
41
    /**
42
     * Xlsx\Theme instance.
43
     *
44
     * @var Xlsx\Theme
45
     */
46
    private static $theme = null;
47
48
    /**
49
     * Create a new Xlsx Reader instance.
50
     */
51 39
    public function __construct()
52
    {
53 39
        $this->readFilter = new DefaultReadFilter();
54 39
        $this->referenceHelper = ReferenceHelper::getInstance();
55 39
    }
56
57
    /**
58
     * Can the current IReader read the file?
59
     *
60
     * @param string $pFilename
61
     *
62
     * @throws Exception
63
     *
64
     * @return bool
65
     */
66 6
    public function canRead($pFilename)
67
    {
68 6
        File::assertFile($pFilename);
69
70 6
        $xl = false;
71
        // Load file
72 6
        $zip = new ZipArchive();
73 6
        if ($zip->open($pFilename) === true) {
74
            // check if it is an OOXML archive
75 6
            $rels = simplexml_load_string(
76 6
                $this->securityScan(
77 6
                    $this->getFromZipArchive($zip, '_rels/.rels')
78
                ),
79 6
                'SimpleXMLElement',
80 6
                Settings::getLibXmlLoaderOptions()
81
            );
82 6
            if ($rels !== false) {
83 6
                foreach ($rels->Relationship as $rel) {
84 6
                    switch ($rel['Type']) {
85 6
                        case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
86 6
                            if (basename($rel['Target']) == 'workbook.xml') {
87 6
                                $xl = true;
88
                            }
89
90 6
                            break;
91
                    }
92
                }
93
            }
94 6
            $zip->close();
95
        }
96
97 6
        return $xl;
98
    }
99
100
    /**
101
     * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
102
     *
103
     * @param string $pFilename
104
     *
105
     * @throws Exception
106
     *
107
     * @return array
108
     */
109 1
    public function listWorksheetNames($pFilename)
110
    {
111 1
        File::assertFile($pFilename);
112
113 1
        $worksheetNames = [];
114
115 1
        $zip = new ZipArchive();
116 1
        $zip->open($pFilename);
117
118
        //    The files we're looking at here are small enough that simpleXML is more efficient than XMLReader
119
        //~ http://schemas.openxmlformats.org/package/2006/relationships");
120 1
        $rels = simplexml_load_string(
121 1
            $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels'))
122
        );
123 1
        foreach ($rels->Relationship as $rel) {
124 1
            switch ($rel['Type']) {
125 1
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
126
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
127 1
                    $xmlWorkbook = simplexml_load_string(
128 1
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}"))
129
                    );
130
131 1
                    if ($xmlWorkbook->sheets) {
132 1
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
133
                            // Check if sheet should be skipped
134 1
                            $worksheetNames[] = (string) $eleSheet['name'];
135
                        }
136
                    }
137
            }
138
        }
139
140 1
        $zip->close();
141
142 1
        return $worksheetNames;
143
    }
144
145
    /**
146
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
147
     *
148
     * @param string $pFilename
149
     *
150
     * @throws Exception
151
     *
152
     * @return array
153
     */
154 1
    public function listWorksheetInfo($pFilename)
155
    {
156 1
        File::assertFile($pFilename);
157
158 1
        $worksheetInfo = [];
159
160 1
        $zip = new ZipArchive();
161 1
        $zip->open($pFilename);
162
163
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
164 1
        $rels = simplexml_load_string(
165 1
            $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels')),
166 1
            'SimpleXMLElement',
167 1
            Settings::getLibXmlLoaderOptions()
168
        );
169 1
        foreach ($rels->Relationship as $rel) {
170 1
            if ($rel['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument') {
171 1
                $dir = dirname($rel['Target']);
172
173
                //~ http://schemas.openxmlformats.org/package/2006/relationships"
174 1
                $relsWorkbook = simplexml_load_string(
175 1
                    $this->securityScan(
176 1
                        $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')
177
                    ),
178 1
                    'SimpleXMLElement',
179 1
                    Settings::getLibXmlLoaderOptions()
180
                );
181 1
                $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
182
183 1
                $worksheets = [];
184 1
                foreach ($relsWorkbook->Relationship as $ele) {
185 1
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet') {
186 1
                        $worksheets[(string) $ele['Id']] = $ele['Target'];
187
                    }
188
                }
189
190
                //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
191 1
                $xmlWorkbook = simplexml_load_string(
192 1
                    $this->securityScan(
193 1
                        $this->getFromZipArchive($zip, "{$rel['Target']}")
194
                    ),
195 1
                    'SimpleXMLElement',
196 1
                    Settings::getLibXmlLoaderOptions()
197
                );
198 1
                if ($xmlWorkbook->sheets) {
199 1
                    $dir = dirname($rel['Target']);
200
                    /** @var SimpleXMLElement $eleSheet */
201 1
                    foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
202
                        $tmpInfo = [
203 1
                            'worksheetName' => (string) $eleSheet['name'],
204 1
                            'lastColumnLetter' => 'A',
205 1
                            'lastColumnIndex' => 0,
206 1
                            'totalRows' => 0,
207 1
                            'totalColumns' => 0,
208
                        ];
209
210 1
                        $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
211
212 1
                        $xml = new XMLReader();
213 1
                        $xml->xml(
214 1
                            $this->securityScanFile(
215 1
                                'zip://' . File::realpath($pFilename) . '#' . "$dir/$fileWorksheet"
216
                            ),
217 1
                            null,
218 1
                            Settings::getLibXmlLoaderOptions()
219
                        );
220 1
                        $xml->setParserProperty(2, true);
221
222 1
                        $currCells = 0;
223 1
                        while ($xml->read()) {
224 1
                            if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) {
225 1
                                $row = $xml->getAttribute('r');
226 1
                                $tmpInfo['totalRows'] = $row;
227 1
                                $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
228 1
                                $currCells = 0;
229 1
                            } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) {
230 1
                                ++$currCells;
231
                            }
232
                        }
233 1
                        $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
234 1
                        $xml->close();
235
236 1
                        $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
237 1
                        $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
238
239 1
                        $worksheetInfo[] = $tmpInfo;
240
                    }
241
                }
242
            }
243
        }
244
245 1
        $zip->close();
246
247 1
        return $worksheetInfo;
248
    }
249
250 4
    private static function castToBoolean($c)
251
    {
252 4
        $value = isset($c->v) ? (string) $c->v : null;
253 4
        if ($value == '0') {
254
            return false;
255 4
        } elseif ($value == '1') {
256 4
            return true;
257
        }
258
259
        return (bool) $c->v;
260
    }
261
262
    private static function castToError($c)
263
    {
264
        return isset($c->v) ? (string) $c->v : null;
265
    }
266
267 17
    private static function castToString($c)
268
    {
269 17
        return isset($c->v) ? (string) $c->v : null;
270
    }
271
272 7
    private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType)
273
    {
274 7
        $cellDataType = 'f';
275 7
        $value = "={$c->f}";
276 7
        $calculatedValue = self::$castBaseType($c);
277
278
        // Shared formula?
279 7
        if (isset($c->f['t']) && strtolower((string) $c->f['t']) == 'shared') {
280 2
            $instance = (string) $c->f['si'];
281
282 2
            if (!isset($sharedFormulas[(string) $c->f['si']])) {
283 2
                $sharedFormulas[$instance] = ['master' => $r, 'formula' => $value];
284
            } else {
285 2
                $master = Coordinate::coordinateFromString($sharedFormulas[$instance]['master']);
286 2
                $current = Coordinate::coordinateFromString($r);
287
288 2
                $difference = [0, 0];
289 2
                $difference[0] = Coordinate::columnIndexFromString($current[0]) - Coordinate::columnIndexFromString($master[0]);
290 2
                $difference[1] = $current[1] - $master[1];
291
292 2
                $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], 'A1', $difference[0], $difference[1]);
293
            }
294
        }
295 7
    }
296
297
    /**
298
     * @param ZipArchive $archive
299
     * @param string $fileName
300
     *
301
     * @return string
302
     */
303 38
    private function getFromZipArchive(ZipArchive $archive, $fileName = '')
304
    {
305
        // Root-relative paths
306 38
        if (strpos($fileName, '//') !== false) {
307
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
308
        }
309 38
        $fileName = File::realpath($fileName);
310
311
        // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
312
        //    so we need to load case-insensitively from the zip file
313
314
        // Apache POI fixes
315 38
        $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
316 38
        if ($contents === false) {
317 1
            $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
318
        }
319
320 38
        return $contents;
321
    }
322
323
    /**
324
     * Set Worksheet column attributes by attributes array passed.
325
     *
326
     * @param Worksheet $docSheet
327
     * @param string $column A, B, ... DX, ...
328
     * @param array $columnAttributes array of attributes (indexes are attribute name, values are value)
329
     *                               'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'width', ... ?
330
     */
331 3
    private function setColumnAttributes(Worksheet $docSheet, $column, array $columnAttributes)
332
    {
333 3
        if (isset($columnAttributes['xfIndex'])) {
334
            $docSheet->getColumnDimension($column)->setXfIndex($columnAttributes['xfIndex']);
335
        }
336 3
        if (isset($columnAttributes['visible'])) {
337
            $docSheet->getColumnDimension($column)->setVisible($columnAttributes['visible']);
338
        }
339 3
        if (isset($columnAttributes['collapsed'])) {
340
            $docSheet->getColumnDimension($column)->setCollapsed($columnAttributes['collapsed']);
341
        }
342 3
        if (isset($columnAttributes['outlineLevel'])) {
343
            $docSheet->getColumnDimension($column)->setOutlineLevel($columnAttributes['outlineLevel']);
344
        }
345 3
        if (isset($columnAttributes['width'])) {
346 3
            $docSheet->getColumnDimension($column)->setWidth($columnAttributes['width']);
347
        }
348 3
    }
349
350
    /**
351
     * Set Worksheet row attributes by attributes array passed.
352
     *
353
     * @param Worksheet $docSheet
354
     * @param int $row 1, 2, 3, ... 99, ...
355
     * @param array $rowAttributes array of attributes (indexes are attribute name, values are value)
356
     *                               'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'rowHeight', ... ?
357
     */
358 3
    private function setRowAttributes(Worksheet $docSheet, $row, array $rowAttributes)
359
    {
360 3
        if (isset($rowAttributes['xfIndex'])) {
361
            $docSheet->getRowDimension($row)->setXfIndex($rowAttributes['xfIndex']);
362
        }
363 3
        if (isset($rowAttributes['visible'])) {
364
            $docSheet->getRowDimension($row)->setVisible($rowAttributes['visible']);
365
        }
366 3
        if (isset($rowAttributes['collapsed'])) {
367
            $docSheet->getRowDimension($row)->setCollapsed($rowAttributes['collapsed']);
368
        }
369 3
        if (isset($rowAttributes['outlineLevel'])) {
370
            $docSheet->getRowDimension($row)->setOutlineLevel($rowAttributes['outlineLevel']);
371
        }
372 3
        if (isset($rowAttributes['rowHeight'])) {
373 3
            $docSheet->getRowDimension($row)->setRowHeight($rowAttributes['rowHeight']);
374
        }
375 3
    }
376
377
    /**
378
     * Loads Spreadsheet from file.
379
     *
380
     * @param string $pFilename
381
     *
382
     * @throws Exception
383
     *
384
     * @return Spreadsheet
385
     */
386 35
    public function load($pFilename)
387
    {
388 35
        File::assertFile($pFilename);
389
390
        // Initialisations
391 35
        $excel = new Spreadsheet();
392 35
        $excel->removeSheetByIndex(0);
393 35
        if (!$this->readDataOnly) {
394 35
            $excel->removeCellStyleXfByIndex(0); // remove the default style
395 35
            $excel->removeCellXfByIndex(0); // remove the default style
396
        }
397 35
        $unparsedLoadedData = [];
398
399 35
        $zip = new ZipArchive();
400 35
        $zip->open($pFilename);
401
402
        //    Read the theme first, because we need the colour scheme when reading the styles
403
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
404 35
        $wbRels = simplexml_load_string(
405 35
            $this->securityScan($this->getFromZipArchive($zip, 'xl/_rels/workbook.xml.rels')),
406 35
            'SimpleXMLElement',
407 35
            Settings::getLibXmlLoaderOptions()
408
        );
409 35
        foreach ($wbRels->Relationship as $rel) {
410 35
            switch ($rel['Type']) {
411 35
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme':
412 35
                    $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
413 35
                    $themeOrderAdditional = count($themeOrderArray);
414
415 35
                    $xmlTheme = simplexml_load_string(
416 35
                        $this->securityScan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")),
417 35
                        'SimpleXMLElement',
418 35
                        Settings::getLibXmlLoaderOptions()
419
                    );
420 35
                    if (is_object($xmlTheme)) {
421 35
                        $xmlThemeName = $xmlTheme->attributes();
422 35
                        $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
423 35
                        $themeName = (string) $xmlThemeName['name'];
424
425 35
                        $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
426 35
                        $colourSchemeName = (string) $colourScheme['name'];
427 35
                        $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
428
429 35
                        $themeColours = [];
430 35
                        foreach ($colourScheme as $k => $xmlColour) {
431 35
                            $themePos = array_search($k, $themeOrderArray);
432 35
                            if ($themePos === false) {
433 35
                                $themePos = $themeOrderAdditional++;
434
                            }
435 35
                            if (isset($xmlColour->sysClr)) {
436 35
                                $xmlColourData = $xmlColour->sysClr->attributes();
437 35
                                $themeColours[$themePos] = $xmlColourData['lastClr'];
438 35
                            } elseif (isset($xmlColour->srgbClr)) {
439 35
                                $xmlColourData = $xmlColour->srgbClr->attributes();
440 35
                                $themeColours[$themePos] = $xmlColourData['val'];
441
                            }
442
                        }
443 35
                        self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours);
444
                    }
445
446 35
                    break;
447
            }
448
        }
449
450
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
451 35
        $rels = simplexml_load_string(
452 35
            $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels')),
453 35
            'SimpleXMLElement',
454 35
            Settings::getLibXmlLoaderOptions()
455
        );
456 35
        foreach ($rels->Relationship as $rel) {
457 35
            switch ($rel['Type']) {
458 35
                case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties':
459 34
                    $xmlCore = simplexml_load_string(
460 34
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
461 34
                        'SimpleXMLElement',
462 34
                        Settings::getLibXmlLoaderOptions()
463
                    );
464 34
                    if (is_object($xmlCore)) {
465 34
                        $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/');
466 34
                        $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/');
467 34
                        $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
468 34
                        $docProps = $excel->getProperties();
469 34
                        $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator')));
470 34
                        $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy')));
471 34
                        $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type
472 34
                        $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type
473 34
                        $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title')));
474 34
                        $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description')));
475 34
                        $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject')));
476 34
                        $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath('cp:keywords')));
477 34
                        $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath('cp:category')));
478
                    }
479
480 34
                    break;
481 35
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties':
482 34
                    $xmlCore = simplexml_load_string(
483 34
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
484 34
                        'SimpleXMLElement',
485 34
                        Settings::getLibXmlLoaderOptions()
486
                    );
487 34
                    if (is_object($xmlCore)) {
488 34
                        $docProps = $excel->getProperties();
489 34
                        if (isset($xmlCore->Company)) {
490 32
                            $docProps->setCompany((string) $xmlCore->Company);
491
                        }
492 34
                        if (isset($xmlCore->Manager)) {
493 29
                            $docProps->setManager((string) $xmlCore->Manager);
494
                        }
495
                    }
496
497 34
                    break;
498 35
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties':
499 3
                    $xmlCore = simplexml_load_string(
500 3
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
501 3
                        'SimpleXMLElement',
502 3
                        Settings::getLibXmlLoaderOptions()
503
                    );
504 3
                    if (is_object($xmlCore)) {
505 3
                        $docProps = $excel->getProperties();
506
                        /** @var SimpleXMLElement $xmlProperty */
507 3
                        foreach ($xmlCore as $xmlProperty) {
508 3
                            $cellDataOfficeAttributes = $xmlProperty->attributes();
509 3
                            if (isset($cellDataOfficeAttributes['name'])) {
510 3
                                $propertyName = (string) $cellDataOfficeAttributes['name'];
511 3
                                $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
512 3
                                $attributeType = $cellDataOfficeChildren->getName();
513 3
                                $attributeValue = (string) $cellDataOfficeChildren->{$attributeType};
514 3
                                $attributeValue = Properties::convertProperty($attributeValue, $attributeType);
515 3
                                $attributeType = Properties::convertPropertyType($attributeType);
516 3
                                $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType);
517
                            }
518
                        }
519
                    }
520
521 3
                    break;
522
                //Ribbon
523 35
                case 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility':
524
                    $customUI = $rel['Target'];
525
                    if ($customUI !== null) {
526
                        $this->readRibbon($excel, $customUI, $zip);
527
                    }
528
529
                    break;
530 35
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
531 35
                    $dir = dirname($rel['Target']);
532
                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
533 35
                    $relsWorkbook = simplexml_load_string(
534 35
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')),
535 35
                        'SimpleXMLElement',
536 35
                        Settings::getLibXmlLoaderOptions()
537
                    );
538 35
                    $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
539
540 35
                    $sharedStrings = [];
541 35
                    $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
542
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
543 35
                    $xmlStrings = simplexml_load_string(
544 35
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
545 35
                        'SimpleXMLElement',
546 35
                        Settings::getLibXmlLoaderOptions()
547
                    );
548 35
                    if (isset($xmlStrings, $xmlStrings->si)) {
549 18
                        foreach ($xmlStrings->si as $val) {
550 18
                            if (isset($val->t)) {
551 18
                                $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
552 3
                            } elseif (isset($val->r)) {
553 18
                                $sharedStrings[] = $this->parseRichText($val);
554
                            }
555
                        }
556
                    }
557
558 35
                    $worksheets = [];
559 35
                    $macros = $customUI = null;
560 35
                    foreach ($relsWorkbook->Relationship as $ele) {
561 35
                        switch ($ele['Type']) {
562 35
                            case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet':
563 35
                                $worksheets[(string) $ele['Id']] = $ele['Target'];
564
565 35
                                break;
566
                            // a vbaProject ? (: some macros)
567 35
                            case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject':
568 1
                                $macros = $ele['Target'];
569
570 35
                                break;
571
                        }
572
                    }
573
574 35
                    if ($macros !== null) {
575 1
                        $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin
576 1
                        if ($macrosCode !== false) {
577 1
                            $excel->setMacrosCode($macrosCode);
578 1
                            $excel->setHasMacros(true);
579
                            //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir
580 1
                            $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin');
581 1
                            if ($Certificate !== false) {
582
                                $excel->setMacrosCertificate($Certificate);
583
                            }
584
                        }
585
                    }
586 35
                    $styles = [];
587 35
                    $cellStyles = [];
588 35
                    $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
589
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
590 35
                    $xmlStyles = simplexml_load_string(
591 35
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
592 35
                        'SimpleXMLElement',
593 35
                        Settings::getLibXmlLoaderOptions()
594
                    );
595 35
                    $numFmts = null;
596 35
                    if ($xmlStyles && $xmlStyles->numFmts[0]) {
597 28
                        $numFmts = $xmlStyles->numFmts[0];
598
                    }
599 35
                    if (isset($numFmts) && ($numFmts !== null)) {
600 28
                        $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
601
                    }
602 35
                    if (!$this->readDataOnly && $xmlStyles) {
603 35
                        foreach ($xmlStyles->cellXfs->xf as $xf) {
604 35
                            $numFmt = NumberFormat::FORMAT_GENERAL;
605
606 35
                            if ($xf['numFmtId']) {
607 35
                                if (isset($numFmts)) {
608 28
                                    $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
609
610 28
                                    if (isset($tmpNumFmt['formatCode'])) {
611 3
                                        $numFmt = (string) $tmpNumFmt['formatCode'];
612
                                    }
613
                                }
614
615
                                // We shouldn't override any of the built-in MS Excel values (values below id 164)
616
                                //  But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used
617
                                //  So we make allowance for them rather than lose formatting masks
618 35
                                if ((int) $xf['numFmtId'] < 164 &&
619 35
                                    NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '') {
620 35
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
621
                                }
622
                            }
623 35
                            $quotePrefix = false;
624 35
                            if (isset($xf['quotePrefix'])) {
625
                                $quotePrefix = (bool) $xf['quotePrefix'];
626
                            }
627
628
                            $style = (object) [
629 35
                                'numFmt' => $numFmt,
630 35
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
631 35
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
632 35
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
633 35
                                'alignment' => $xf->alignment,
634 35
                                'protection' => $xf->protection,
635 35
                                'quotePrefix' => $quotePrefix,
636
                            ];
637 35
                            $styles[] = $style;
638
639
                            // add style to cellXf collection
640 35
                            $objStyle = new Style();
641 35
                            self::readStyle($objStyle, $style);
642 35
                            $excel->addCellXf($objStyle);
643
                        }
644
645 35
                        foreach ($xmlStyles->cellStyleXfs->xf as $xf) {
646 35
                            $numFmt = NumberFormat::FORMAT_GENERAL;
647 35
                            if ($numFmts && $xf['numFmtId']) {
648 28
                                $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
649 28
                                if (isset($tmpNumFmt['formatCode'])) {
650 1
                                    $numFmt = (string) $tmpNumFmt['formatCode'];
651 28
                                } elseif ((int) $xf['numFmtId'] < 165) {
652 28
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
653
                                }
654
                            }
655
656
                            $cellStyle = (object) [
657 35
                                'numFmt' => $numFmt,
658 35
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
659 35
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
660 35
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
661 35
                                'alignment' => $xf->alignment,
662 35
                                'protection' => $xf->protection,
663 35
                                'quotePrefix' => $quotePrefix,
664
                            ];
665 35
                            $cellStyles[] = $cellStyle;
666
667
                            // add style to cellStyleXf collection
668 35
                            $objStyle = new Style();
669 35
                            self::readStyle($objStyle, $cellStyle);
670 35
                            $excel->addCellStyleXf($objStyle);
671
                        }
672
                    }
673
674 35
                    $dxfs = [];
675 35
                    if (!$this->readDataOnly && $xmlStyles) {
676
                        //    Conditional Styles
677 35
                        if ($xmlStyles->dxfs) {
678 35
                            foreach ($xmlStyles->dxfs->dxf as $dxf) {
679 1
                                $style = new Style(false, true);
680 1
                                self::readStyle($style, $dxf);
681 1
                                $dxfs[] = $style;
682
                            }
683
                        }
684
                        //    Cell Styles
685 35
                        if ($xmlStyles->cellStyles) {
686 35
                            foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) {
687 35
                                if ((int) ($cellStyle['builtinId']) == 0) {
688 35
                                    if (isset($cellStyles[(int) ($cellStyle['xfId'])])) {
689
                                        // Set default style
690 35
                                        $style = new Style();
691 35
                                        self::readStyle($style, $cellStyles[(int) ($cellStyle['xfId'])]);
692
693
                                        // normal style, currently not using it for anything
694
                                    }
695
                                }
696
                            }
697
                        }
698
                    }
699
700
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
701 35
                    $xmlWorkbook = simplexml_load_string(
702 35
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
703 35
                        'SimpleXMLElement',
704 35
                        Settings::getLibXmlLoaderOptions()
705
                    );
706
707
                    // Set base date
708 35
                    if ($xmlWorkbook->workbookPr) {
709 34
                        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
710 34
                        if (isset($xmlWorkbook->workbookPr['date1904'])) {
711
                            if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) {
712
                                Date::setExcelCalendar(Date::CALENDAR_MAC_1904);
713
                            }
714
                        }
715
                    }
716
717
                    // Set protection
718 35
                    $this->readProtection($excel, $xmlWorkbook);
719
720 35
                    $sheetId = 0; // keep track of new sheet id in final workbook
721 35
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
722 35
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
723 35
                    $mapSheetId = []; // mapping of sheet ids from old to new
724
725 35
                    $charts = $chartDetails = [];
726
727 35
                    if ($xmlWorkbook->sheets) {
728
                        /** @var SimpleXMLElement $eleSheet */
729 35
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
730 35
                            ++$oldSheetId;
731
732
                            // Check if sheet should be skipped
733 35
                            if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) {
734 1
                                ++$countSkippedSheets;
735 1
                                $mapSheetId[$oldSheetId] = null;
736
737 1
                                continue;
738
                            }
739
740
                            // Map old sheet id in original workbook to new sheet id.
741
                            // They will differ if loadSheetsOnly() is being used
742 35
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
743
744
                            // Load sheet
745 35
                            $docSheet = $excel->createSheet();
746
                            //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet
747
                            //        references in formula cells... during the load, all formulae should be correct,
748
                            //        and we're simply bringing the worksheet name in line with the formula, not the
749
                            //        reverse
750 35
                            $docSheet->setTitle((string) $eleSheet['name'], false, false);
751 35
                            $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
752
                            //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
753 35
                            $xmlSheet = simplexml_load_string(
754 35
                                $this->securityScan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")),
755 35
                                'SimpleXMLElement',
756 35
                                Settings::getLibXmlLoaderOptions()
757
                            );
758
759 35
                            $sharedFormulas = [];
760
761 35
                            if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') {
762 1
                                $docSheet->setSheetState((string) $eleSheet['state']);
763
                            }
764
765 35
                            if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) {
766 35
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) {
767
                                    $zoomScale = (int) ($xmlSheet->sheetViews->sheetView['zoomScale']);
768
                                    if ($zoomScale <= 0) {
769
                                        // setZoomScale will throw an Exception if the scale is less than or equals 0
770
                                        // that is OK when manually creating documents, but we should be able to read all documents
771
                                        $zoomScale = 100;
772
                                    }
773
774
                                    $docSheet->getSheetView()->setZoomScale($zoomScale);
775
                                }
776 35
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) {
777
                                    $zoomScaleNormal = (int) ($xmlSheet->sheetViews->sheetView['zoomScaleNormal']);
778
                                    if ($zoomScaleNormal <= 0) {
779
                                        // setZoomScaleNormal will throw an Exception if the scale is less than or equals 0
780
                                        // that is OK when manually creating documents, but we should be able to read all documents
781
                                        $zoomScaleNormal = 100;
782
                                    }
783
784
                                    $docSheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal);
785
                                }
786 35
                                if (isset($xmlSheet->sheetViews->sheetView['view'])) {
787
                                    $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']);
788
                                }
789 35
                                if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
790 27
                                    $docSheet->setShowGridLines(self::boolean((string) $xmlSheet->sheetViews->sheetView['showGridLines']));
791
                                }
792 35
                                if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
793 27
                                    $docSheet->setShowRowColHeaders(self::boolean((string) $xmlSheet->sheetViews->sheetView['showRowColHeaders']));
794
                                }
795 35
                                if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
796
                                    $docSheet->setRightToLeft(self::boolean((string) $xmlSheet->sheetViews->sheetView['rightToLeft']));
797
                                }
798 35
                                if (isset($xmlSheet->sheetViews->sheetView->pane)) {
799 3
                                    $xSplit = 0;
800 3
                                    $ySplit = 0;
801 3
                                    $topLeftCell = null;
802
803 3
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
804 1
                                        $xSplit = (int) ($xmlSheet->sheetViews->sheetView->pane['xSplit']);
805
                                    }
806
807 3
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
808 3
                                        $ySplit = (int) ($xmlSheet->sheetViews->sheetView->pane['ySplit']);
809
                                    }
810
811 3
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
812 3
                                        $topLeftCell = (string) $xmlSheet->sheetViews->sheetView->pane['topLeftCell'];
813
                                    }
814
815 3
                                    $docSheet->freezePane(Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1), $topLeftCell);
816
                                }
817
818 35
                                if (isset($xmlSheet->sheetViews->sheetView->selection)) {
819 33
                                    if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
820 32
                                        $sqref = (string) $xmlSheet->sheetViews->sheetView->selection['sqref'];
821 32
                                        $sqref = explode(' ', $sqref);
822 32
                                        $sqref = $sqref[0];
823 32
                                        $docSheet->setSelectedCells($sqref);
824
                                    }
825
                                }
826
                            }
827
828 35
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->tabColor)) {
829 2
                                if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
830 2
                                    $docSheet->getTabColor()->setARGB((string) $xmlSheet->sheetPr->tabColor['rgb']);
831
                                }
832
                            }
833 35
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr['codeName'])) {
834 1
                                $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName'], false);
835
                            }
836 35
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->outlinePr)) {
837 27
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) &&
838 27
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) {
839
                                    $docSheet->setShowSummaryRight(false);
840
                                } else {
841 27
                                    $docSheet->setShowSummaryRight(true);
842
                                }
843
844 27
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) &&
845 27
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) {
846
                                    $docSheet->setShowSummaryBelow(false);
847
                                } else {
848 27
                                    $docSheet->setShowSummaryBelow(true);
849
                                }
850
                            }
851
852 35
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->pageSetUpPr)) {
853
                                if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) &&
854
                                    !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) {
855
                                    $docSheet->getPageSetup()->setFitToPage(false);
856
                                } else {
857
                                    $docSheet->getPageSetup()->setFitToPage(true);
858
                                }
859
                            }
860
861 35
                            if (isset($xmlSheet->sheetFormatPr)) {
862 35
                                if (isset($xmlSheet->sheetFormatPr['customHeight']) &&
863 35
                                    self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) &&
864 35
                                    isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
865 1
                                    $docSheet->getDefaultRowDimension()->setRowHeight((float) $xmlSheet->sheetFormatPr['defaultRowHeight']);
866
                                }
867 35
                                if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
868 1
                                    $docSheet->getDefaultColumnDimension()->setWidth((float) $xmlSheet->sheetFormatPr['defaultColWidth']);
869
                                }
870 35
                                if (isset($xmlSheet->sheetFormatPr['zeroHeight']) &&
871 35
                                    ((string) $xmlSheet->sheetFormatPr['zeroHeight'] == '1')) {
872
                                    $docSheet->getDefaultRowDimension()->setZeroHeight(true);
873
                                }
874
                            }
875
876 35
                            if (isset($xmlSheet->printOptions) && !$this->readDataOnly) {
877 27
                                if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) {
878 27
                                    $docSheet->setShowGridlines(true);
879
                                }
880 27
                                if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) {
881
                                    $docSheet->setPrintGridlines(true);
882
                                }
883 27
                                if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) {
884
                                    $docSheet->getPageSetup()->setHorizontalCentered(true);
885
                                }
886 27
                                if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) {
887
                                    $docSheet->getPageSetup()->setVerticalCentered(true);
888
                                }
889
                            }
890
891 35
                            $columnsAttributes = [];
892 35
                            $rowsAttributes = [];
893 35
                            if (isset($xmlSheet->cols) && !$this->readDataOnly) {
894 8
                                foreach ($xmlSheet->cols->col as $col) {
895 8
                                    for ($i = (int) ($col['min']); $i <= (int) ($col['max']); ++$i) {
896 8
                                        if ($col['style'] && !$this->readDataOnly) {
897 3
                                            $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['xfIndex'] = (int) $col['style'];
898
                                        }
899 8
                                        if (self::boolean($col['hidden'])) {
900 1
                                            $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['visible'] = false;
901
                                        }
902 8
                                        if (self::boolean($col['collapsed'])) {
903 1
                                            $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['collapsed'] = true;
904
                                        }
905 8
                                        if ($col['outlineLevel'] > 0) {
906 1
                                            $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['outlineLevel'] = (int) $col['outlineLevel'];
907
                                        }
908 8
                                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['width'] = (float) $col['width'];
909
910 8
                                        if ((int) ($col['max']) == 16384) {
911
                                            break;
912
                                        }
913
                                    }
914
                                }
915
                            }
916
917 35
                            if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
918 29
                                foreach ($xmlSheet->sheetData->row as $row) {
919 29
                                    if ($row['ht'] && !$this->readDataOnly) {
920 3
                                        $rowsAttributes[(int) $row['r']]['rowHeight'] = (float) $row['ht'];
921
                                    }
922 29
                                    if (self::boolean($row['hidden']) && !$this->readDataOnly) {
923
                                        $rowsAttributes[(int) $row['r']]['visible'] = false;
924
                                    }
925 29
                                    if (self::boolean($row['collapsed'])) {
926
                                        $rowsAttributes[(int) $row['r']]['collapsed'] = true;
927
                                    }
928 29
                                    if ($row['outlineLevel'] > 0) {
929
                                        $rowsAttributes[(int) $row['r']]['outlineLevel'] = (int) $row['outlineLevel'];
930
                                    }
931 29
                                    if ($row['s'] && !$this->readDataOnly) {
932 29
                                        $rowsAttributes[(int) $row['r']]['xfIndex'] = (int) $row['s'];
933
                                    }
934
                                }
935
                            }
936
937
                            // set columns/rows attributes
938 35
                            $columnsAttributesSet = [];
939 35
                            $rowsAttributesSet = [];
940 35
                            foreach ($columnsAttributes as $coordColumn => $columnAttributes) {
941 8
                                foreach ($rowsAttributes as $coordRow => $rowAttributes) {
942 3
                                    if ($this->getReadFilter() !== null) {
943 3
                                        if (!$this->getReadFilter()->readCell($coordColumn, $coordRow, $docSheet->getTitle())) {
944
                                            continue;
945
                                        }
946
                                    }
947
948 3
                                    if (!isset($columnsAttributesSet[$coordColumn])) {
949 3
                                        $this->setColumnAttributes($docSheet, $coordColumn, $columnAttributes);
950 3
                                        $columnsAttributesSet[$coordColumn] = true;
951
                                    }
952 3
                                    if (!isset($rowsAttributesSet[$coordRow])) {
953 3
                                        $this->setRowAttributes($docSheet, $coordRow, $rowAttributes);
954 8
                                        $rowsAttributesSet[$coordRow] = true;
955
                                    }
956
                                }
957
                            }
958
959 35
                            if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
960 29
                                $cIndex = 1; // Cell Start from 1
961 29
                                foreach ($xmlSheet->sheetData->row as $row) {
962 29
                                    $rowIndex = 1;
963 29
                                    foreach ($row->c as $c) {
964 29
                                        $r = (string) $c['r'];
965 29
                                        if ($r == '') {
966 1
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
967
                                        }
968 29
                                        $cellDataType = (string) $c['t'];
969 29
                                        $value = null;
970 29
                                        $calculatedValue = null;
971
972
                                        // Read cell?
973 29
                                        if ($this->getReadFilter() !== null) {
974 29
                                            $coordinates = Coordinate::coordinateFromString($r);
975
976 29
                                            if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) {
977 2
                                                continue;
978
                                            }
979
                                        }
980
981
                                        // Read cell!
982
                                        switch ($cellDataType) {
983 29
                                            case 's':
984 18
                                                if ((string) $c->v != '') {
985 18
                                                    $value = $sharedStrings[(int) ($c->v)];
986
987 18
                                                    if ($value instanceof RichText) {
988 18
                                                        $value = clone $value;
989
                                                    }
990
                                                } else {
991
                                                    $value = '';
992
                                                }
993
994 18
                                                break;
995 20
                                            case 'b':
996 4
                                                if (!isset($c->f)) {
997 2
                                                    $value = self::castToBoolean($c);
998
                                                } else {
999
                                                    // Formula
1000 2
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean');
1001 2
                                                    if (isset($c->f['t'])) {
1002
                                                        $att = $c->f;
1003
                                                        $docSheet->getCell($r)->setFormulaAttributes($att);
1004
                                                    }
1005
                                                }
1006
1007 4
                                                break;
1008 17
                                            case 'inlineStr':
1009 2
                                                if (isset($c->f)) {
1010
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
1011
                                                } else {
1012 2
                                                    $value = $this->parseRichText($c->is);
1013
                                                }
1014
1015 2
                                                break;
1016 17
                                            case 'e':
1017
                                                if (!isset($c->f)) {
1018
                                                    $value = self::castToError($c);
1019
                                                } else {
1020
                                                    // Formula
1021
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
1022
                                                }
1023
1024
                                                break;
1025
                                            default:
1026 17
                                                if (!isset($c->f)) {
1027 15
                                                    $value = self::castToString($c);
1028
                                                } else {
1029
                                                    // Formula
1030 6
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
1031
                                                }
1032
1033 17
                                                break;
1034
                                        }
1035
1036
                                        // Check for numeric values
1037 29
                                        if (is_numeric($value) && $cellDataType != 's') {
1038 15
                                            if ($value == (int) $value) {
1039 14
                                                $value = (int) $value;
1040 1
                                            } elseif ($value == (float) $value) {
1041 1
                                                $value = (float) $value;
1042
                                            } elseif ($value == (float) $value) {
1043
                                                $value = (float) $value;
1044
                                            }
1045
                                        }
1046
1047
                                        // Rich text?
1048 29
                                        if ($value instanceof RichText && $this->readDataOnly) {
1049
                                            $value = $value->getPlainText();
1050
                                        }
1051
1052 29
                                        $cell = $docSheet->getCell($r);
1053
                                        // Assign value
1054 29
                                        if ($cellDataType != '') {
1055 22
                                            $cell->setValueExplicit($value, $cellDataType);
1056
                                        } else {
1057 15
                                            $cell->setValue($value);
1058
                                        }
1059 29
                                        if ($calculatedValue !== null) {
1060 7
                                            $cell->setCalculatedValue($calculatedValue);
1061
                                        }
1062
1063
                                        // Style information?
1064 29
                                        if ($c['s'] && !$this->readDataOnly) {
1065
                                            // no style index means 0, it seems
1066 7
                                            $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
1067 7
                                                (int) ($c['s']) : 0);
1068
                                        }
1069 29
                                        $rowIndex += 1;
1070
                                    }
1071 29
                                    $cIndex += 1;
1072
                                }
1073
                            }
1074
1075 35
                            $conditionals = [];
1076 35
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
1077 1
                                foreach ($xmlSheet->conditionalFormatting as $conditional) {
1078 1
                                    foreach ($conditional->cfRule as $cfRule) {
1079 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'])])) {
1080 1
                                            $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
1081
                                        }
1082
                                    }
1083
                                }
1084
1085 1
                                foreach ($conditionals as $ref => $cfRules) {
1086 1
                                    ksort($cfRules);
1087 1
                                    $conditionalStyles = [];
1088 1
                                    foreach ($cfRules as $cfRule) {
1089 1
                                        $objConditional = new Conditional();
1090 1
                                        $objConditional->setConditionType((string) $cfRule['type']);
1091 1
                                        $objConditional->setOperatorType((string) $cfRule['operator']);
1092
1093 1
                                        if ((string) $cfRule['text'] != '') {
1094
                                            $objConditional->setText((string) $cfRule['text']);
1095
                                        }
1096
1097 1
                                        if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
1098 1
                                            $objConditional->setStopIfTrue(true);
1099
                                        }
1100
1101 1
                                        if (count($cfRule->formula) > 1) {
1102
                                            foreach ($cfRule->formula as $formula) {
1103
                                                $objConditional->addCondition((string) $formula);
1104
                                            }
1105
                                        } else {
1106 1
                                            $objConditional->addCondition((string) $cfRule->formula);
1107
                                        }
1108 1
                                        $objConditional->setStyle(clone $dxfs[(int) ($cfRule['dxfId'])]);
1109 1
                                        $conditionalStyles[] = $objConditional;
1110
                                    }
1111
1112
                                    // Extract all cell references in $ref
1113 1
                                    $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
1114 1
                                    foreach ($cellBlocks as $cellBlock) {
1115 1
                                        $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
1116
                                    }
1117
                                }
1118
                            }
1119
1120 35
                            $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
1121 35
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1122 30
                                foreach ($aKeys as $key) {
1123 30
                                    $method = 'set' . ucfirst($key);
1124 30
                                    $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
1125
                                }
1126
                            }
1127
1128 35
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1129 30
                                $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true);
1130 30
                                if ($xmlSheet->protectedRanges->protectedRange) {
1131 2
                                    foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
1132 2
                                        $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
1133
                                    }
1134
                                }
1135
                            }
1136
1137 35
                            if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
1138
                                $autoFilterRange = (string) $xmlSheet->autoFilter['ref'];
1139
                                if (strpos($autoFilterRange, ':') !== false) {
1140
                                    $autoFilter = $docSheet->getAutoFilter();
1141
                                    $autoFilter->setRange($autoFilterRange);
1142
1143
                                    foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
1144
                                        $column = $autoFilter->getColumnByOffset((int) $filterColumn['colId']);
1145
                                        //    Check for standard filters
1146
                                        if ($filterColumn->filters) {
1147
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
1148
                                            $filters = $filterColumn->filters;
1149
                                            if ((isset($filters['blank'])) && ($filters['blank'] == 1)) {
1150
                                                //    Operator is undefined, but always treated as EQUAL
1151
                                                $column->createRule()->setRule(null, '')->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1152
                                            }
1153
                                            //    Standard filters are always an OR join, so no join rule needs to be set
1154
                                            //    Entries can be either filter elements
1155
                                            foreach ($filters->filter as $filterRule) {
1156
                                                //    Operator is undefined, but always treated as EQUAL
1157
                                                $column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1158
                                            }
1159
                                            //    Or Date Group elements
1160
                                            foreach ($filters->dateGroupItem as $dateGroupItem) {
1161
                                                //    Operator is undefined, but always treated as EQUAL
1162
                                                $column->createRule()->setRule(
1163
                                                    null,
1164
                                                    [
1165
                                                        'year' => (string) $dateGroupItem['year'],
1166
                                                        'month' => (string) $dateGroupItem['month'],
1167
                                                        'day' => (string) $dateGroupItem['day'],
1168
                                                        'hour' => (string) $dateGroupItem['hour'],
1169
                                                        'minute' => (string) $dateGroupItem['minute'],
1170
                                                        'second' => (string) $dateGroupItem['second'],
1171
                                                    ],
1172
                                                    (string) $dateGroupItem['dateTimeGrouping']
1173
                                                )
1174
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP);
1175
                                            }
1176
                                        }
1177
                                        //    Check for custom filters
1178
                                        if ($filterColumn->customFilters) {
1179
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
1180
                                            $customFilters = $filterColumn->customFilters;
1181
                                            //    Custom filters can an AND or an OR join;
1182
                                            //        and there should only ever be one or two entries
1183
                                            if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
1184
                                                $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
1185
                                            }
1186
                                            foreach ($customFilters->customFilter as $filterRule) {
1187
                                                $column->createRule()->setRule(
1188
                                                    (string) $filterRule['operator'],
1189
                                                    (string) $filterRule['val']
1190
                                                )
1191
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
1192
                                            }
1193
                                        }
1194
                                        //    Check for dynamic filters
1195
                                        if ($filterColumn->dynamicFilter) {
1196
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
1197
                                            //    We should only ever have one dynamic filter
1198
                                            foreach ($filterColumn->dynamicFilter as $filterRule) {
1199
                                                //    Operator is undefined, but always treated as EQUAL
1200
                                                $column->createRule()->setRule(
1201
                                                    null,
1202
                                                    (string) $filterRule['val'],
1203
                                                    (string) $filterRule['type']
1204
                                                )
1205
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
1206
                                                if (isset($filterRule['val'])) {
1207
                                                    $column->setAttribute('val', (string) $filterRule['val']);
1208
                                                }
1209
                                                if (isset($filterRule['maxVal'])) {
1210
                                                    $column->setAttribute('maxVal', (string) $filterRule['maxVal']);
1211
                                                }
1212
                                            }
1213
                                        }
1214
                                        //    Check for dynamic filters
1215
                                        if ($filterColumn->top10) {
1216
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
1217
                                            //    We should only ever have one top10 filter
1218
                                            foreach ($filterColumn->top10 as $filterRule) {
1219
                                                $column->createRule()->setRule(
1220
                                                    (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
1221
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
1222
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
1223
                                                    ),
1224
                                                    (string) $filterRule['val'],
1225
                                                    (((isset($filterRule['top'])) && ($filterRule['top'] == 1))
1226
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
1227
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
1228
                                                    )
1229
                                                )
1230
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
1231
                                            }
1232
                                        }
1233
                                    }
1234
                                }
1235
                            }
1236
1237 35
                            if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
1238 6
                                foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
1239 6
                                    $mergeRef = (string) $mergeCell['ref'];
1240 6
                                    if (strpos($mergeRef, ':') !== false) {
1241 6
                                        $docSheet->mergeCells((string) $mergeCell['ref']);
1242
                                    }
1243
                                }
1244
                            }
1245
1246 35
                            if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) {
1247 34
                                $docPageMargins = $docSheet->getPageMargins();
1248 34
                                $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
1249 34
                                $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
1250 34
                                $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
1251 34
                                $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
1252 34
                                $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
1253 34
                                $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
1254
                            }
1255
1256 35
                            if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) {
1257 34
                                $docPageSetup = $docSheet->getPageSetup();
1258
1259 34
                                if (isset($xmlSheet->pageSetup['orientation'])) {
1260 34
                                    $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
1261
                                }
1262 34
                                if (isset($xmlSheet->pageSetup['paperSize'])) {
1263 31
                                    $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
1264
                                }
1265 34
                                if (isset($xmlSheet->pageSetup['scale'])) {
1266 27
                                    $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
1267
                                }
1268 34
                                if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
1269 27
                                    $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
1270
                                }
1271 34
                                if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
1272 27
                                    $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
1273
                                }
1274 34
                                if (isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) &&
1275 34
                                    self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) {
1276
                                    $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
1277
                                }
1278
1279 34
                                $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1280 34
                                if (isset($relAttributes['id'])) {
1281 7
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id'];
1282
                                }
1283
                            }
1284
1285 35
                            if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) {
1286 29
                                $docHeaderFooter = $docSheet->getHeaderFooter();
1287
1288 29
                                if (isset($xmlSheet->headerFooter['differentOddEven']) &&
1289 29
                                    self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) {
1290
                                    $docHeaderFooter->setDifferentOddEven(true);
1291
                                } else {
1292 29
                                    $docHeaderFooter->setDifferentOddEven(false);
1293
                                }
1294 29
                                if (isset($xmlSheet->headerFooter['differentFirst']) &&
1295 29
                                    self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) {
1296
                                    $docHeaderFooter->setDifferentFirst(true);
1297
                                } else {
1298 29
                                    $docHeaderFooter->setDifferentFirst(false);
1299
                                }
1300 29
                                if (isset($xmlSheet->headerFooter['scaleWithDoc']) &&
1301 29
                                    !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) {
1302
                                    $docHeaderFooter->setScaleWithDocument(false);
1303
                                } else {
1304 29
                                    $docHeaderFooter->setScaleWithDocument(true);
1305
                                }
1306 29
                                if (isset($xmlSheet->headerFooter['alignWithMargins']) &&
1307 29
                                    !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) {
1308 3
                                    $docHeaderFooter->setAlignWithMargins(false);
1309
                                } else {
1310 26
                                    $docHeaderFooter->setAlignWithMargins(true);
1311
                                }
1312
1313 29
                                $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
1314 29
                                $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
1315 29
                                $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
1316 29
                                $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
1317 29
                                $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
1318 29
                                $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
1319
                            }
1320
1321 35
                            if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) {
1322
                                foreach ($xmlSheet->rowBreaks->brk as $brk) {
1323
                                    if ($brk['man']) {
1324
                                        $docSheet->setBreak("A$brk[id]", Worksheet::BREAK_ROW);
1325
                                    }
1326
                                }
1327
                            }
1328 35
                            if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) {
1329
                                foreach ($xmlSheet->colBreaks->brk as $brk) {
1330
                                    if ($brk['man']) {
1331
                                        $docSheet->setBreak(Coordinate::stringFromColumnIndex((string) $brk['id'] + 1) . '1', Worksheet::BREAK_COLUMN);
1332
                                    }
1333
                                }
1334
                            }
1335
1336 35
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
1337
                                foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
1338
                                    // Uppercase coordinate
1339
                                    $range = strtoupper($dataValidation['sqref']);
1340
                                    $rangeSet = explode(' ', $range);
1341
                                    foreach ($rangeSet as $range) {
1342
                                        $stRange = $docSheet->shrinkRangeToFit($range);
1343
1344
                                        // Extract all cell references in $range
1345
                                        foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) {
1346
                                            // Create validation
1347
                                            $docValidation = $docSheet->getCell($reference)->getDataValidation();
1348
                                            $docValidation->setType((string) $dataValidation['type']);
1349
                                            $docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
1350
                                            $docValidation->setOperator((string) $dataValidation['operator']);
1351
                                            $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
1352
                                            $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
1353
                                            $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
1354
                                            $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
1355
                                            $docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
1356
                                            $docValidation->setError((string) $dataValidation['error']);
1357
                                            $docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
1358
                                            $docValidation->setPrompt((string) $dataValidation['prompt']);
1359
                                            $docValidation->setFormula1((string) $dataValidation->formula1);
1360
                                            $docValidation->setFormula2((string) $dataValidation->formula2);
1361
                                        }
1362
                                    }
1363
                                }
1364
                            }
1365
1366
                            // unparsed sheet AlternateContent
1367 35
                            if ($xmlSheet && !$this->readDataOnly) {
1368 35
                                $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
1369 35
                                if ($mc->AlternateContent) {
1370 1
                                    foreach ($mc->AlternateContent as $alternateContent) {
1371 1
                                        $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
1372
                                    }
1373
                                }
1374
                            }
1375
1376
                            // Add hyperlinks
1377 35
                            $hyperlinks = [];
1378 35
                            if (!$this->readDataOnly) {
1379
                                // Locate hyperlink relations
1380 35
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1381
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1382 34
                                    $relsWorksheet = simplexml_load_string(
1383 34
                                        $this->securityScan(
1384 34
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1385
                                        ),
1386 34
                                        'SimpleXMLElement',
1387 34
                                        Settings::getLibXmlLoaderOptions()
1388
                                    );
1389 34
                                    foreach ($relsWorksheet->Relationship as $ele) {
1390 10
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1391 10
                                            $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1392
                                        }
1393
                                    }
1394
                                }
1395
1396
                                // Loop through hyperlinks
1397 35
                                if ($xmlSheet && $xmlSheet->hyperlinks) {
1398
                                    /** @var SimpleXMLElement $hyperlink */
1399 2
                                    foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
1400
                                        // Link url
1401 2
                                        $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1402
1403 2
                                        foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
1404 2
                                            $cell = $docSheet->getCell($cellReference);
1405 2
                                            if (isset($linkRel['id'])) {
1406 2
                                                $hyperlinkUrl = $hyperlinks[(string) $linkRel['id']];
1407 2
                                                if (isset($hyperlink['location'])) {
1408
                                                    $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
1409
                                                }
1410 2
                                                $cell->getHyperlink()->setUrl($hyperlinkUrl);
1411 2
                                            } elseif (isset($hyperlink['location'])) {
1412 2
                                                $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
1413
                                            }
1414
1415
                                            // Tooltip
1416 2
                                            if (isset($hyperlink['tooltip'])) {
1417 2
                                                $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
1418
                                            }
1419
                                        }
1420
                                    }
1421
                                }
1422
                            }
1423
1424
                            // Add comments
1425 35
                            $comments = [];
1426 35
                            $vmlComments = [];
1427 35
                            if (!$this->readDataOnly) {
1428
                                // Locate comment relations
1429 35
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1430
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1431 34
                                    $relsWorksheet = simplexml_load_string(
1432 34
                                        $this->securityScan(
1433 34
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1434
                                        ),
1435 34
                                        'SimpleXMLElement',
1436 34
                                        Settings::getLibXmlLoaderOptions()
1437
                                    );
1438 34
                                    foreach ($relsWorksheet->Relationship as $ele) {
1439 10
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
1440 3
                                            $comments[(string) $ele['Id']] = (string) $ele['Target'];
1441
                                        }
1442 10
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1443 10
                                            $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
1444
                                        }
1445
                                    }
1446
                                }
1447
1448
                                // Loop through comments
1449 35
                                foreach ($comments as $relName => $relPath) {
1450
                                    // Load comments file
1451 3
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1452 3
                                    $commentsFile = simplexml_load_string(
1453 3
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1454 3
                                        'SimpleXMLElement',
1455 3
                                        Settings::getLibXmlLoaderOptions()
1456
                                    );
1457
1458
                                    // Utility variables
1459 3
                                    $authors = [];
1460
1461
                                    // Loop through authors
1462 3
                                    foreach ($commentsFile->authors->author as $author) {
1463 3
                                        $authors[] = (string) $author;
1464
                                    }
1465
1466
                                    // Loop through contents
1467 3
                                    foreach ($commentsFile->commentList->comment as $comment) {
1468 3
                                        if (!empty($comment['authorId'])) {
1469
                                            $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]);
1470
                                        }
1471 3
                                        $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text));
1472
                                    }
1473
                                }
1474
1475
                                // later we will remove from it real vmlComments
1476 35
                                $unparsedVmlDrawings = $vmlComments;
1477
1478
                                // Loop through VML comments
1479 35
                                foreach ($vmlComments as $relName => $relPath) {
1480
                                    // Load VML comments file
1481 4
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1482 4
                                    $vmlCommentsFile = simplexml_load_string(
1483 4
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1484 4
                                        'SimpleXMLElement',
1485 4
                                        Settings::getLibXmlLoaderOptions()
1486
                                    );
1487 4
                                    $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1488
1489 4
                                    $shapes = $vmlCommentsFile->xpath('//v:shape');
1490 4
                                    foreach ($shapes as $shape) {
1491 4
                                        $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1492
1493 4
                                        if (isset($shape['style'])) {
1494 4
                                            $style = (string) $shape['style'];
1495 4
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
1496 4
                                            $column = null;
1497 4
                                            $row = null;
1498
1499 4
                                            $clientData = $shape->xpath('.//x:ClientData');
1500 4
                                            if (is_array($clientData) && !empty($clientData)) {
1501 4
                                                $clientData = $clientData[0];
1502
1503 4
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
1504 3
                                                    $temp = $clientData->xpath('.//x:Row');
1505 3
                                                    if (is_array($temp)) {
1506 3
                                                        $row = $temp[0];
1507
                                                    }
1508
1509 3
                                                    $temp = $clientData->xpath('.//x:Column');
1510 3
                                                    if (is_array($temp)) {
1511 3
                                                        $column = $temp[0];
1512
                                                    }
1513
                                                }
1514
                                            }
1515
1516 4
                                            if (($column !== null) && ($row !== null)) {
1517
                                                // Set comment properties
1518 3
                                                $comment = $docSheet->getCommentByColumnAndRow($column + 1, $row + 1);
1519 3
                                                $comment->getFillColor()->setRGB($fillColor);
1520
1521
                                                // Parse style
1522 3
                                                $styleArray = explode(';', str_replace(' ', '', $style));
1523 3
                                                foreach ($styleArray as $stylePair) {
1524 3
                                                    $stylePair = explode(':', $stylePair);
1525
1526 3
                                                    if ($stylePair[0] == 'margin-left') {
1527 3
                                                        $comment->setMarginLeft($stylePair[1]);
1528
                                                    }
1529 3
                                                    if ($stylePair[0] == 'margin-top') {
1530 3
                                                        $comment->setMarginTop($stylePair[1]);
1531
                                                    }
1532 3
                                                    if ($stylePair[0] == 'width') {
1533 3
                                                        $comment->setWidth($stylePair[1]);
1534
                                                    }
1535 3
                                                    if ($stylePair[0] == 'height') {
1536 3
                                                        $comment->setHeight($stylePair[1]);
1537
                                                    }
1538 3
                                                    if ($stylePair[0] == 'visibility') {
1539 3
                                                        $comment->setVisible($stylePair[1] == 'visible');
1540
                                                    }
1541
                                                }
1542
1543 4
                                                unset($unparsedVmlDrawings[$relName]);
1544
                                            }
1545
                                        }
1546
                                    }
1547
                                }
1548
1549
                                // unparsed vmlDrawing
1550 35
                                if ($unparsedVmlDrawings) {
1551 1
                                    foreach ($unparsedVmlDrawings as $rId => $relPath) {
1552 1
                                        $rId = substr($rId, 3); // rIdXXX
1553 1
                                        $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
1554 1
                                        $unparsedVmlDrawing[$rId] = [];
1555 1
                                        $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
1556 1
                                        $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
1557 1
                                        $unparsedVmlDrawing[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
1558 1
                                        unset($unparsedVmlDrawing);
1559
                                    }
1560
                                }
1561
1562
                                // Header/footer images
1563 35
                                if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
1564
                                    if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1565
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1566
                                        $relsWorksheet = simplexml_load_string(
1567
                                            $this->securityScan(
1568
                                                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1569
                                            ),
1570
                                            'SimpleXMLElement',
1571
                                            Settings::getLibXmlLoaderOptions()
1572
                                        );
1573
                                        $vmlRelationship = '';
1574
1575
                                        foreach ($relsWorksheet->Relationship as $ele) {
1576
                                            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1577
                                                $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1578
                                            }
1579
                                        }
1580
1581
                                        if ($vmlRelationship != '') {
1582
                                            // Fetch linked images
1583
                                            //~ http://schemas.openxmlformats.org/package/2006/relationships"
1584
                                            $relsVML = simplexml_load_string(
1585
                                                $this->securityScan(
1586
                                                    $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
1587
                                                ),
1588
                                                'SimpleXMLElement',
1589
                                                Settings::getLibXmlLoaderOptions()
1590
                                            );
1591
                                            $drawings = [];
1592
                                            foreach ($relsVML->Relationship as $ele) {
1593
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1594
                                                    $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
1595
                                                }
1596
                                            }
1597
1598
                                            // Fetch VML document
1599
                                            $vmlDrawing = simplexml_load_string(
1600
                                                $this->securityScan($this->getFromZipArchive($zip, $vmlRelationship)),
1601
                                                'SimpleXMLElement',
1602
                                                Settings::getLibXmlLoaderOptions()
1603
                                            );
1604
                                            $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1605
1606
                                            $hfImages = [];
1607
1608
                                            $shapes = $vmlDrawing->xpath('//v:shape');
1609
                                            foreach ($shapes as $idx => $shape) {
1610
                                                $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1611
                                                $imageData = $shape->xpath('//v:imagedata');
1612
1613
                                                if (!$imageData) {
1614
                                                    continue;
1615
                                                }
1616
1617
                                                $imageData = $imageData[$idx];
1618
1619
                                                $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
1620
                                                $style = self::toCSSArray((string) $shape['style']);
1621
1622
                                                $hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
1623
                                                if (isset($imageData['title'])) {
1624
                                                    $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
1625
                                                }
1626
1627
                                                $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
1628
                                                $hfImages[(string) $shape['id']]->setResizeProportional(false);
1629
                                                $hfImages[(string) $shape['id']]->setWidth($style['width']);
1630
                                                $hfImages[(string) $shape['id']]->setHeight($style['height']);
1631
                                                if (isset($style['margin-left'])) {
1632
                                                    $hfImages[(string) $shape['id']]->setOffsetX($style['margin-left']);
1633
                                                }
1634
                                                $hfImages[(string) $shape['id']]->setOffsetY($style['margin-top']);
1635
                                                $hfImages[(string) $shape['id']]->setResizeProportional(true);
1636
                                            }
1637
1638
                                            $docSheet->getHeaderFooter()->setImages($hfImages);
1639
                                        }
1640
                                    }
1641
                                }
1642
                            }
1643
1644
                            // TODO: Autoshapes from twoCellAnchors!
1645 35
                            if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1646
                                //~ http://schemas.openxmlformats.org/package/2006/relationships"
1647 34
                                $relsWorksheet = simplexml_load_string(
1648 34
                                    $this->securityScan(
1649 34
                                        $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1650
                                    ),
1651 34
                                    'SimpleXMLElement',
1652 34
                                    Settings::getLibXmlLoaderOptions()
1653
                                );
1654 34
                                $drawings = [];
1655 34
                                foreach ($relsWorksheet->Relationship as $ele) {
1656 10
                                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1657 10
                                        $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1658
                                    }
1659
                                }
1660 34
                                if ($xmlSheet->drawing && !$this->readDataOnly) {
1661 5
                                    foreach ($xmlSheet->drawing as $drawing) {
1662 5
                                        $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
1663
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1664 5
                                        $relsDrawing = simplexml_load_string(
1665 5
                                            $this->securityScan(
1666 5
                                                $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
1667
                                            ),
1668 5
                                            'SimpleXMLElement',
1669 5
                                            Settings::getLibXmlLoaderOptions()
1670
                                        );
1671 5
                                        $images = [];
1672
1673 5
                                        if ($relsDrawing && $relsDrawing->Relationship) {
1674 4
                                            foreach ($relsDrawing->Relationship as $ele) {
1675 4
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1676 4
                                                    $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
1677 2
                                                } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
1678 2
                                                    if ($this->includeCharts) {
1679 2
                                                        $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
1680 2
                                                            'id' => (string) $ele['Id'],
1681 4
                                                            'sheet' => $docSheet->getTitle(),
1682
                                                        ];
1683
                                                    }
1684
                                                }
1685
                                            }
1686
                                        }
1687 5
                                        $xmlDrawing = simplexml_load_string(
1688 5
                                            $this->securityScan($this->getFromZipArchive($zip, $fileDrawing)),
1689 5
                                            'SimpleXMLElement',
1690 5
                                            Settings::getLibXmlLoaderOptions()
1691 5
                                        )->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
1692
1693 5
                                        if ($xmlDrawing->oneCellAnchor) {
1694 2
                                            foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
1695 2
                                                if ($oneCellAnchor->pic->blipFill) {
1696
                                                    /** @var SimpleXMLElement $blip */
1697 2
                                                    $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1698
                                                    /** @var SimpleXMLElement $xfrm */
1699 2
                                                    $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1700
                                                    /** @var SimpleXMLElement $outerShdw */
1701 2
                                                    $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1702 2
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1703 2
                                                    $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1704 2
                                                    $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1705 2
                                                    $objDrawing->setPath(
1706 2
                                                        'zip://' . File::realpath($pFilename) . '#' .
1707 2
                                                        $images[(string) self::getArrayItem(
1708 2
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1709 2
                                                            'embed'
1710
                                                        )],
1711 2
                                                        false
1712
                                                    );
1713 2
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
1714 2
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
1715 2
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
1716 2
                                                    $objDrawing->setResizeProportional(false);
1717 2
                                                    $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
1718 2
                                                    $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
1719 2
                                                    if ($xfrm) {
1720 2
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
1721
                                                    }
1722 2
                                                    if ($outerShdw) {
1723 2
                                                        $shadow = $objDrawing->getShadow();
1724 2
                                                        $shadow->setVisible(true);
1725 2
                                                        $shadow->setBlurRadius(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
1726 2
                                                        $shadow->setDistance(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
1727 2
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
1728 2
                                                        $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
1729 2
                                                        $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), 'val'));
1730 2
                                                        $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), 'val') / 1000);
1731
                                                    }
1732 2
                                                    $objDrawing->setWorksheet($docSheet);
1733
                                                } else {
1734
                                                    //    ? Can charts be positioned with a oneCellAnchor ?
1735
                                                    $coordinates = Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1);
1736
                                                    $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff);
1737
                                                    $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
1738
                                                    $width = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx'));
1739 2
                                                    $height = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy'));
1740
                                                }
1741
                                            }
1742
                                        }
1743 5
                                        if ($xmlDrawing->twoCellAnchor) {
1744 2
                                            foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) {
1745 2
                                                if ($twoCellAnchor->pic->blipFill) {
1746 2
                                                    $blip = $twoCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1747 2
                                                    $xfrm = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1748 2
                                                    $outerShdw = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1749 2
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1750 2
                                                    $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1751 2
                                                    $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1752 2
                                                    $objDrawing->setPath(
1753 2
                                                        'zip://' . File::realpath($pFilename) . '#' .
1754 2
                                                        $images[(string) self::getArrayItem(
1755 2
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1756 2
                                                            'embed'
1757
                                                        )],
1758 2
                                                        false
1759
                                                    );
1760 2
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1));
1761 2
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff));
1762 2
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
1763 2
                                                    $objDrawing->setResizeProportional(false);
1764
1765 2
                                                    if ($xfrm) {
1766 2
                                                        $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cx')));
1767 2
                                                        $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cy')));
1768 2
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
1769
                                                    }
1770 2
                                                    if ($outerShdw) {
1771
                                                        $shadow = $objDrawing->getShadow();
1772
                                                        $shadow->setVisible(true);
1773
                                                        $shadow->setBlurRadius(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
1774
                                                        $shadow->setDistance(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
1775
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
1776
                                                        $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
1777
                                                        $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), 'val'));
1778
                                                        $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), 'val') / 1000);
1779
                                                    }
1780 2
                                                    $objDrawing->setWorksheet($docSheet);
1781 2
                                                } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
1782 2
                                                    $fromCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
1783 2
                                                    $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff);
1784 2
                                                    $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
1785 2
                                                    $toCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
1786 2
                                                    $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff);
1787 2
                                                    $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
1788 2
                                                    $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic;
1789
                                                    /** @var SimpleXMLElement $chartRef */
1790 2
                                                    $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart;
1791 2
                                                    $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1792
1793 2
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1794 2
                                                        'fromCoordinate' => $fromCoordinate,
1795 2
                                                        'fromOffsetX' => $fromOffsetX,
1796 2
                                                        'fromOffsetY' => $fromOffsetY,
1797 2
                                                        'toCoordinate' => $toCoordinate,
1798 2
                                                        'toOffsetX' => $toOffsetX,
1799 2
                                                        'toOffsetY' => $toOffsetY,
1800 5
                                                        'worksheetTitle' => $docSheet->getTitle(),
1801
                                                    ];
1802
                                                }
1803
                                            }
1804
                                        }
1805
                                    }
1806
1807
                                    // store original rId of drawing files
1808 5
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = [];
1809 5
                                    foreach ($relsWorksheet->Relationship as $ele) {
1810 5
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1811 5
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = (string) $ele['Id'];
1812
                                        }
1813
                                    }
1814
1815
                                    // unparsed drawing AlternateContent
1816 5
                                    $xmlAltDrawing = simplexml_load_string(
1817 5
                                        $this->securityScan($this->getFromZipArchive($zip, $fileDrawing)),
1818 5
                                        'SimpleXMLElement',
1819 5
                                        Settings::getLibXmlLoaderOptions()
1820 5
                                    )->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
1821
1822 5
                                    if ($xmlAltDrawing->AlternateContent) {
1823 1
                                        foreach ($xmlAltDrawing->AlternateContent as $alternateContent) {
1824 1
                                            $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML();
1825
                                        }
1826
                                    }
1827
                                }
1828
                            }
1829
1830 35
                            $this->readFormControlProperties($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1831 35
                            $this->readPrinterSettings($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1832
1833
                            // Loop through definedNames
1834 35
                            if ($xmlWorkbook->definedNames) {
1835 27
                                foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1836
                                    // Extract range
1837 2
                                    $extractedRange = (string) $definedName;
1838 2
                                    if (($spos = strpos($extractedRange, '!')) !== false) {
1839 2
                                        $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1840
                                    } else {
1841
                                        $extractedRange = str_replace('$', '', $extractedRange);
1842
                                    }
1843
1844
                                    // Valid range?
1845 2
                                    if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') {
1846
                                        continue;
1847
                                    }
1848
1849
                                    // Some definedNames are only applicable if we are on the same sheet...
1850 2
                                    if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) {
1851
                                        // Switch on type
1852 2
                                        switch ((string) $definedName['name']) {
1853 2
                                            case '_xlnm._FilterDatabase':
1854
                                                if ((string) $definedName['hidden'] !== '1') {
1855
                                                    $extractedRange = explode(',', $extractedRange);
1856
                                                    foreach ($extractedRange as $range) {
1857
                                                        $autoFilterRange = $range;
1858
                                                        if (strpos($autoFilterRange, ':') !== false) {
1859
                                                            $docSheet->getAutoFilter()->setRange($autoFilterRange);
1860
                                                        }
1861
                                                    }
1862
                                                }
1863
1864
                                                break;
1865 2
                                            case '_xlnm.Print_Titles':
1866
                                                // Split $extractedRange
1867 1
                                                $extractedRange = explode(',', $extractedRange);
1868
1869
                                                // Set print titles
1870 1
                                                foreach ($extractedRange as $range) {
1871 1
                                                    $matches = [];
1872 1
                                                    $range = str_replace('$', '', $range);
1873
1874
                                                    // check for repeating columns, e g. 'A:A' or 'A:D'
1875 1
                                                    if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
1876
                                                        $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]);
1877 1
                                                    } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
1878
                                                        // check for repeating rows, e.g. '1:1' or '1:5'
1879 1
                                                        $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]);
1880
                                                    }
1881
                                                }
1882
1883 1
                                                break;
1884 1
                                            case '_xlnm.Print_Area':
1885 1
                                                $rangeSets = preg_split("/'(.*?)'(?:![A-Z0-9]+:[A-Z0-9]+,?)/", $extractedRange, PREG_SPLIT_NO_EMPTY);
1886 1
                                                $newRangeSets = [];
1887 1
                                                foreach ($rangeSets as $rangeSet) {
1888 1
                                                    $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark?
1889 1
                                                    $rangeSet = isset($range[1]) ? $range[1] : $range[0];
1890 1
                                                    if (strpos($rangeSet, ':') === false) {
1891
                                                        $rangeSet = $rangeSet . ':' . $rangeSet;
1892
                                                    }
1893 1
                                                    $newRangeSets[] = str_replace('$', '', $rangeSet);
1894
                                                }
1895 1
                                                $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
1896
1897 1
                                                break;
1898
                                            default:
1899 2
                                                break;
1900
                                        }
1901
                                    }
1902
                                }
1903
                            }
1904
1905
                            // Next sheet id
1906 35
                            ++$sheetId;
1907
                        }
1908
1909
                        // Loop through definedNames
1910 35
                        if ($xmlWorkbook->definedNames) {
1911 27
                            foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1912
                                // Extract range
1913 2
                                $extractedRange = (string) $definedName;
1914 2
                                if (($spos = strpos($extractedRange, '!')) !== false) {
1915 2
                                    $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1916
                                } else {
1917
                                    $extractedRange = str_replace('$', '', $extractedRange);
1918
                                }
1919
1920
                                // Valid range?
1921 2
                                if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') {
1922
                                    continue;
1923
                                }
1924
1925
                                // Some definedNames are only applicable if we are on the same sheet...
1926 2
                                if ((string) $definedName['localSheetId'] != '') {
1927
                                    // Local defined name
1928
                                    // Switch on type
1929 2
                                    switch ((string) $definedName['name']) {
1930 2
                                        case '_xlnm._FilterDatabase':
1931 2
                                        case '_xlnm.Print_Titles':
1932 1
                                        case '_xlnm.Print_Area':
1933 2
                                            break;
1934
                                        default:
1935
                                            if ($mapSheetId[(int) $definedName['localSheetId']] !== null) {
1936
                                                $range = explode('!', (string) $definedName);
1937
                                                if (count($range) == 2) {
1938
                                                    $range[0] = str_replace("''", "'", $range[0]);
1939
                                                    $range[0] = str_replace("'", '', $range[0]);
1940
                                                    if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) {
1941
                                                        $extractedRange = str_replace('$', '', $range[1]);
1942
                                                        $scope = $docSheet->getParent()->getSheet($mapSheetId[(int) $definedName['localSheetId']]);
1943
                                                        $excel->addNamedRange(new NamedRange((string) $definedName['name'], $worksheet, $extractedRange, true, $scope));
1944
                                                    }
1945
                                                }
1946
                                            }
1947
1948 2
                                            break;
1949
                                    }
1950
                                } elseif (!isset($definedName['localSheetId'])) {
1951
                                    // "Global" definedNames
1952
                                    $locatedSheet = null;
1953
                                    $extractedSheetName = '';
1954
                                    if (strpos((string) $definedName, '!') !== false) {
1955
                                        // Extract sheet name
1956
                                        $extractedSheetName = Worksheet::extractSheetTitle((string) $definedName, true);
1957
                                        $extractedSheetName = $extractedSheetName[0];
1958
1959
                                        // Locate sheet
1960
                                        $locatedSheet = $excel->getSheetByName($extractedSheetName);
1961
1962
                                        // Modify range
1963
                                        $range = explode('!', $extractedRange);
1964
                                        $extractedRange = isset($range[1]) ? $range[1] : $range[0];
1965
                                    }
1966
1967
                                    if ($locatedSheet !== null) {
1968 2
                                        $excel->addNamedRange(new NamedRange((string) $definedName['name'], $locatedSheet, $extractedRange, false));
1969
                                    }
1970
                                }
1971
                            }
1972
                        }
1973
                    }
1974
1975 35
                    if ((!$this->readDataOnly) || (!empty($this->loadSheetsOnly))) {
1976 35
                        $workbookView = $xmlWorkbook->bookViews->workbookView;
1977
1978
                        // active sheet index
1979 35
                        $activeTab = (int) ($workbookView['activeTab']); // refers to old sheet index
1980
1981
                        // keep active sheet index if sheet is still loaded, else first sheet is set as the active
1982 35
                        if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
1983 35
                            $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
1984
                        } else {
1985
                            if ($excel->getSheetCount() == 0) {
1986
                                $excel->createSheet();
1987
                            }
1988
                            $excel->setActiveSheetIndex(0);
1989
                        }
1990
1991 35
                        if (isset($workbookView['showHorizontalScroll'])) {
1992 27
                            $showHorizontalScroll = (string) $workbookView['showHorizontalScroll'];
1993 27
                            $excel->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll));
1994
                        }
1995
1996 35
                        if (isset($workbookView['showVerticalScroll'])) {
1997 27
                            $showVerticalScroll = (string) $workbookView['showVerticalScroll'];
1998 27
                            $excel->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll));
1999
                        }
2000
2001 35
                        if (isset($workbookView['showSheetTabs'])) {
2002 27
                            $showSheetTabs = (string) $workbookView['showSheetTabs'];
2003 27
                            $excel->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs));
2004
                        }
2005
2006 35
                        if (isset($workbookView['minimized'])) {
2007 27
                            $minimized = (string) $workbookView['minimized'];
2008 27
                            $excel->setMinimized($this->castXsdBooleanToBool($minimized));
2009
                        }
2010
2011 35
                        if (isset($workbookView['autoFilterDateGrouping'])) {
2012 27
                            $autoFilterDateGrouping = (string) $workbookView['autoFilterDateGrouping'];
2013 27
                            $excel->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping));
2014
                        }
2015
2016 35
                        if (isset($workbookView['firstSheet'])) {
2017 27
                            $firstSheet = (string) $workbookView['firstSheet'];
2018 27
                            $excel->setFirstSheetIndex((int) $firstSheet);
2019
                        }
2020
2021 35
                        if (isset($workbookView['visibility'])) {
2022 27
                            $visibility = (string) $workbookView['visibility'];
2023 27
                            $excel->setVisibility($visibility);
2024
                        }
2025
2026 35
                        if (isset($workbookView['tabRatio'])) {
2027 27
                            $tabRatio = (string) $workbookView['tabRatio'];
2028 27
                            $excel->setTabRatio((int) $tabRatio);
2029
                        }
2030
                    }
2031
2032 35
                    break;
2033
            }
2034
        }
2035
2036 35
        if (!$this->readDataOnly) {
2037 35
            $contentTypes = simplexml_load_string(
2038 35
                $this->securityScan(
2039 35
                    $this->getFromZipArchive($zip, '[Content_Types].xml')
2040
                ),
2041 35
                'SimpleXMLElement',
2042 35
                Settings::getLibXmlLoaderOptions()
2043
            );
2044
2045
            // Default content types
2046 35
            foreach ($contentTypes->Default as $contentType) {
2047 35
                switch ($contentType['ContentType']) {
2048 35
                    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings':
2049 8
                        $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType'];
2050
2051 35
                        break;
2052
                }
2053
            }
2054
2055
            // Override content types
2056 35
            foreach ($contentTypes->Override as $contentType) {
2057 35
                switch ($contentType['ContentType']) {
2058 35
                    case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
2059 2
                        if ($this->includeCharts) {
2060 2
                            $chartEntryRef = ltrim($contentType['PartName'], '/');
2061 2
                            $chartElements = simplexml_load_string(
2062 2
                                $this->securityScan(
2063 2
                                    $this->getFromZipArchive($zip, $chartEntryRef)
2064
                                ),
2065 2
                                'SimpleXMLElement',
2066 2
                                Settings::getLibXmlLoaderOptions()
2067
                            );
2068 2
                            $objChart = Chart::readChart($chartElements, basename($chartEntryRef, '.xml'));
2069
2070 2
                            if (isset($charts[$chartEntryRef])) {
2071 2
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
2072 2
                                if (isset($chartDetails[$chartPositionRef])) {
2073 2
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
2074 2
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
2075 2
                                    $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
2076 2
                                    $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
2077
                                }
2078
                            }
2079
                        }
2080
2081 2
                        break;
2082
2083
                    // unparsed
2084 35
                    case 'application/vnd.ms-excel.controlproperties+xml':
2085 1
                        $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
2086
2087 35
                        break;
2088
                }
2089
            }
2090
        }
2091
2092 35
        $excel->setUnparsedLoadedData($unparsedLoadedData);
2093
2094 35
        $zip->close();
2095
2096 35
        return $excel;
2097
    }
2098
2099 35
    private static function readColor($color, $background = false)
2100
    {
2101 35
        if (isset($color['rgb'])) {
2102 30
            return (string) $color['rgb'];
2103 10
        } elseif (isset($color['indexed'])) {
2104 7
            return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
2105 7
        } elseif (isset($color['theme'])) {
2106 6
            if (self::$theme !== null) {
2107 6
                $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
2108 6
                if (isset($color['tint'])) {
2109 1
                    $tintAdjust = (float) $color['tint'];
2110 1
                    $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
2111
                }
2112
2113 6
                return 'FF' . $returnColour;
2114
            }
2115
        }
2116
2117 2
        if ($background) {
2118
            return 'FFFFFFFF';
2119
        }
2120
2121 2
        return 'FF000000';
2122
    }
2123
2124
    /**
2125
     * @param Style $docStyle
2126
     * @param SimpleXMLElement|\stdClass $style
2127
     */
2128 35
    private static function readStyle(Style $docStyle, $style)
2129
    {
2130 35
        $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
2131
2132
        // font
2133 35
        if (isset($style->font)) {
2134 35
            $docStyle->getFont()->setName((string) $style->font->name['val']);
2135 35
            $docStyle->getFont()->setSize((string) $style->font->sz['val']);
2136 35
            if (isset($style->font->b)) {
2137 31
                $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val']));
2138
            }
2139 35
            if (isset($style->font->i)) {
2140 28
                $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val']));
2141
            }
2142 35
            if (isset($style->font->strike)) {
2143 27
                $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val']));
2144
            }
2145 35
            $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color));
2146
2147 35
            if (isset($style->font->u) && !isset($style->font->u['val'])) {
2148
                $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2149 35
            } elseif (isset($style->font->u, $style->font->u['val'])) {
2150 27
                $docStyle->getFont()->setUnderline((string) $style->font->u['val']);
2151
            }
2152
2153 35
            if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) {
2154
                $vertAlign = strtolower((string) $style->font->vertAlign['val']);
2155
                if ($vertAlign == 'superscript') {
2156
                    $docStyle->getFont()->setSuperscript(true);
2157
                }
2158
                if ($vertAlign == 'subscript') {
2159
                    $docStyle->getFont()->setSubscript(true);
2160
                }
2161
            }
2162
        }
2163
2164
        // fill
2165 35
        if (isset($style->fill)) {
2166 35
            if ($style->fill->gradientFill) {
2167
                /** @var SimpleXMLElement $gradientFill */
2168 2
                $gradientFill = $style->fill->gradientFill[0];
2169 2
                if (!empty($gradientFill['type'])) {
2170 2
                    $docStyle->getFill()->setFillType((string) $gradientFill['type']);
2171
                }
2172 2
                $docStyle->getFill()->setRotation((float) ($gradientFill['degree']));
2173 2
                $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
2174 2
                $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
2175 2
                $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
2176 35
            } elseif ($style->fill->patternFill) {
2177 35
                $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid';
2178 35
                $docStyle->getFill()->setFillType($patternType);
2179 35
                if ($style->fill->patternFill->fgColor) {
2180 4
                    $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true));
2181
                } else {
2182 35
                    $docStyle->getFill()->getStartColor()->setARGB('FF000000');
2183
                }
2184 35
                if ($style->fill->patternFill->bgColor) {
2185 5
                    $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true));
2186
                }
2187
            }
2188
        }
2189
2190
        // border
2191 35
        if (isset($style->border)) {
2192 35
            $diagonalUp = self::boolean((string) $style->border['diagonalUp']);
2193 35
            $diagonalDown = self::boolean((string) $style->border['diagonalDown']);
2194 35
            if (!$diagonalUp && !$diagonalDown) {
2195 35
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
2196
            } elseif ($diagonalUp && !$diagonalDown) {
2197
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
2198
            } elseif (!$diagonalUp && $diagonalDown) {
2199
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
2200
            } else {
2201
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
2202
            }
2203 35
            self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
2204 35
            self::readBorder($docStyle->getBorders()->getRight(), $style->border->right);
2205 35
            self::readBorder($docStyle->getBorders()->getTop(), $style->border->top);
2206 35
            self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
2207 35
            self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
2208
        }
2209
2210
        // alignment
2211 35
        if (isset($style->alignment)) {
2212 35
            $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']);
2213 35
            $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']);
2214
2215 35
            $textRotation = 0;
2216 35
            if ((int) $style->alignment['textRotation'] <= 90) {
2217 35
                $textRotation = (int) $style->alignment['textRotation'];
2218
            } elseif ((int) $style->alignment['textRotation'] > 90) {
2219
                $textRotation = 90 - (int) $style->alignment['textRotation'];
2220
            }
2221
2222 35
            $docStyle->getAlignment()->setTextRotation((int) $textRotation);
2223 35
            $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText']));
2224 35
            $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit']));
2225 35
            $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0);
2226 35
            $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0);
2227
        }
2228
2229
        // protection
2230 35
        if (isset($style->protection)) {
2231 35
            if (isset($style->protection['locked'])) {
2232 2
                if (self::boolean((string) $style->protection['locked'])) {
2233
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
2234
                } else {
2235 2
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
2236
                }
2237
            }
2238
2239 35
            if (isset($style->protection['hidden'])) {
2240
                if (self::boolean((string) $style->protection['hidden'])) {
2241
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
2242
                } else {
2243
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
2244
                }
2245
            }
2246
        }
2247
2248
        // top-level style settings
2249 35
        if (isset($style->quotePrefix)) {
2250 35
            $docStyle->setQuotePrefix($style->quotePrefix);
2251
        }
2252 35
    }
2253
2254
    /**
2255
     * @param Border $docBorder
2256
     * @param SimpleXMLElement $eleBorder
2257
     */
2258 35
    private static function readBorder(Border $docBorder, $eleBorder)
2259
    {
2260 35
        if (isset($eleBorder['style'])) {
2261 3
            $docBorder->setBorderStyle((string) $eleBorder['style']);
2262
        }
2263 35
        if (isset($eleBorder->color)) {
2264 3
            $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
2265
        }
2266 35
    }
2267
2268
    /**
2269
     * @param SimpleXMLElement | null $is
2270
     *
2271
     * @return RichText
2272
     */
2273 4
    private function parseRichText($is)
2274
    {
2275 4
        $value = new RichText();
2276
2277 4
        if (isset($is->t)) {
2278
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
2279
        } else {
2280 4
            if (is_object($is->r)) {
2281 4
                foreach ($is->r as $run) {
2282 4
                    if (!isset($run->rPr)) {
2283 4
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2284
                    } else {
2285 3
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2286
2287 3
                        if (isset($run->rPr->rFont['val'])) {
2288 3
                            $objText->getFont()->setName((string) $run->rPr->rFont['val']);
2289
                        }
2290 3
                        if (isset($run->rPr->sz['val'])) {
2291 3
                            $objText->getFont()->setSize((float) $run->rPr->sz['val']);
2292
                        }
2293 3
                        if (isset($run->rPr->color)) {
2294 3
                            $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
2295
                        }
2296 3
                        if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
2297 3
                            (isset($run->rPr->b) && !isset($run->rPr->b['val']))) {
2298 3
                            $objText->getFont()->setBold(true);
2299
                        }
2300 3
                        if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
2301 3
                            (isset($run->rPr->i) && !isset($run->rPr->i['val']))) {
2302 2
                            $objText->getFont()->setItalic(true);
2303
                        }
2304 3
                        if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
2305
                            $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
2306
                            if ($vertAlign == 'superscript') {
2307
                                $objText->getFont()->setSuperscript(true);
2308
                            }
2309
                            if ($vertAlign == 'subscript') {
2310
                                $objText->getFont()->setSubscript(true);
2311
                            }
2312
                        }
2313 3
                        if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
2314
                            $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2315 3
                        } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
2316 2
                            $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
2317
                        }
2318 3
                        if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
2319 3
                            (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) {
2320 4
                            $objText->getFont()->setStrikethrough(true);
2321
                        }
2322
                    }
2323
                }
2324
            }
2325
        }
2326
2327 4
        return $value;
2328
    }
2329
2330
    /**
2331
     * @param Spreadsheet $excel
2332
     * @param mixed $customUITarget
2333
     * @param mixed $zip
2334
     */
2335
    private function readRibbon(Spreadsheet $excel, $customUITarget, $zip)
2336
    {
2337
        $baseDir = dirname($customUITarget);
2338
        $nameCustomUI = basename($customUITarget);
2339
        // get the xml file (ribbon)
2340
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
2341
        $customUIImagesNames = [];
2342
        $customUIImagesBinaries = [];
2343
        // something like customUI/_rels/customUI.xml.rels
2344
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
2345
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
2346
        if ($dataRels) {
2347
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
2348
            $UIRels = simplexml_load_string(
2349
                $this->securityScan($dataRels),
2350
                'SimpleXMLElement',
2351
                Settings::getLibXmlLoaderOptions()
2352
            );
2353
            if (false !== $UIRels) {
2354
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
2355
                foreach ($UIRels->Relationship as $ele) {
2356
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
2357
                        // an image ?
2358
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
2359
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
2360
                    }
2361
                }
2362
            }
2363
        }
2364
        if ($localRibbon) {
2365
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
2366
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2367
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
2368
            } else {
2369
                $excel->setRibbonBinObjects(null, null);
2370
            }
2371
        } else {
2372
            $excel->setRibbonXMLData(null, null);
2373
            $excel->setRibbonBinObjects(null, null);
2374
        }
2375
    }
2376
2377 36
    private static function getArrayItem($array, $key = 0)
2378
    {
2379 36
        return isset($array[$key]) ? $array[$key] : null;
2380
    }
2381
2382 9
    private static function dirAdd($base, $add)
2383
    {
2384 9
        return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
2385
    }
2386
2387
    private static function toCSSArray($style)
2388
    {
2389
        $style = trim(str_replace(["\r", "\n"], '', $style), ';');
2390
2391
        $temp = explode(';', $style);
2392
        $style = [];
2393
        foreach ($temp as $item) {
2394
            $item = explode(':', $item);
2395
2396
            if (strpos($item[1], 'px') !== false) {
2397
                $item[1] = str_replace('px', '', $item[1]);
2398
            }
2399
            if (strpos($item[1], 'pt') !== false) {
2400
                $item[1] = str_replace('pt', '', $item[1]);
2401
                $item[1] = Font::fontSizeToPixels($item[1]);
2402
            }
2403
            if (strpos($item[1], 'in') !== false) {
2404
                $item[1] = str_replace('in', '', $item[1]);
2405
                $item[1] = Font::inchSizeToPixels($item[1]);
2406
            }
2407
            if (strpos($item[1], 'cm') !== false) {
2408
                $item[1] = str_replace('cm', '', $item[1]);
2409
                $item[1] = Font::centimeterSizeToPixels($item[1]);
2410
            }
2411
2412
            $style[$item[0]] = $item[1];
2413
        }
2414
2415
        return $style;
2416
    }
2417
2418 35
    private static function boolean($value)
2419
    {
2420 35
        if (is_object($value)) {
2421 1
            $value = (string) $value;
2422
        }
2423 35
        if (is_numeric($value)) {
2424 32
            return (bool) $value;
2425
        }
2426
2427 35
        return $value === 'true' || $value === 'TRUE';
2428
    }
2429
2430 35
    private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook)
2431
    {
2432 35
        if (!$xmlWorkbook->workbookProtection) {
2433 34
            return;
2434
        }
2435
2436 1
        if ($xmlWorkbook->workbookProtection['lockRevision']) {
2437
            $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']);
2438
        }
2439
2440 1
        if ($xmlWorkbook->workbookProtection['lockStructure']) {
2441 1
            $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']);
2442
        }
2443
2444 1
        if ($xmlWorkbook->workbookProtection['lockWindows']) {
2445
            $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']);
2446
        }
2447
2448 1
        if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
2449
            $excel->getSecurity()->setRevisionsPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true);
2450
        }
2451
2452 1
        if ($xmlWorkbook->workbookProtection['workbookPassword']) {
2453 1
            $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true);
2454
        }
2455 1
    }
2456
2457 35
    private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2458
    {
2459 35
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2460 4
            return;
2461
        }
2462
2463
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2464 34
        $relsWorksheet = simplexml_load_string(
2465 34
            $this->securityScan(
2466 34
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2467
            ),
2468 34
            'SimpleXMLElement',
2469 34
            Settings::getLibXmlLoaderOptions()
2470
        );
2471 34
        $ctrlProps = [];
2472 34
        foreach ($relsWorksheet->Relationship as $ele) {
2473 10
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') {
2474 10
                $ctrlProps[(string) $ele['Id']] = $ele;
2475
            }
2476
        }
2477
2478 34
        $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
2479 34
        foreach ($ctrlProps as $rId => $ctrlProp) {
2480 1
            $rId = substr($rId, 3); // rIdXXX
2481 1
            $unparsedCtrlProps[$rId] = [];
2482 1
            $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
2483 1
            $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
2484 1
            $unparsedCtrlProps[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
2485
        }
2486 34
        unset($unparsedCtrlProps);
2487 34
    }
2488
2489 35
    private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2490
    {
2491 35
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2492 4
            return;
2493
        }
2494
2495
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2496 34
        $relsWorksheet = simplexml_load_string(
2497 34
            $this->securityScan(
2498 34
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2499
            ),
2500 34
            'SimpleXMLElement',
2501 34
            Settings::getLibXmlLoaderOptions()
2502
        );
2503 34
        $sheetPrinterSettings = [];
2504 34
        foreach ($relsWorksheet->Relationship as $ele) {
2505 10
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') {
2506 10
                $sheetPrinterSettings[(string) $ele['Id']] = $ele;
2507
            }
2508
        }
2509
2510 34
        $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
2511 34
        foreach ($sheetPrinterSettings as $rId => $printerSettings) {
2512 7
            $rId = substr($rId, 3); // rIdXXX
2513 7
            $unparsedPrinterSettings[$rId] = [];
2514 7
            $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']);
2515 7
            $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target'];
2516 7
            $unparsedPrinterSettings[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
2517
        }
2518 34
        unset($unparsedPrinterSettings);
2519 34
    }
2520
2521
    /**
2522
     * Convert an 'xsd:boolean' XML value to a PHP boolean value.
2523
     * A valid 'xsd:boolean' XML value can be one of the following
2524
     * four values: 'true', 'false', '1', '0'.  It is case sensitive.
2525
     *
2526
     * Note that just doing '(bool) $xsdBoolean' is not safe,
2527
     * since '(bool) "false"' returns true.
2528
     *
2529
     * @see https://www.w3.org/TR/xmlschema11-2/#boolean
2530
     *
2531
     * @param string $xsdBoolean An XML string value of type 'xsd:boolean'
2532
     *
2533
     * @return bool  Boolean value
2534
     */
2535 27
    private function castXsdBooleanToBool($xsdBoolean)
2536
    {
2537 27
        if ($xsdBoolean === 'false') {
2538 27
            return false;
2539
        }
2540
2541 27
        return (bool) $xsdBoolean;
2542
    }
2543
}
2544