Passed
Push — develop ( 57404f...50a9bc )
by Adrien
32:00
created

Xlsx::readColor()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7.0145

Importance

Changes 0
Metric Value
cc 7
eloc 14
nc 8
nop 2
dl 0
loc 23
ccs 14
cts 15
cp 0.9333
crap 7.0145
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
6
use PhpOffice\PhpSpreadsheet\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 42
    public function __construct()
53
    {
54 42
        $this->readFilter = new DefaultReadFilter();
55 42
        $this->referenceHelper = ReferenceHelper::getInstance();
56 42
    }
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]);
0 ignored issues
show
Bug introduced by
'A1' of type string is incompatible with the type integer expected by parameter $pBefore of PhpOffice\PhpSpreadsheet...dateFormulaReferences(). ( Ignorable by Annotation )

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

293
                $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], /** @scrutinizer ignore-type */ 'A1', $difference[0], $difference[1]);
Loading history...
294
            }
295
        }
296 7
    }
297
298
    /**
299
     * @param ZipArchive $archive
300
     * @param string $fileName
301
     *
302
     * @return string
303
     */
304 41
    private function getFromZipArchive(ZipArchive $archive, $fileName = '')
305
    {
306
        // Root-relative paths
307 41
        if (strpos($fileName, '//') !== false) {
308
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
309
        }
310 41
        $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 41
        $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
317 41
        if ($contents === false) {
318 1
            $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
319
        }
320
321 41
        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 9
    private function setColumnAttributes(Worksheet $docSheet, $column, array $columnAttributes)
333
    {
334 9
        if (isset($columnAttributes['xfIndex'])) {
335 4
            $docSheet->getColumnDimension($column)->setXfIndex($columnAttributes['xfIndex']);
336
        }
337 9
        if (isset($columnAttributes['visible'])) {
338 1
            $docSheet->getColumnDimension($column)->setVisible($columnAttributes['visible']);
339
        }
340 9
        if (isset($columnAttributes['collapsed'])) {
341 1
            $docSheet->getColumnDimension($column)->setCollapsed($columnAttributes['collapsed']);
342
        }
343 9
        if (isset($columnAttributes['outlineLevel'])) {
344 1
            $docSheet->getColumnDimension($column)->setOutlineLevel($columnAttributes['outlineLevel']);
345
        }
346 9
        if (isset($columnAttributes['width'])) {
347 9
            $docSheet->getColumnDimension($column)->setWidth($columnAttributes['width']);
348
        }
349 9
    }
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 38
    public function load($pFilename)
388
    {
389 38
        File::assertFile($pFilename);
390
391
        // Initialisations
392 38
        $excel = new Spreadsheet();
393 38
        $excel->removeSheetByIndex(0);
394 38
        if (!$this->readDataOnly) {
395 38
            $excel->removeCellStyleXfByIndex(0); // remove the default style
396 38
            $excel->removeCellXfByIndex(0); // remove the default style
397
        }
398 38
        $unparsedLoadedData = [];
399
400 38
        $zip = new ZipArchive();
401 38
        $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 38
        $wbRels = simplexml_load_string(
406 38
            $this->securityScan($this->getFromZipArchive($zip, 'xl/_rels/workbook.xml.rels')),
407 38
            'SimpleXMLElement',
408 38
            Settings::getLibXmlLoaderOptions()
409
        );
410 38
        foreach ($wbRels->Relationship as $rel) {
411 38
            switch ($rel['Type']) {
412 38
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme':
413 38
                    $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
414 38
                    $themeOrderAdditional = count($themeOrderArray);
415
416 38
                    $xmlTheme = simplexml_load_string(
417 38
                        $this->securityScan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")),
418 38
                        'SimpleXMLElement',
419 38
                        Settings::getLibXmlLoaderOptions()
420
                    );
421 38
                    if (is_object($xmlTheme)) {
422 38
                        $xmlThemeName = $xmlTheme->attributes();
423 38
                        $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
424 38
                        $themeName = (string) $xmlThemeName['name'];
425
426 38
                        $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
427 38
                        $colourSchemeName = (string) $colourScheme['name'];
428 38
                        $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
429
430 38
                        $themeColours = [];
431 38
                        foreach ($colourScheme as $k => $xmlColour) {
432 38
                            $themePos = array_search($k, $themeOrderArray);
433 38
                            if ($themePos === false) {
434 38
                                $themePos = $themeOrderAdditional++;
435
                            }
436 38
                            if (isset($xmlColour->sysClr)) {
437 38
                                $xmlColourData = $xmlColour->sysClr->attributes();
438 38
                                $themeColours[$themePos] = $xmlColourData['lastClr'];
439 38
                            } elseif (isset($xmlColour->srgbClr)) {
440 38
                                $xmlColourData = $xmlColour->srgbClr->attributes();
441 38
                                $themeColours[$themePos] = $xmlColourData['val'];
442
                            }
443
                        }
444 38
                        self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours);
445
                    }
446
447 38
                    break;
448
            }
449
        }
450
451
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
452 38
        $rels = simplexml_load_string(
453 38
            $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels')),
454 38
            'SimpleXMLElement',
455 38
            Settings::getLibXmlLoaderOptions()
456
        );
457 38
        foreach ($rels->Relationship as $rel) {
458 38
            switch ($rel['Type']) {
459 38
                case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties':
460 37
                    $xmlCore = simplexml_load_string(
461 37
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
462 37
                        'SimpleXMLElement',
463 37
                        Settings::getLibXmlLoaderOptions()
464
                    );
465 37
                    if (is_object($xmlCore)) {
466 37
                        $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/');
467 37
                        $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/');
468 37
                        $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
469 37
                        $docProps = $excel->getProperties();
470 37
                        $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator')));
471 37
                        $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy')));
472 37
                        $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type
473 37
                        $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type
474 37
                        $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title')));
475 37
                        $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description')));
476 37
                        $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject')));
477 37
                        $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath('cp:keywords')));
478 37
                        $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath('cp:category')));
479
                    }
480
481 37
                    break;
482 38
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties':
483 37
                    $xmlCore = simplexml_load_string(
484 37
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
485 37
                        'SimpleXMLElement',
486 37
                        Settings::getLibXmlLoaderOptions()
487
                    );
488 37
                    if (is_object($xmlCore)) {
489 37
                        $docProps = $excel->getProperties();
490 37
                        if (isset($xmlCore->Company)) {
491 35
                            $docProps->setCompany((string) $xmlCore->Company);
492
                        }
493 37
                        if (isset($xmlCore->Manager)) {
494 32
                            $docProps->setManager((string) $xmlCore->Manager);
495
                        }
496
                    }
497
498 37
                    break;
499 38
                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 38
                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 38
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
532 38
                    $dir = dirname($rel['Target']);
533
                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
534 38
                    $relsWorkbook = simplexml_load_string(
535 38
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')),
536 38
                        'SimpleXMLElement',
537 38
                        Settings::getLibXmlLoaderOptions()
538
                    );
539 38
                    $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
540
541 38
                    $sharedStrings = [];
542 38
                    $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 38
                    $xmlStrings = simplexml_load_string(
545 38
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
546 38
                        'SimpleXMLElement',
547 38
                        Settings::getLibXmlLoaderOptions()
548
                    );
549 38
                    if (isset($xmlStrings, $xmlStrings->si)) {
550 19
                        foreach ($xmlStrings->si as $val) {
551 19
                            if (isset($val->t)) {
552 19
                                $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
553 3
                            } elseif (isset($val->r)) {
554 19
                                $sharedStrings[] = $this->parseRichText($val);
555
                            }
556
                        }
557
                    }
558
559 38
                    $worksheets = [];
560 38
                    $macros = $customUI = null;
561 38
                    foreach ($relsWorkbook->Relationship as $ele) {
562 38
                        switch ($ele['Type']) {
563 38
                            case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet':
564 38
                                $worksheets[(string) $ele['Id']] = $ele['Target'];
565
566 38
                                break;
567
                            // a vbaProject ? (: some macros)
568 38
                            case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject':
569 1
                                $macros = $ele['Target'];
570
571 38
                                break;
572
                        }
573
                    }
574
575 38
                    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 38
                    $styles = [];
588 38
                    $cellStyles = [];
589 38
                    $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 38
                    $xmlStyles = simplexml_load_string(
592 38
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
593 38
                        'SimpleXMLElement',
594 38
                        Settings::getLibXmlLoaderOptions()
595
                    );
596 38
                    $numFmts = null;
597 38
                    if ($xmlStyles && $xmlStyles->numFmts[0]) {
598 31
                        $numFmts = $xmlStyles->numFmts[0];
599
                    }
600 38
                    if (isset($numFmts) && ($numFmts !== null)) {
601 31
                        $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
602
                    }
