Passed
Push — develop ( b05d07...17d4a5 )
by Adrien
26:16
created

Xlsx::readHyperLinkDrawing()   A

Complexity

Conditions 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

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