603 38
                    if (!$this->readDataOnly && $xmlStyles) {
604 38
                        foreach ($xmlStyles->cellXfs->xf as $xf) {
605 38
                            $numFmt = NumberFormat::FORMAT_GENERAL;
606
607 38
                            if ($xf['numFmtId']) {
608 38
                                if (isset($numFmts)) {
609 31
                                    $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
610
611 31
                                    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 38
                                if ((int) $xf['numFmtId'] < 164 &&
620 38
                                    NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '') {
621 38
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
622
                                }
623
                            }
624 38
                            $quotePrefix = false;
625 38
                            if (isset($xf['quotePrefix'])) {
626
                                $quotePrefix = (bool) $xf['quotePrefix'];
627
                            }
628
629
                            $style = (object) [
630 38
                                'numFmt' => $numFmt,
631 38
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
632 38
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
633 38
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
634 38
                                'alignment' => $xf->alignment,
635 38
                                'protection' => $xf->protection,
636 38
                                'quotePrefix' => $quotePrefix,
637
                            ];
638 38
                            $styles[] = $style;
639
640
                            // add style to cellXf collection
641 38
                            $objStyle = new Style();
642 38
                            self::readStyle($objStyle, $style);
643 38
                            $excel->addCellXf($objStyle);
644
                        }
645
646 38
                        foreach (isset($xmlStyles->cellStyleXfs->xf) ? $xmlStyles->cellStyleXfs->xf : [] as $xf) {
647 38
                            $numFmt = NumberFormat::FORMAT_GENERAL;
648 38
                            if ($numFmts && $xf['numFmtId']) {
649 31
                                $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
650 31
                                if (isset($tmpNumFmt['formatCode'])) {
651 1
                                    $numFmt = (string) $tmpNumFmt['formatCode'];
652 31
                                } elseif ((int) $xf['numFmtId'] < 165) {
653 31
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
654
                                }
655
                            }
656
657
                            $cellStyle = (object) [
658 38
                                'numFmt' => $numFmt,
659 38
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
660 38
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
661 38
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
662 38
                                'alignment' => $xf->alignment,
663 38
                                'protection' => $xf->protection,
664 38
                                'quotePrefix' => $quotePrefix,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $quotePrefix does not seem to be defined for all execution paths leading up to this point.
Loading history...
665
                            ];
666 38
                            $cellStyles[] = $cellStyle;
667
668
                            // add style to cellStyleXf collection
669 38
                            $objStyle = new Style();
670 38
                            self::readStyle($objStyle, $cellStyle);
671 38
                            $excel->addCellStyleXf($objStyle);
672
                        }
673
                    }
674
675 38
                    $dxfs = [];
676 38
                    if (!$this->readDataOnly && $xmlStyles) {
677
                        //    Conditional Styles
678 38
                        if ($xmlStyles->dxfs) {
679 38
                            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 38
                        if ($xmlStyles->cellStyles) {
687 38
                            foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) {
688 38
                                if ((int) ($cellStyle['builtinId']) == 0) {
689 38
                                    if (isset($cellStyles[(int) ($cellStyle['xfId'])])) {
690
                                        // Set default style
691 38
                                        $style = new Style();
692 38
                                        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 38
                    $xmlWorkbook = simplexml_load_string(
703 38
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
704 38
                        'SimpleXMLElement',
705 38
                        Settings::getLibXmlLoaderOptions()
706
                    );
707
708
                    // Set base date
709 38
                    if ($xmlWorkbook->workbookPr) {
710 37
                        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
711 37
                        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 38
                    $this->readProtection($excel, $xmlWorkbook);
1 ignored issue
show
Bug introduced by
It seems like $xmlWorkbook can also be of type false; however, parameter $xmlWorkbook of PhpOffice\PhpSpreadsheet...\Xlsx::readProtection() does only seem to accept SimpleXMLElement, maybe add an additional type check? ( Ignorable by Annotation )

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

719
                    $this->readProtection($excel, /** @scrutinizer ignore-type */ $xmlWorkbook);
Loading history...
720
721 38
                    $sheetId = 0; // keep track of new sheet id in final workbook
722 38
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
723 38
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
724 38
                    $mapSheetId = []; // mapping of sheet ids from old to new
725
726 38
                    $charts = $chartDetails = [];
727
728 38
                    if ($xmlWorkbook->sheets) {
729
                        /** @var SimpleXMLElement $eleSheet */
730 38
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
731 38
                            ++$oldSheetId;
732
733
                            // Check if sheet should be skipped
734 38
                            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 38
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
744
745
                            // Load sheet
746 38
                            $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 38
                            $docSheet->setTitle((string) $eleSheet['name'], false, false);
752 38
                            $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
753
                            //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
754 38
                            $xmlSheet = simplexml_load_string(
755 38
                                $this->securityScan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")),
756 38
                                'SimpleXMLElement',
757 38
                                Settings::getLibXmlLoaderOptions()
758
                            );
759
760 38
                            $sharedFormulas = [];
761
762 38
                            if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') {
763 1
                                $docSheet->setSheetState((string) $eleSheet['state']);
764
                            }
765
766 38
                            if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) {
767 38
                                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 38
                                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 38
                                if (isset($xmlSheet->sheetViews->sheetView['view'])) {
788
                                    $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']);
789
                                }
790 38
                                if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
791 30
                                    $docSheet->setShowGridLines(self::boolean((string) $xmlSheet->sheetViews->sheetView['showGridLines']));
792
                                }
793 38
                                if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
794 30
                                    $docSheet->setShowRowColHeaders(self::boolean((string) $xmlSheet->sheetViews->sheetView['showRowColHeaders']));
795
                                }
796 38
                                if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
797
                                    $docSheet->setRightToLeft(self::boolean((string) $xmlSheet->sheetViews->sheetView['rightToLeft']));
798
                                }
799 38
                                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 38
                                if (isset($xmlSheet->sheetViews->sheetView->selection)) {
820 36
                                    if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
821 35
                                        $sqref = (string) $xmlSheet->sheetViews->sheetView->selection['sqref'];
822 35
                                        $sqref = explode(' ', $sqref);
823 35
                                        $sqref = $sqref[0];
824 35
                                        $docSheet->setSelectedCells($sqref);
825
                                    }
826
                                }
827
                            }
828
829 38
                            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 38
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr['codeName'])) {
835 1
                                $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName'], false);
836
                            }
837 38
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->outlinePr)) {
838 30
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) &&
839 30
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) {
840
                                    $docSheet->setShowSummaryRight(false);
841
                                } else {
842 30
                                    $docSheet->setShowSummaryRight(true);
843
                                }
844
845 30
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) &&
846 30
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) {
847
                                    $docSheet->setShowSummaryBelow(false);
848
                                } else {
849 30
                                    $docSheet->setShowSummaryBelow(true);
850
                                }
851
                            }
852
853 38
                            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 38
                            if (isset($xmlSheet->sheetFormatPr)) {
863 38
                                if (isset($xmlSheet->sheetFormatPr['customHeight']) &&
864 38
                                    self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) &&
865 38
                                    isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
866 1
                                    $docSheet->getDefaultRowDimension()->setRowHeight((float) $xmlSheet->sheetFormatPr['defaultRowHeight']);
867
                                }
868 38
                                if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
869 1
                                    $docSheet->getDefaultColumnDimension()->setWidth((float) $xmlSheet->sheetFormatPr['defaultColWidth']);
870
                                }
871 38
                                if (isset($xmlSheet->sheetFormatPr['zeroHeight']) &&
872 38
                                    ((string) $xmlSheet->sheetFormatPr['zeroHeight'] == '1')) {
873
                                    $docSheet->getDefaultRowDimension()->setZeroHeight(true);
874
                                }
875
                            }
876
877 38
                            if (isset($xmlSheet->printOptions) && !$this->readDataOnly) {
878 30
                                if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) {
879 30
                                    $docSheet->setShowGridlines(true);
880
                                }
881 30
                                if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) {
882
                                    $docSheet->setPrintGridlines(true);
883
                                }
884 30
                                if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) {
885
                                    $docSheet->getPageSetup()->setHorizontalCentered(true);
886
                                }
887 30
                                if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) {
888
                                    $docSheet->getPageSetup()->setVerticalCentered(true);
889
                                }
890
                            }
891
892 38
                            $this->readColumnsAndRowsAttributes($xmlSheet, $docSheet);
1 ignored issue
show
Bug introduced by
It seems like $xmlSheet can also be of type false; however, parameter $xmlSheet of PhpOffice\PhpSpreadsheet...umnsAndRowsAttributes() does only seem to accept SimpleXMLElement, maybe add an additional type check? ( Ignorable by Annotation )

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

892
                            $this->readColumnsAndRowsAttributes(/** @scrutinizer ignore-type */ $xmlSheet, $docSheet);
Loading history...
893
894 38
                            if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
895 32
                                $cIndex = 1; // Cell Start from 1
896 32
                                foreach ($xmlSheet->sheetData->row as $row) {
897 32
                                    $rowIndex = 1;
898 32
                                    foreach ($row->c as $c) {
899 32
                                        $r = (string) $c['r'];
900 32
                                        if ($r == '') {
901 1
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
902
                                        }
903 32
                                        $cellDataType = (string) $c['t'];
904 32
                                        $value = null;
905 32
                                        $calculatedValue = null;
906
907
                                        // Read cell?
908 32
                                        if ($this->getReadFilter() !== null) {
909 32
                                            $coordinates = Coordinate::coordinateFromString($r);
910
911 32
                                            if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) {
912 2
                                                continue;
913
                                            }
914
                                        }
915
916
                                        // Read cell!
917
                                        switch ($cellDataType) {
918 32
                                            case 's':
919 19
                                                if ((string) $c->v != '') {
920 19
                                                    $value = $sharedStrings[(int) ($c->v)];
921
922 19
                                                    if ($value instanceof RichText) {
923 19
                                                        $value = clone $value;
924
                                                    }
925
                                                } else {
926
                                                    $value = '';
927
                                                }
928
929 19
                                                break;
930 22
                                            case 'b':
931 4
                                                if (!isset($c->f)) {
932 2
                                                    $value = self::castToBoolean($c);
933
                                                } else {
934
                                                    // Formula
935 2
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean');
936 2
                                                    if (isset($c->f['t'])) {
937
                                                        $att = $c->f;
938
                                                        $docSheet->getCell($r)->setFormulaAttributes($att);
939
                                                    }
940
                                                }
941
942 4
                                                break;
943 19
                                            case 'inlineStr':
944 2
                                                if (isset($c->f)) {
945
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
946
                                                } else {
947 2
                                                    $value = $this->parseRichText($c->is);
948
                                                }
949
950 2
                                                break;
951 19
                                            case 'e':
952
                                                if (!isset($c->f)) {
953
                                                    $value = self::castToError($c);
954
                                                } else {
955
                                                    // Formula
956
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
957
                                                }
958
959
                                                break;
960
                                            default:
961 19
                                                if (!isset($c->f)) {
962 17
                                                    $value = self::castToString($c);
963
                                                } else {
964
                                                    // Formula
965 6
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
966
                                                }
967
968 19
                                                break;
969
                                        }
970
971
                                        // Check for numeric values
972 32
                                        if (is_numeric($value) && $cellDataType != 's') {
973 15
                                            if ($value == (int) $value) {
974 14
                                                $value = (int) $value;
975 1
                                            } elseif ($value == (float) $value) {
976 1
                                                $value = (float) $value;
977
                                            } elseif ($value == (float) $value) {
978
                                                $value = (float) $value;
979
                                            }
980
                                        }
981
982
                                        // Rich text?
983 32
                                        if ($value instanceof RichText && $this->readDataOnly) {
984
                                            $value = $value->getPlainText();
985
                                        }
986
987 32
                                        $cell = $docSheet->getCell($r);
988
                                        // Assign value
989 32
                                        if ($cellDataType != '') {
990 23
                                            $cell->setValueExplicit($value, $cellDataType);
991
                                        } else {
992 17
                                            $cell->setValue($value);
993
                                        }
994 32
                                        if ($calculatedValue !== null) {
995 7
                                            $cell->setCalculatedValue($calculatedValue);
996
                                        }
997
998
                                        // Style information?
999 32
                                        if ($c['s'] && !$this->readDataOnly) {
1000
                                            // no style index means 0, it seems
1001 7
                                            $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
1002 7
                                                (int) ($c['s']) : 0);
1003
                                        }
1004 32
                                        $rowIndex += 1;
1005
                                    }
1006 32
                                    $cIndex += 1;
1007
                                }
1008
                            }
1009
1010 38
                            $conditionals = [];
1011 38
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
1012 1
                                foreach ($xmlSheet->conditionalFormatting as $conditional) {
1013 1
                                    foreach ($conditional->cfRule as $cfRule) {
1014 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'])])) {
1015 1
                                            $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
1016
                                        }
1017
                                    }
1018
                                }
1019
1020 1
                                foreach ($conditionals as $ref => $cfRules) {
1021 1
                                    ksort($cfRules);
1022 1
                                    $conditionalStyles = [];
1023 1
                                    foreach ($cfRules as $cfRule) {
1024 1
                                        $objConditional = new Conditional();
1025 1
                                        $objConditional->setConditionType((string) $cfRule['type']);
1026 1
                                        $objConditional->setOperatorType((string) $cfRule['operator']);
1027
1028 1
                                        if ((string) $cfRule['text'] != '') {
1029
                                            $objConditional->setText((string) $cfRule['text']);
1030
                                        }
1031
1032 1
                                        if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
1033 1
                                            $objConditional->setStopIfTrue(true);
1034
                                        }
1035
1036 1
                                        if (count($cfRule->formula) > 1) {
1037
                                            foreach ($cfRule->formula as $formula) {
1038
                                                $objConditional->addCondition((string) $formula);
1039
                                            }
1040
                                        } else {
1041 1
                                            $objConditional->addCondition((string) $cfRule->formula);
1042
                                        }
1043 1
                                        $objConditional->setStyle(clone $dxfs[(int) ($cfRule['dxfId'])]);
1044 1
                                        $conditionalStyles[] = $objConditional;
1045
                                    }
1046
1047
                                    // Extract all cell references in $ref
1048 1
                                    $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
1049 1
                                    foreach ($cellBlocks as $cellBlock) {
1050 1
                                        $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
1051
                                    }
1052
                                }
1053
                            }
1054
1055 38
                            $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
1056 38
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1057 33
                                foreach ($aKeys as $key) {
1058 33
                                    $method = 'set' . ucfirst($key);
1059 33
                                    $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
1060
                                }
1061
                            }
1062
1063 38
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1064 33
                                $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true);
1065 33
                                if ($xmlSheet->protectedRanges->protectedRange) {
1066 2
                                    foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
1067 2
                                        $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
1068
                                    }
1069
                                }
1070
                            }
1071
1072 38
                            if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
1073
                                $autoFilterRange = (string) $xmlSheet->autoFilter['ref'];
1074
                                if (strpos($autoFilterRange, ':') !== false) {
1075
                                    $autoFilter = $docSheet->getAutoFilter();
1076
                                    $autoFilter->setRange($autoFilterRange);
1077
1078
                                    foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
1079
                                        $column = $autoFilter->getColumnByOffset((int) $filterColumn['colId']);
1080
                                        //    Check for standard filters
1081
                                        if ($filterColumn->filters) {
1082
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
1083
                                            $filters = $filterColumn->filters;
1084
                                            if ((isset($filters['blank'])) && ($filters['blank'] == 1)) {
1085
                                                //    Operator is undefined, but always treated as EQUAL
1086
                                                $column->createRule()->setRule(null, '')->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1087
                                            }
1088
                                            //    Standard filters are always an OR join, so no join rule needs to be set
1089
                                            //    Entries can be either filter elements
1090
                                            foreach ($filters->filter as $filterRule) {
1091
                                                //    Operator is undefined, but always treated as EQUAL
1092
                                                $column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1093
                                            }
1094
                                            //    Or Date Group elements
1095
                                            foreach ($filters->dateGroupItem as $dateGroupItem) {
1096
                                                //    Operator is undefined, but always treated as EQUAL
1097
                                                $column->createRule()->setRule(
1098
                                                    null,
1099
                                                    [
1100
                                                        'year' => (string) $dateGroupItem['year'],
1101
                                                        'month' => (string) $dateGroupItem['month'],
1102
                                                        'day' => (string) $dateGroupItem['day'],
1103
                                                        'hour' => (string) $dateGroupItem['hour'],
1104
                                                        'minute' => (string) $dateGroupItem['minute'],
1105
                                                        'second' => (string) $dateGroupItem['second'],
1106
                                                    ],
1107
                                                    (string) $dateGroupItem['dateTimeGrouping']
1108
                                                )
1109
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP);
1110
                                            }
1111
                                        }
1112
                                        //    Check for custom filters
1113
                                        if ($filterColumn->customFilters) {
1114
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
1115
                                            $customFilters = $filterColumn->customFilters;
1116
                                            //    Custom filters can an AND or an OR join;
1117
                                            //        and there should only ever be one or two entries
1118
                                            if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
1119
                                                $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
1120
                                            }
1121
                                            foreach ($customFilters->customFilter as $filterRule) {
1122
                                                $column->createRule()->setRule(
1123
                                                    (string) $filterRule['operator'],
1124
                                                    (string) $filterRule['val']
1125
                                                )
1126
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
1127
                                            }
1128
                                        }
1129
                                        //    Check for dynamic filters
1130
                                        if ($filterColumn->dynamicFilter) {
1131
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
1132
                                            //    We should only ever have one dynamic filter
1133
                                            foreach ($filterColumn->dynamicFilter as $filterRule) {
1134
                                                //    Operator is undefined, but always treated as EQUAL
1135
                                                $column->createRule()->setRule(
1136
                                                    null,
1137
                                                    (string) $filterRule['val'],
1138
                                                    (string) $filterRule['type']
1139
                                                )
1140
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
1141
                                                if (isset($filterRule['val'])) {
1142
                                                    $column->setAttribute('val', (string) $filterRule['val']);
1143
                                                }
1144
                                                if (isset($filterRule['maxVal'])) {
1145
                                                    $column->setAttribute('maxVal', (string) $filterRule['maxVal']);
1146
                                                }
1147
                                            }
1148
                                        }
1149
                                        //    Check for dynamic filters
1150
                                        if ($filterColumn->top10) {
1151
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
1152
                                            //    We should only ever have one top10 filter
1153
                                            foreach ($filterColumn->top10 as $filterRule) {
1154
                                                $column->createRule()->setRule(
1155
                                                    (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
1156
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
1157
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
1158
                                                    ),
1159
                                                    (string) $filterRule['val'],
1160
                                                    (((isset($filterRule['top'])) && ($filterRule['top'] == 1))
1161
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
1162
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
1163
                                                    )
1164
                                                )
1165
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
1166
                                            }
1167
                                        }
1168
                                    }
1169
                                }
1170
                            }
1171
1172 38
                            if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
1173 6
                                foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
1174 6
                                    $mergeRef = (string) $mergeCell['ref'];
1175 6
                                    if (strpos($mergeRef, ':') !== false) {
1176 6
                                        $docSheet->mergeCells((string) $mergeCell['ref']);
1177
                                    }
1178
                                }
1179
                            }
1180
1181 38
                            if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) {
1182 37
                                $docPageMargins = $docSheet->getPageMargins();
1183 37
                                $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
1184 37
                                $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
1185 37
                                $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
1186 37
                                $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
1187 37
                                $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
1188 37
                                $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
1189
                            }
1190
1191 38
                            if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) {
1192 37
                                $docPageSetup = $docSheet->getPageSetup();
1193
1194 37
                                if (isset($xmlSheet->pageSetup['orientation'])) {
1195 37
                                    $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
1196
                                }
1197 37
                                if (isset($xmlSheet->pageSetup['paperSize'])) {
1198 34
                                    $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
1199
                                }
1200 37
                                if (isset($xmlSheet->pageSetup['scale'])) {
1201 30
                                    $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
1202
                                }
1203 37
                                if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
1204 30
                                    $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
1205
                                }
1206 37
                                if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
1207 30
                                    $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
1208
                                }
1209 37
                                if (isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) &&
1210 37
                                    self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) {
1211
                                    $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
1212
                                }
1213
1214 37
                                $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1215 37
                                if (isset($relAttributes['id'])) {
1216 7
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id'];
1217
                                }
1218
                            }
1219
1220 38
                            if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) {
1221 32
                                $docHeaderFooter = $docSheet->getHeaderFooter();
1222
1223 32
                                if (isset($xmlSheet->headerFooter['differentOddEven']) &&
1224 32
                                    self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) {
1225
                                    $docHeaderFooter->setDifferentOddEven(true);
1226
                                } else {
1227 32
                                    $docHeaderFooter->setDifferentOddEven(false);
1228
                                }
1229 32
                                if (isset($xmlSheet->headerFooter['differentFirst']) &&
1230 32
                                    self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) {
1231
                                    $docHeaderFooter->setDifferentFirst(true);
1232
                                } else {
1233 32
                                    $docHeaderFooter->setDifferentFirst(false);
1234
                                }
1235 32
                                if (isset($xmlSheet->headerFooter['scaleWithDoc']) &&
1236 32
                                    !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) {
1237
                                    $docHeaderFooter->setScaleWithDocument(false);
1238
                                } else {
1239 32
                                    $docHeaderFooter->setScaleWithDocument(true);
1240
                                }
1241 32
                                if (isset($xmlSheet->headerFooter['alignWithMargins']) &&
1242 32
                                    !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) {
1243 3
                                    $docHeaderFooter->setAlignWithMargins(false);
1244
                                } else {
1245 29
                                    $docHeaderFooter->setAlignWithMargins(true);
1246
                                }
1247
1248 32
                                $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
1249 32
                                $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
1250 32
                                $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
1251 32
                                $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
1252 32
                                $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
1253 32
                                $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
1254
                            }
1255
1256 38
                            if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) {
1257
                                foreach ($xmlSheet->rowBreaks->brk as $brk) {
1258
                                    if ($brk['man']) {
1259
                                        $docSheet->setBreak("A$brk[id]", Worksheet::BREAK_ROW);
1260
                                    }
1261
                                }
1262
                            }
1263 38
                            if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) {
1264
                                foreach ($xmlSheet->colBreaks->brk as $brk) {
1265
                                    if ($brk['man']) {
1266
                                        $docSheet->setBreak(Coordinate::stringFromColumnIndex((string) $brk['id'] + 1) . '1', Worksheet::BREAK_COLUMN);
1267
                                    }
1268
                                }
1269
                            }
1270
1271 38
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
1272
                                foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
1273
                                    // Uppercase coordinate
1274
                                    $range = strtoupper($dataValidation['sqref']);
1275
                                    $rangeSet = explode(' ', $range);
1276
                                    foreach ($rangeSet as $range) {
1277
                                        $stRange = $docSheet->shrinkRangeToFit($range);
1278
1279
                                        // Extract all cell references in $range
1280
                                        foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) {
1281
                                            // Create validation
1282
                                            $docValidation = $docSheet->getCell($reference)->getDataValidation();
1283
                                            $docValidation->setType((string) $dataValidation['type']);
1284
                                            $docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
1285
                                            $docValidation->setOperator((string) $dataValidation['operator']);
1286
                                            $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
1287
                                            $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
1288
                                            $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
1289
                                            $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
1290
                                            $docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
1291
                                            $docValidation->setError((string) $dataValidation['error']);
1292
                                            $docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
1293
                                            $docValidation->setPrompt((string) $dataValidation['prompt']);
1294
                                            $docValidation->setFormula1((string) $dataValidation->formula1);
1295
                                            $docValidation->setFormula2((string) $dataValidation->formula2);
1296
                                        }
1297
                                    }
1298
                                }
1299
                            }
1300
1301
                            // unparsed sheet AlternateContent
1302 38
                            if ($xmlSheet && !$this->readDataOnly) {
1303 38
                                $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
1304 38
                                if ($mc->AlternateContent) {
1305 1
                                    foreach ($mc->AlternateContent as $alternateContent) {
1306 1
                                        $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
1307
                                    }
1308
                                }
1309
                            }
1310
1311
                            // Add hyperlinks
1312 38
                            $hyperlinks = [];
1313 38
                            if (!$this->readDataOnly) {
1314
                                // Locate hyperlink relations
1315 38
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1316
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1317 37
                                    $relsWorksheet = simplexml_load_string(
1318 37
                                        $this->securityScan(
1319 37
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1320
                                        ),
1321 37
                                        'SimpleXMLElement',
1322 37
                                        Settings::getLibXmlLoaderOptions()
1323
                                    );
1324 37
                                    foreach ($relsWorksheet->Relationship as $ele) {
1325 12
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1326 12
                                            $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1327
                                        }
1328
                                    }
1329
                                }
1330
1331
                                // Loop through hyperlinks
1332 38
                                if ($xmlSheet && $xmlSheet->hyperlinks) {
1333
                                    /** @var SimpleXMLElement $hyperlink */
1334 2
                                    foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
1335
                                        // Link url
1336 2
                                        $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1337
1338 2
                                        foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
1339 2
                                            $cell = $docSheet->getCell($cellReference);
1340 2
                                            if (isset($linkRel['id'])) {
1341 2
                                                $hyperlinkUrl = $hyperlinks[(string) $linkRel['id']];
1342 2
                                                if (isset($hyperlink['location'])) {
1343
                                                    $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
1344
                                                }
1345 2
                                                $cell->getHyperlink()->setUrl($hyperlinkUrl);
1346 2
                                            } elseif (isset($hyperlink['location'])) {
1347 2
                                                $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
1348
                                            }
1349
1350
                                            // Tooltip
1351 2
                                            if (isset($hyperlink['tooltip'])) {
1352 2
                                                $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
1353
                                            }
1354
                                        }
1355
                                    }
1356
                                }
1357
                            }
1358
1359
                            // Add comments
1360 38
                            $comments = [];
1361 38
                            $vmlComments = [];
1362 38
                            if (!$this->readDataOnly) {
1363
                                // Locate comment relations
1364 38
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1365
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1366 37
                                    $relsWorksheet = simplexml_load_string(
1367 37
                                        $this->securityScan(
1368 37
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1369
                                        ),
1370 37
                                        'SimpleXMLElement',
1371 37
                                        Settings::getLibXmlLoaderOptions()
1372
                                    );
1373 37
                                    foreach ($relsWorksheet->Relationship as $ele) {
1374 12
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
1375 3
                                            $comments[(string) $ele['Id']] = (string) $ele['Target'];
1376
                                        }
1377 12
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1378 12
                                            $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
1379
                                        }
1380
                                    }
1381
                                }
1382
1383
                                // Loop through comments
1384 38
                                foreach ($comments as $relName => $relPath) {
1385
                                    // Load comments file
1386 3
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1387 3
                                    $commentsFile = simplexml_load_string(
1388 3
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1389 3
                                        'SimpleXMLElement',
1390 3
                                        Settings::getLibXmlLoaderOptions()
1391
                                    );
1392
1393
                                    // Utility variables
1394 3
                                    $authors = [];
1395
1396
                                    // Loop through authors
1397 3
                                    foreach ($commentsFile->authors->author as $author) {
1398 3
                                        $authors[] = (string) $author;
1399
                                    }
1400
1401
                                    // Loop through contents
1402 3
                                    foreach ($commentsFile->commentList->comment as $comment) {
1403 3
                                        if (!empty($comment['authorId'])) {
1404
                                            $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]);
1405
                                        }
1406 3
                                        $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text));
1407
                                    }
1408
                                }
1409
1410
                                // later we will remove from it real vmlComments
1411 38
                                $unparsedVmlDrawings = $vmlComments;
1412
1413
                                // Loop through VML comments
1414 38
                                foreach ($vmlComments as $relName => $relPath) {
1415
                                    // Load VML comments file
1416 4
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1417 4
                                    $vmlCommentsFile = simplexml_load_string(
1418 4
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1419 4
                                        'SimpleXMLElement',
1420 4
                                        Settings::getLibXmlLoaderOptions()
1421
                                    );
1422 4
                                    $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1423
1424 4
                                    $shapes = $vmlCommentsFile->xpath('//v:shape');
1425 4
                                    foreach ($shapes as $shape) {
1426 4
                                        $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1427
1428 4
                                        if (isset($shape['style'])) {
1429 4
                                            $style = (string) $shape['style'];
1430 4
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
1431 4
                                            $column = null;
1432 4
                                            $row = null;
1433
1434 4
                                            $clientData = $shape->xpath('.//x:ClientData');
1435 4
                                            if (is_array($clientData) && !empty($clientData)) {
1436 4
                                                $clientData = $clientData[0];
1437
1438 4
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
1439 3
                                                    $temp = $clientData->xpath('.//x:Row');
1440 3
                                                    if (is_array($temp)) {
1441 3
                                                        $row = $temp[0];
1442
                                                    }
1443
1444 3
                                                    $temp = $clientData->xpath('.//x:Column');
1445 3
                                                    if (is_array($temp)) {
1446 3
                                                        $column = $temp[0];
1447
                                                    }
1448
                                                }
1449
                                            }
1450
1451 4
                                            if (($column !== null) && ($row !== null)) {
1452
                                                // Set comment properties
1453 3
                                                $comment = $docSheet->getCommentByColumnAndRow($column + 1, $row + 1);
1454 3
                                                $comment->getFillColor()->setRGB($fillColor);
1455
1456
                                                // Parse style
1457 3
                                                $styleArray = explode(';', str_replace(' ', '', $style));
1458 3
                                                foreach ($styleArray as $stylePair) {
1459 3
                                                    $stylePair = explode(':', $stylePair);
1460
1461 3
                                                    if ($stylePair[0] == 'margin-left') {
1462 3
                                                        $comment->setMarginLeft($stylePair[1]);
1463
                                                    }
1464 3
                                                    if ($stylePair[0] == 'margin-top') {
1465 3
                                                        $comment->setMarginTop($stylePair[1]);
1466
                                                    }
1467 3
                                                    if ($stylePair[0] == 'width') {
1468 3
                                                        $comment->setWidth($stylePair[1]);
1469
                                                    }
1470 3
                                                    if ($stylePair[0] == 'height') {
1471 3
                                                        $comment->setHeight($stylePair[1]);
1472
                                                    }
1473 3
                                                    if ($stylePair[0] == 'visibility') {
1474 3
                                                        $comment->setVisible($stylePair[1] == 'visible');
1475
                                                    }
1476
                                                }
1477
1478 4
                                                unset($unparsedVmlDrawings[$relName]);
1479
                                            }
1480
                                        }
1481
                                    }
1482
                                }
1483
1484
                                // unparsed vmlDrawing
1485 38
                                if ($unparsedVmlDrawings) {
1486 1
                                    foreach ($unparsedVmlDrawings as $rId => $relPath) {
1487 1
                                        $rId = substr($rId, 3); // rIdXXX
1488 1
                                        $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
1489 1
                                        $unparsedVmlDrawing[$rId] = [];
1490 1
                                        $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
1491 1
                                        $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
1492 1
                                        $unparsedVmlDrawing[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
1493 1
                                        unset($unparsedVmlDrawing);
1494
                                    }
1495
                                }
1496
1497
                                // Header/footer images
1498 38
                                if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
1499
                                    if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1500
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1501
                                        $relsWorksheet = simplexml_load_string(
1502
                                            $this->securityScan(
1503
                                                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1504
                                            ),
1505
                                            'SimpleXMLElement',
1506
                                            Settings::getLibXmlLoaderOptions()
1507
                                        );
1508
                                        $vmlRelationship = '';
1509
1510
                                        foreach ($relsWorksheet->Relationship as $ele) {
1511
                                            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1512
                                                $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1513
                                            }
1514
                                        }
1515
1516
                                        if ($vmlRelationship != '') {
1517
                                            // Fetch linked images
1518
                                            //~ http://schemas.openxmlformats.org/package/2006/relationships"
1519
                                            $relsVML = simplexml_load_string(
1520
                                                $this->securityScan(
1521
                                                    $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
1522
                                                ),
1523
                                                'SimpleXMLElement',
1524
                                                Settings::getLibXmlLoaderOptions()
1525
                                            );
1526
                                            $drawings = [];
1527
                                            foreach ($relsVML->Relationship as $ele) {
1528
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1529
                                                    $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
1530
                                                }
1531
                                            }
1532
1533
                                            // Fetch VML document
1534
                                            $vmlDrawing = simplexml_load_string(
1535
                                                $this->securityScan($this->getFromZipArchive($zip, $vmlRelationship)),
1536
                                                'SimpleXMLElement',
1537
                                                Settings::getLibXmlLoaderOptions()
1538
                                            );
1539
                                            $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1540
1541
                                            $hfImages = [];
1542
1543
                                            $shapes = $vmlDrawing->xpath('//v:shape');
1544
                                            foreach ($shapes as $idx => $shape) {
1545
                                                $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1546
                                                $imageData = $shape->xpath('//v:imagedata');
1547
1548
                                                if (!$imageData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $imageData of type SimpleXMLElement[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1549
                                                    continue;
1550
                                                }
1551
1552
                                                $imageData = $imageData[$idx];
1553
1554
                                                $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
1555
                                                $style = self::toCSSArray((string) $shape['style']);
1556
1557
                                                $hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
1558
                                                if (isset($imageData['title'])) {
1559
                                                    $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
1560
                                                }
1561
1562
                                                $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
1563
                                                $hfImages[(string) $shape['id']]->setResizeProportional(false);
1564
                                                $hfImages[(string) $shape['id']]->setWidth($style['width']);
1565
                                                $hfImages[(string) $shape['id']]->setHeight($style['height']);
1566
                                                if (isset($style['margin-left'])) {
1567
                                                    $hfImages[(string) $shape['id']]->setOffsetX($style['margin-left']);
1568
                                                }
1569
                                                $hfImages[(string) $shape['id']]->setOffsetY($style['margin-top']);
1570
                                                $hfImages[(string) $shape['id']]->setResizeProportional(true);
1571
                                            }
1572
1573
                                            $docSheet->getHeaderFooter()->setImages($hfImages);
1574
                                        }
1575
                                    }
1576
                                }
1577
                            }
1578
1579
                            // TODO: Autoshapes from twoCellAnchors!
1580 38
                            if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1581
                                //~ http://schemas.openxmlformats.org/package/2006/relationships"
1582 37
                                $relsWorksheet = simplexml_load_string(
1583 37
                                    $this->securityScan(
1584 37
                                        $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1585
                                    ),
1586 37
                                    'SimpleXMLElement',
1587 37
                                    Settings::getLibXmlLoaderOptions()
1588
                                );
1589 37
                                $drawings = [];
1590 37
                                foreach ($relsWorksheet->Relationship as $ele) {
1591 12
                                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1592 12
                                        $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1593
                                    }
1594
                                }
1595 37
                                if ($xmlSheet->drawing && !$this->readDataOnly) {
1596 7
                                    foreach ($xmlSheet->drawing as $drawing) {
1597 7
                                        $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
1598
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1599 7
                                        $relsDrawing = simplexml_load_string(
1600 7
                                            $this->securityScan(
1601 7
                                                $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
1602
                                            ),
1603 7
                                            'SimpleXMLElement',
1604 7
                                            Settings::getLibXmlLoaderOptions()
1605
                                        );
1606 7
                                        $images = [];
1607 7
                                        $hyperlinks = [];
1608 7
                                        if ($relsDrawing && $relsDrawing->Relationship) {
1609 6
                                            foreach ($relsDrawing->Relationship as $ele) {
1610 6
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1611 2
                                                    $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1612
                                                }
1613 6
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1614 6
                                                    $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
1615 4
                                                } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
1616 2
                                                    if ($this->includeCharts) {
1617 2
                                                        $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
1618 2
                                                            'id' => (string) $ele['Id'],
1619 6
                                                            'sheet' => $docSheet->getTitle(),
1620
                                                        ];
1621
                                                    }
1622
                                                }
1623
                                            }
1624
                                        }
1625 7
                                        $xmlDrawing = simplexml_load_string(
1626 7
                                            $this->securityScan($this->getFromZipArchive($zip, $fileDrawing)),
1627 7
                                            'SimpleXMLElement',
1628 7
                                            Settings::getLibXmlLoaderOptions()
1629 7
                                        )->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
1630
1631 7
                                        if ($xmlDrawing->oneCellAnchor) {
1632 4
                                            foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
1633 4
                                                if ($oneCellAnchor->pic->blipFill) {
1634
                                                    /** @var SimpleXMLElement $blip */
1635 4
                                                    $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1636
                                                    /** @var SimpleXMLElement $xfrm */
1637 4
                                                    $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1638
                                                    /** @var SimpleXMLElement $outerShdw */
1639 4
                                                    $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1640
                                                    /** @var \SimpleXMLElement $hlinkClick */
1641 4
                                                    $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
0 ignored issues
show
Unused Code introduced by
The assignment to $hlinkClick is dead and can be removed.
Loading history...
1642
1643 4
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1644 4
                                                    $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1645 4
                                                    $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1646 4
                                                    $objDrawing->setPath(
1647 4
                                                        'zip://' . File::realpath($pFilename) . '#' .
1648 4
                                                        $images[(string) self::getArrayItem(
1649 4
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1650 4
                                                            'embed'
1651
                                                        )],
1652 4
                                                        false
1653
                                                    );
1654 4
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
1655 4
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
1656 4
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
1657 4
                                                    $objDrawing->setResizeProportional(false);
1658 4
                                                    $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
1659 4
                                                    $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
1660 4
                                                    if ($xfrm) {
1661 4
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
1 ignored issue
show
Bug introduced by
It seems like self::getArrayItem($xfrm->attributes(), 'rot') can also be of type SimpleXMLElement; however, parameter $pValue of PhpOffice\PhpSpreadsheet...awing::angleToDegrees() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

1666
                                                        $shadow->setBlurRadius(Drawing::EMUTopixels(/** @scrutinizer ignore-type */ self::getArrayItem($outerShdw->attributes(), 'blurRad')));
Loading history...
1667 2
                                                        $shadow->setDistance(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
1668 2
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
1669 2
                                                        $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
0 ignored issues
show
Bug introduced by
(string)self::getArrayIt...->attributes(), 'algn') of type string is incompatible with the type integer expected by parameter $pValue of PhpOffice\PhpSpreadsheet...\Shadow::setAlignment(). ( Ignorable by Annotation )

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

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

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

2014
                            $objChart = Chart::readChart(/** @scrutinizer ignore-type */ $chartElements, basename($chartEntryRef, '.xml'));
Loading history...
2015
2016 2
                            if (isset($charts[$chartEntryRef])) {
2017 2
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
2018 2
                                if (isset($chartDetails[$chartPositionRef])) {
2019 2
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
2020 2
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
2021 2
                                    $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
2022 2
                                    $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
2023
                                }
2024
                            }
2025
                        }
2026
2027 2
                        break;
2028
2029
                    // unparsed
2030 38
                    case 'application/vnd.ms-excel.controlproperties+xml':
2031 1
                        $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
2032
2033 38
                        break;
2034
                }
2035
            }
2036
        }
2037
2038 38
        $excel->setUnparsedLoadedData($unparsedLoadedData);
2039
2040 38
        $zip->close();
2041
2042 38
        return $excel;
2043
    }
2044
2045 38
    private static function readColor($color, $background = false)
2046
    {
2047 38
        if (isset($color['rgb'])) {
2048 33
            return (string) $color['rgb'];
2049 10
        } elseif (isset($color['indexed'])) {
2050 7
            return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
2051 7
        } elseif (isset($color['theme'])) {
2052 6
            if (self::$theme !== null) {
2053 6
                $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
2054 6
                if (isset($color['tint'])) {
2055 1
                    $tintAdjust = (float) $color['tint'];
2056 1
                    $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
2057
                }
2058
2059 6
                return 'FF' . $returnColour;
2060
            }
2061
        }
2062
2063 2
        if ($background) {
2064
            return 'FFFFFFFF';
2065
        }
2066
2067 2
        return 'FF000000';
2068
    }
2069
2070
    /**
2071
     * @param Style $docStyle
2072
     * @param SimpleXMLElement|\stdClass $style
2073
     */
2074 38
    private static function readStyle(Style $docStyle, $style)
2075
    {
2076 38
        $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
2077
2078
        // font
2079 38
        if (isset($style->font)) {
2080 38
            $docStyle->getFont()->setName((string) $style->font->name['val']);
2081 38
            $docStyle->getFont()->setSize((string) $style->font->sz['val']);
0 ignored issues
show
Bug introduced by
(string)$style->font->sz['val'] of type string is incompatible with the type double expected by parameter $pValue of PhpOffice\PhpSpreadsheet\Style\Font::setSize(). ( Ignorable by Annotation )

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

2081
            $docStyle->getFont()->setSize(/** @scrutinizer ignore-type */ (string) $style->font->sz['val']);
Loading history...
2082 38
            if (isset($style->font->b)) {
2083 34
                $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val']));
2084
            }
2085 38
            if (isset($style->font->i)) {
2086 31
                $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val']));
2087
            }
2088 38
            if (isset($style->font->strike)) {
2089 30
                $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val']));
2090
            }
2091 38
            $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color));
2092
2093 38
            if (isset($style->font->u) && !isset($style->font->u['val'])) {
2094
                $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2095 38
            } elseif (isset($style->font->u, $style->font->u['val'])) {
2096 30
                $docStyle->getFont()->setUnderline((string) $style->font->u['val']);
2097
            }
2098
2099 38
            if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) {
2100
                $vertAlign = strtolower((string) $style->font->vertAlign['val']);
2101
                if ($vertAlign == 'superscript') {
2102
                    $docStyle->getFont()->setSuperscript(true);
2103
                }
2104
                if ($vertAlign == 'subscript') {
2105
                    $docStyle->getFont()->setSubscript(true);
2106
                }
2107
            }
2108
        }
2109
2110
        // fill
2111 38
        if (isset($style->fill)) {
2112 38
            if ($style->fill->gradientFill) {
2113
                /** @var SimpleXMLElement $gradientFill */
2114 2
                $gradientFill = $style->fill->gradientFill[0];
2115 2
                if (!empty($gradientFill['type'])) {
2116 2
                    $docStyle->getFill()->setFillType((string) $gradientFill['type']);
2117
                }
2118 2
                $docStyle->getFill()->setRotation((float) ($gradientFill['degree']));
2119 2
                $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
2120 2
                $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
2121 2
                $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
2122 38
            } elseif ($style->fill->patternFill) {
2123 38
                $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid';
2124 38
                $docStyle->getFill()->setFillType($patternType);
2125 38
                if ($style->fill->patternFill->fgColor) {
2126 4
                    $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true));
2127
                } else {
2128 38
                    $docStyle->getFill()->getStartColor()->setARGB('FF000000');
2129
                }
2130 38
                if ($style->fill->patternFill->bgColor) {
2131 5
                    $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true));
2132
                }
2133
            }
2134
        }
2135
2136
        // border
2137 38
        if (isset($style->border)) {
2138 38
            $diagonalUp = self::boolean((string) $style->border['diagonalUp']);
2139 38
            $diagonalDown = self::boolean((string) $style->border['diagonalDown']);
2140 38
            if (!$diagonalUp && !$diagonalDown) {
2141 38
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
2142
            } elseif ($diagonalUp && !$diagonalDown) {
2143
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
2144
            } elseif (!$diagonalUp && $diagonalDown) {
2145
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
2146
            } else {
2147
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
2148
            }
2149 38
            self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
2150 38
            self::readBorder($docStyle->getBorders()->getRight(), $style->border->right);
2151 38
            self::readBorder($docStyle->getBorders()->getTop(), $style->border->top);
2152 38
            self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
2153 38
            self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
2154
        }
2155
2156
        // alignment
2157 38
        if (isset($style->alignment)) {
2158 38
            $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']);
2159 38
            $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']);
2160
2161 38
            $textRotation = 0;
2162 38
            if ((int) $style->alignment['textRotation'] <= 90) {
2163 38
                $textRotation = (int) $style->alignment['textRotation'];
2164
            } elseif ((int) $style->alignment['textRotation'] > 90) {
2165
                $textRotation = 90 - (int) $style->alignment['textRotation'];
2166
            }
2167
2168 38
            $docStyle->getAlignment()->setTextRotation((int) $textRotation);
2169 38
            $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText']));
2170 38
            $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit']));
2171 38
            $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0);
2172 38
            $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0);
2173
        }
2174
2175
        // protection
2176 38
        if (isset($style->protection)) {
2177 38
            if (isset($style->protection['locked'])) {
2178 2
                if (self::boolean((string) $style->protection['locked'])) {
2179
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
2180
                } else {
2181 2
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
2182
                }
2183
            }
2184
2185 38
            if (isset($style->protection['hidden'])) {
2186
                if (self::boolean((string) $style->protection['hidden'])) {
2187
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
2188
                } else {
2189
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
2190
                }
2191
            }
2192
        }
2193
2194
        // top-level style settings
2195 38
        if (isset($style->quotePrefix)) {
2196 38
            $docStyle->setQuotePrefix($style->quotePrefix);
0 ignored issues
show
Bug introduced by
$style->quotePrefix of type SimpleXMLElement is incompatible with the type boolean expected by parameter $pValue of PhpOffice\PhpSpreadsheet...Style::setQuotePrefix(). ( Ignorable by Annotation )

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

2196
            $docStyle->setQuotePrefix(/** @scrutinizer ignore-type */ $style->quotePrefix);
Loading history...
2197
        }
2198 38
    }
2199
2200
    /**
2201
     * @param Border $docBorder
2202
     * @param SimpleXMLElement $eleBorder
2203
     */
2204 38
    private static function readBorder(Border $docBorder, $eleBorder)
2205
    {
2206 38
        if (isset($eleBorder['style'])) {
2207 3
            $docBorder->setBorderStyle((string) $eleBorder['style']);
2208
        }
2209 38
        if (isset($eleBorder->color)) {
2210 3
            $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
2211
        }
2212 38
    }
2213
2214
    /**
2215
     * @param SimpleXMLElement | null $is
2216
     *
2217
     * @return RichText
2218
     */
2219 4
    private function parseRichText($is)
2220
    {
2221 4
        $value = new RichText();
2222
2223 4
        if (isset($is->t)) {
2224
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
2225
        } else {
2226 4
            if (is_object($is->r)) {
2227 4
                foreach ($is->r as $run) {
2228 4
                    if (!isset($run->rPr)) {
2229 4
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2230
                    } else {
2231 3
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2232
2233 3
                        if (isset($run->rPr->rFont['val'])) {
2234 3
                            $objText->getFont()->setName((string) $run->rPr->rFont['val']);
2235
                        }
2236 3
                        if (isset($run->rPr->sz['val'])) {
2237 3
                            $objText->getFont()->setSize((float) $run->rPr->sz['val']);
2238
                        }
2239 3
                        if (isset($run->rPr->color)) {
2240 3
                            $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
2241
                        }
2242 3
                        if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
2243 3
                            (isset($run->rPr->b) && !isset($run->rPr->b['val']))) {
2244 3
                            $objText->getFont()->setBold(true);
2245
                        }
2246 3
                        if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
2247 3
                            (isset($run->rPr->i) && !isset($run->rPr->i['val']))) {
2248 2
                            $objText->getFont()->setItalic(true);
2249
                        }
2250 3
                        if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
2251
                            $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
2252
                            if ($vertAlign == 'superscript') {
2253
                                $objText->getFont()->setSuperscript(true);
2254
                            }
2255
                            if ($vertAlign == 'subscript') {
2256
                                $objText->getFont()->setSubscript(true);
2257
                            }
2258
                        }
2259 3
                        if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
2260
                            $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2261 3
                        } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
2262 2
                            $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
2263
                        }
2264 3
                        if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
2265 3
                            (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) {
2266 4
                            $objText->getFont()->setStrikethrough(true);
2267
                        }
2268
                    }
2269
                }
2270
            }
2271
        }
2272
2273 4
        return $value;
2274
    }
2275
2276
    /**
2277
     * @param Spreadsheet $excel
2278
     * @param mixed $customUITarget
2279
     * @param mixed $zip
2280
     */
2281
    private function readRibbon(Spreadsheet $excel, $customUITarget, $zip)
2282
    {
2283
        $baseDir = dirname($customUITarget);
2284
        $nameCustomUI = basename($customUITarget);
2285
        // get the xml file (ribbon)
2286
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
2287
        $customUIImagesNames = [];
2288
        $customUIImagesBinaries = [];
2289
        // something like customUI/_rels/customUI.xml.rels
2290
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
2291
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
2292
        if ($dataRels) {
2293
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
2294
            $UIRels = simplexml_load_string(
2295
                $this->securityScan($dataRels),
2296
                'SimpleXMLElement',
2297
                Settings::getLibXmlLoaderOptions()
2298
            );
2299
            if (false !== $UIRels) {
2300
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
2301
                foreach ($UIRels->Relationship as $ele) {
2302
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
2303
                        // an image ?
2304
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
2305
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
2306
                    }
2307
                }
2308
            }
2309
        }
2310
        if ($localRibbon) {
2311
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
2312
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2313
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
2314
            } else {
2315
                $excel->setRibbonBinObjects(null, null);
2316
            }
2317
        } else {
2318
            $excel->setRibbonXMLData(null, null);
2319
            $excel->setRibbonBinObjects(null, null);
2320
        }
2321
    }
2322
2323 39
    private static function getArrayItem($array, $key = 0)
2324
    {
2325 39
        return isset($array[$key]) ? $array[$key] : null;
2326
    }
2327
2328 11
    private static function dirAdd($base, $add)
2329
    {
2330 11
        return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
2331
    }
2332
2333
    private static function toCSSArray($style)
2334
    {
2335
        $style = trim(str_replace(["\r", "\n"], '', $style), ';');
2336
2337
        $temp = explode(';', $style);
2338
        $style = [];
2339
        foreach ($temp as $item) {
2340
            $item = explode(':', $item);
2341
2342
            if (strpos($item[1], 'px') !== false) {
2343
                $item[1] = str_replace('px', '', $item[1]);
2344
            }
2345
            if (strpos($item[1], 'pt') !== false) {
2346
                $item[1] = str_replace('pt', '', $item[1]);
2347
                $item[1] = Font::fontSizeToPixels($item[1]);
2348
            }
2349
            if (strpos($item[1], 'in') !== false) {
2350
                $item[1] = str_replace('in', '', $item[1]);
2351
                $item[1] = Font::inchSizeToPixels($item[1]);
2352
            }
2353
            if (strpos($item[1], 'cm') !== false) {
2354
                $item[1] = str_replace('cm', '', $item[1]);
2355
                $item[1] = Font::centimeterSizeToPixels($item[1]);
2356
            }
2357
2358
            $style[$item[0]] = $item[1];
2359
        }
2360
2361
        return $style;
2362
    }
2363
2364 38
    private static function boolean($value)
2365
    {
2366 38
        if (is_object($value)) {
2367 1
            $value = (string) $value;
2368
        }
2369 38
        if (is_numeric($value)) {
2370 35
            return (bool) $value;
2371
        }
2372
2373 38
        return $value === 'true' || $value === 'TRUE';
2374
    }
2375
2376
    /**
2377
     * @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing
2378
     * @param \SimpleXMLElement $cellAnchor
2379
     * @param array $hyperlinks
2380
     */
2381 6
    private function readHyperLinkDrawing($objDrawing, $cellAnchor, $hyperlinks)
2382
    {
2383 6
        $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
2384
2385 6
        if ($hlinkClick->count() === 0) {
2386 4
            return;
2387
        }
2388
2389 2
        $hlinkId = (string) $hlinkClick->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id'];
2390 2
        $hyperlink = new Hyperlink(
2391 2
            $hyperlinks[$hlinkId],
2392 2
            (string) self::getArrayItem($cellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')
2393
        );
2394 2
        $objDrawing->setHyperlink($hyperlink);
2395 2
    }
2396
2397 38
    private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook)
2398
    {
2399 38
        if (!$xmlWorkbook->workbookProtection) {
2400 37
            return;
2401
        }
2402
2403 1
        if ($xmlWorkbook->workbookProtection['lockRevision']) {
2404
            $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']);
2405
        }
2406
2407 1
        if ($xmlWorkbook->workbookProtection['lockStructure']) {
2408 1
            $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']);
2409
        }
2410
2411 1
        if ($xmlWorkbook->workbookProtection['lockWindows']) {
2412
            $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']);
2413
        }
2414
2415 1
        if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
2416
            $excel->getSecurity()->setRevisionsPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true);
2417
        }
2418
2419 1
        if ($xmlWorkbook->workbookProtection['workbookPassword']) {
2420 1
            $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true);
2421
        }
2422 1
    }
2423
2424 38
    private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2425
    {
2426 38
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2427 4
            return;
2428
        }
2429
2430
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2431 37
        $relsWorksheet = simplexml_load_string(
2432 37
            $this->securityScan(
2433 37
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2434
            ),
2435 37
            'SimpleXMLElement',
2436 37
            Settings::getLibXmlLoaderOptions()
2437
        );
2438 37
        $ctrlProps = [];
2439 37
        foreach ($relsWorksheet->Relationship as $ele) {
2440 12
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') {
2441 12
                $ctrlProps[(string) $ele['Id']] = $ele;
2442
            }
2443
        }
2444
2445 37
        $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
2446 37
        foreach ($ctrlProps as $rId => $ctrlProp) {
2447 1
            $rId = substr($rId, 3); // rIdXXX
2448 1
            $unparsedCtrlProps[$rId] = [];
2449 1
            $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
2450 1
            $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
2451 1
            $unparsedCtrlProps[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
2452
        }
2453 37
        unset($unparsedCtrlProps);
2454 37
    }
2455
2456 38
    private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2457
    {
2458 38
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2459 4
            return;
2460
        }
2461
2462
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2463 37
        $relsWorksheet = simplexml_load_string(
2464 37
            $this->securityScan(
2465 37
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2466
            ),
2467 37
            'SimpleXMLElement',
2468 37
            Settings::getLibXmlLoaderOptions()
2469
        );
2470 37
        $sheetPrinterSettings = [];
2471 37
        foreach ($relsWorksheet->Relationship as $ele) {
2472 12
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') {
2473 12
                $sheetPrinterSettings[(string) $ele['Id']] = $ele;
2474
            }
2475
        }
2476
2477 37
        $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
2478 37
        foreach ($sheetPrinterSettings as $rId => $printerSettings) {
2479 7
            $rId = substr($rId, 3); // rIdXXX
2480 7
            $unparsedPrinterSettings[$rId] = [];
2481 7
            $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']);
2482 7
            $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target'];
2483 7
            $unparsedPrinterSettings[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
2484
        }
2485 37
        unset($unparsedPrinterSettings);
2486 37
    }
2487
2488
    /**
2489
     * Convert an 'xsd:boolean' XML value to a PHP boolean value.
2490
     * A valid 'xsd:boolean' XML value can be one of the following
2491
     * four values: 'true', 'false', '1', '0'.  It is case sensitive.
2492
     *
2493
     * Note that just doing '(bool) $xsdBoolean' is not safe,
2494
     * since '(bool) "false"' returns true.
2495
     *
2496
     * @see https://www.w3.org/TR/xmlschema11-2/#boolean
2497
     *
2498
     * @param string $xsdBoolean An XML string value of type 'xsd:boolean'
2499
     *
2500
     * @return bool  Boolean value
2501
     */
2502 30
    private function castXsdBooleanToBool($xsdBoolean)
2503
    {
2504 30
        if ($xsdBoolean === 'false') {
2505 30
            return false;
2506
        }
2507
2508 30
        return (bool) $xsdBoolean;
2509
    }
2510
2511
    /**
2512
     * Read columns and rows attributes from XML and set them on the worksheet.
2513
     *
2514
     * @param SimpleXMLElement $xmlSheet
2515
     * @param Worksheet $docSheet
2516
     */
2517 38
    private function readColumnsAndRowsAttributes(SimpleXMLElement $xmlSheet, Worksheet $docSheet)
2518
    {
2519 38
        $columnsAttributes = [];
2520 38
        $rowsAttributes = [];
2521 38
        if (isset($xmlSheet->cols) && !$this->readDataOnly) {
2522 9
            foreach ($xmlSheet->cols->col as $col) {
2523 9
                for ($i = (int) ($col['min']); $i <= (int) ($col['max']); ++$i) {
2524 9
                    if ($col['style'] && !$this->readDataOnly) {
2525 4
                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['xfIndex'] = (int) $col['style'];
2526
                    }
2527 9
                    if (self::boolean($col['hidden'])) {
2528 1
                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['visible'] = false;
2529
                    }
2530 9
                    if (self::boolean($col['collapsed'])) {
2531 1
                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['collapsed'] = true;
2532
                    }
2533 9
                    if ($col['outlineLevel'] > 0) {
2534 1
                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['outlineLevel'] = (int) $col['outlineLevel'];
2535
                    }
2536 9
                    $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['width'] = (float) $col['width'];
2537
2538 9
                    if ((int) ($col['max']) == 16384) {
2539
                        break;
2540
                    }
2541
                }
2542
            }
2543
        }
2544
2545 38
        if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
2546 32
            foreach ($xmlSheet->sheetData->row as $row) {
2547 32
                if ($row['ht'] && !$this->readDataOnly) {
2548 3
                    $rowsAttributes[(int) $row['r']]['rowHeight'] = (float) $row['ht'];
2549
                }
2550 32
                if (self::boolean($row['hidden']) && !$this->readDataOnly) {
2551
                    $rowsAttributes[(int) $row['r']]['visible'] = false;
2552
                }
2553 32
                if (self::boolean($row['collapsed'])) {
2554
                    $rowsAttributes[(int) $row['r']]['collapsed'] = true;
2555
                }
2556 32
                if ($row['outlineLevel'] > 0) {
2557
                    $rowsAttributes[(int) $row['r']]['outlineLevel'] = (int) $row['outlineLevel'];
2558
                }
2559 32
                if ($row['s'] && !$this->readDataOnly) {
2560 32
                    $rowsAttributes[(int) $row['r']]['xfIndex'] = (int) $row['s'];
2561
                }
2562
            }
2563
        }
2564
2565
        // set columns/rows attributes
2566 38
        $columnsAttributesSet = [];
2567 38
        $rowsAttributesSet = [];
2568 38
        foreach ($columnsAttributes as $coordColumn => $columnAttributes) {
2569 9
            foreach ($rowsAttributes as $coordRow => $rowAttributes) {
2570 3
                if ($this->getReadFilter() !== null) {
2571 3
                    if (!$this->getReadFilter()->readCell($coordColumn, $coordRow, $docSheet->getTitle())) {
2572 3
                        continue 2;
2573
                    }
2574
                }
2575
            }
2576
2577 9
            if (!isset($columnsAttributesSet[$coordColumn])) {
2578 9
                $this->setColumnAttributes($docSheet, $coordColumn, $columnAttributes);
2579 9
                $columnsAttributesSet[$coordColumn] = true;
2580
            }
2581
        }
2582
2583 38
        foreach ($rowsAttributes as $coordRow => $rowAttributes) {
2584 3
            foreach ($columnsAttributes as $coordColumn => $columnAttributes) {
2585 3
                if ($this->getReadFilter() !== null) {
2586 3
                    if (!$this->getReadFilter()->readCell($coordColumn, $coordRow, $docSheet->getTitle())) {
2587 3
                        continue 2;
2588
                    }
2589
                }
2590
            }
2591
2592 3
            if (!isset($rowsAttributesSet[$coordRow])) {
2593 3
                $this->setRowAttributes($docSheet, $coordRow, $rowAttributes);
2594 3
                $rowsAttributesSet[$coordRow] = true;
2595
            }
2596
        }
2597 38
    }
2598
}
2599