Completed
Push — develop ( cdbf33...653adf )
by Adrien
26:38
created

Xlsx::toCSSArray()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 17
nop 1
dl 0
loc 29
rs 8.439
c 0
b 0
f 0
ccs 0
cts 19
cp 0
crap 42
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
6
use PhpOffice\PhpSpreadsheet\Document\Properties;
7
use PhpOffice\PhpSpreadsheet\NamedRange;
8
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart;
9
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
10
use PhpOffice\PhpSpreadsheet\RichText\RichText;
11
use PhpOffice\PhpSpreadsheet\Settings;
12
use PhpOffice\PhpSpreadsheet\Shared\Date;
13
use PhpOffice\PhpSpreadsheet\Shared\Drawing;
14
use PhpOffice\PhpSpreadsheet\Shared\File;
15
use PhpOffice\PhpSpreadsheet\Shared\Font;
16
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
17
use PhpOffice\PhpSpreadsheet\Spreadsheet;
18
use PhpOffice\PhpSpreadsheet\Style\Border;
19
use PhpOffice\PhpSpreadsheet\Style\Borders;
20
use PhpOffice\PhpSpreadsheet\Style\Color;
21
use PhpOffice\PhpSpreadsheet\Style\Conditional;
22
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
23
use PhpOffice\PhpSpreadsheet\Style\Protection;
24
use PhpOffice\PhpSpreadsheet\Style\Style;
25
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
26
use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing;
27
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
28
use XMLReader;
29
use ZipArchive;
30
31
class Xlsx extends BaseReader
32
{
33
    /**
34
     * ReferenceHelper instance.
35
     *
36
     * @var ReferenceHelper
37
     */
38
    private $referenceHelper;
39
40
    /**
41
     * Xlsx\Theme instance.
42
     *
43
     * @var Xlsx\Theme
44
     */
45
    private static $theme = null;
46
47
    /**
48
     * Create a new Xlsx Reader instance.
49
     */
50 20
    public function __construct()
51
    {
52 20
        $this->readFilter = new DefaultReadFilter();
53 20
        $this->referenceHelper = ReferenceHelper::getInstance();
54 20
    }
55
56
    /**
57
     * Can the current IReader read the file?
58
     *
59
     * @param string $pFilename
60
     *
61
     * @throws Exception
62
     *
63
     * @return bool
64
     */
65 6
    public function canRead($pFilename)
66
    {
67 6
        File::assertFile($pFilename);
68
69 6
        $xl = false;
70
        // Load file
71 6
        $zip = new ZipArchive();
72 6
        if ($zip->open($pFilename) === true) {
73
            // check if it is an OOXML archive
74 6
            $rels = simplexml_load_string(
75 6
                $this->securityScan(
76 6
                    $this->getFromZipArchive($zip, '_rels/.rels')
77
                ),
78 6
                'SimpleXMLElement',
79 6
                Settings::getLibXmlLoaderOptions()
80
            );
81 6
            if ($rels !== false) {
82 6
                foreach ($rels->Relationship as $rel) {
83 6
                    switch ($rel['Type']) {
84 6
                        case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
85 6
                            if (basename($rel['Target']) == 'workbook.xml') {
86 6
                                $xl = true;
87
                            }
88
89 6
                            break;
90
                    }
91
                }
92
            }
93 6
            $zip->close();
94
        }
95
96 6
        return $xl;
97
    }
98
99
    /**
100
     * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
101
     *
102
     * @param string $pFilename
103
     *
104
     * @throws Exception
105
     *
106
     * @return array
107
     */
108 1
    public function listWorksheetNames($pFilename)
109
    {
110 1
        File::assertFile($pFilename);
111
112 1
        $worksheetNames = [];
113
114 1
        $zip = new ZipArchive();
115 1
        $zip->open($pFilename);
116
117
        //    The files we're looking at here are small enough that simpleXML is more efficient than XMLReader
118 1
        $rels = simplexml_load_string(
119 1
            $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels'))
120
        ); //~ http://schemas.openxmlformats.org/package/2006/relationships");
121 1
        foreach ($rels->Relationship as $rel) {
122 1
            switch ($rel['Type']) {
123 1
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
124 1
                    $xmlWorkbook = simplexml_load_string(
125 1
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}"))
126
                    ); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
127
128 1
                    if ($xmlWorkbook->sheets) {
129 1
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
130
                            // Check if sheet should be skipped
131 1
                            $worksheetNames[] = (string) $eleSheet['name'];
132
                        }
133
                    }
134
            }
135
        }
136
137 1
        $zip->close();
138
139 1
        return $worksheetNames;
140
    }
141
142
    /**
143
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
144
     *
145
     * @param string $pFilename
146
     *
147
     * @throws Exception
148
     *
149
     * @return array
150
     */
151 1
    public function listWorksheetInfo($pFilename)
152
    {
153 1
        File::assertFile($pFilename);
154
155 1
        $worksheetInfo = [];
156
157 1
        $zip = new ZipArchive();
158 1
        $zip->open($pFilename);
159
160 1
        $rels = simplexml_load_string(
161
            //~ http://schemas.openxmlformats.org/package/2006/relationships"
162 1
            $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels')),
163 1
            'SimpleXMLElement',
164 1
            Settings::getLibXmlLoaderOptions()
165
        );
166 1
        foreach ($rels->Relationship as $rel) {
167 1
            if ($rel['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument') {
168 1
                $dir = dirname($rel['Target']);
169 1
                $relsWorkbook = simplexml_load_string(
170
                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
171 1
                    $this->securityScan(
172 1
                        $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')
173
                    ),
174 1
                    'SimpleXMLElement',
175 1
                    Settings::getLibXmlLoaderOptions()
176
                );
177 1
                $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
178
179 1
                $worksheets = [];
180 1
                foreach ($relsWorkbook->Relationship as $ele) {
181 1
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet') {
182 1
                        $worksheets[(string) $ele['Id']] = $ele['Target'];
183
                    }
184
                }
185
186 1
                $xmlWorkbook = simplexml_load_string(
187
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
188 1
                    $this->securityScan(
189 1
                        $this->getFromZipArchive($zip, "{$rel['Target']}")
190
                    ),
191 1
                    'SimpleXMLElement',
192 1
                    Settings::getLibXmlLoaderOptions()
193
                );
194 1
                if ($xmlWorkbook->sheets) {
195 1
                    $dir = dirname($rel['Target']);
196
                    /** @var \SimpleXMLElement $eleSheet */
197 1
                    foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
198
                        $tmpInfo = [
199 1
                            'worksheetName' => (string) $eleSheet['name'],
200 1
                            'lastColumnLetter' => 'A',
201 1
                            'lastColumnIndex' => 0,
202 1
                            'totalRows' => 0,
203 1
                            'totalColumns' => 0,
204
                        ];
205
206 1
                        $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
207
208 1
                        $xml = new XMLReader();
209 1
                        $xml->xml(
210 1
                            $this->securityScanFile(
211 1
                                'zip://' . File::realpath($pFilename) . '#' . "$dir/$fileWorksheet"
212
                            ),
213 1
                            null,
214 1
                            Settings::getLibXmlLoaderOptions()
215
                        );
216 1
                        $xml->setParserProperty(2, true);
217
218 1
                        $currCells = 0;
219 1
                        while ($xml->read()) {
220 1
                            if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) {
221 1
                                $row = $xml->getAttribute('r');
222 1
                                $tmpInfo['totalRows'] = $row;
223 1
                                $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
224 1
                                $currCells = 0;
225 1
                            } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) {
226 1
                                ++$currCells;
227
                            }
228
                        }
229 1
                        $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
230 1
                        $xml->close();
231
232 1
                        $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
233 1
                        $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
234
235 1
                        $worksheetInfo[] = $tmpInfo;
236
                    }
237
                }
238
            }
239
        }
240
241 1
        $zip->close();
242
243 1
        return $worksheetInfo;
244
    }
245
246 1
    private static function castToBoolean($c)
247
    {
248 1
        $value = isset($c->v) ? (string) $c->v : null;
249 1
        if ($value == '0') {
250
            return false;
251 1
        } elseif ($value == '1') {
252 1
            return true;
253
        }
254
255
        return (bool) $c->v;
256
    }
257
258
    private static function castToError($c)
259
    {
260
        return isset($c->v) ? (string) $c->v : null;
261
    }
262
263 9
    private static function castToString($c)
264
    {
265 9
        return isset($c->v) ? (string) $c->v : null;
266
    }
267
268 4
    private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType)
269
    {
270 4
        $cellDataType = 'f';
271 4
        $value = "={$c->f}";
272 4
        $calculatedValue = self::$castBaseType($c);
273
274
        // Shared formula?
275 4
        if (isset($c->f['t']) && strtolower((string) $c->f['t']) == 'shared') {
276 2
            $instance = (string) $c->f['si'];
277
278 2
            if (!isset($sharedFormulas[(string) $c->f['si']])) {
279 2
                $sharedFormulas[$instance] = ['master' => $r, 'formula' => $value];
280
            } else {
281 2
                $master = Coordinate::coordinateFromString($sharedFormulas[$instance]['master']);
282 2
                $current = Coordinate::coordinateFromString($r);
283
284 2
                $difference = [0, 0];
285 2
                $difference[0] = Coordinate::columnIndexFromString($current[0]) - Coordinate::columnIndexFromString($master[0]);
286 2
                $difference[1] = $current[1] - $master[1];
287
288 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

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

1639
                                                        $shadow->setAlignment(/** @scrutinizer ignore-type */ (string) self::getArrayItem($outerShdw->attributes(), 'algn'));
Loading history...
1640
                                                        $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), 'val'));
1641
                                                        $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), 'val') / 1000);
1642
                                                    }
1643 2
                                                    $objDrawing->setWorksheet($docSheet);
1644 2
                                                } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
1645 2
                                                    $fromCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
1646 2
                                                    $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff);
1647 2
                                                    $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
1648 2
                                                    $toCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
1649 2
                                                    $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff);
1650 2
                                                    $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
1651 2
                                                    $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic;
1652
                                                    /** @var \SimpleXMLElement $chartRef */
1653 2
                                                    $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart;
1654 2
                                                    $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1655
1656 2
                                                    $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1657 2
                                                        'fromCoordinate' => $fromCoordinate,
1658 2
                                                        'fromOffsetX' => $fromOffsetX,
1659 2
                                                        'fromOffsetY' => $fromOffsetY,
1660 2
                                                        'toCoordinate' => $toCoordinate,
1661 2
                                                        'toOffsetX' => $toOffsetX,
1662 2
                                                        'toOffsetY' => $toOffsetY,
1663 4
                                                        'worksheetTitle' => $docSheet->getTitle(),
1664
                                                    ];
1665
                                                }
1666
                                            }
1667
                                        }
1668
                                    }
1669
                                }
1670
                            }
1671
1672
                            // Loop through definedNames
1673 16
                            if ($xmlWorkbook->definedNames) {
1674 9
                                foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1675
                                    // Extract range
1676 1
                                    $extractedRange = (string) $definedName;
1677 1
                                    if (($spos = strpos($extractedRange, '!')) !== false) {
1678 1
                                        $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1679
                                    } else {
1680
                                        $extractedRange = str_replace('$', '', $extractedRange);
1681
                                    }
1682
1683
                                    // Valid range?
1684 1
                                    if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') {
1685
                                        continue;
1686
                                    }
1687
1688
                                    // Some definedNames are only applicable if we are on the same sheet...
1689 1
                                    if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $sheetId) {
1690
                                        // Switch on type
1691 1
                                        switch ((string) $definedName['name']) {
1692 1
                                            case '_xlnm._FilterDatabase':
1693
                                                if ((string) $definedName['hidden'] !== '1') {
1694
                                                    $extractedRange = explode(',', $extractedRange);
1695
                                                    foreach ($extractedRange as $range) {
1696
                                                        $autoFilterRange = $range;
1697
                                                        if (strpos($autoFilterRange, ':') !== false) {
1698
                                                            $docSheet->getAutoFilter()->setRange($autoFilterRange);
1699
                                                        }
1700
                                                    }
1701
                                                }
1702
1703
                                                break;
1704 1
                                            case '_xlnm.Print_Titles':
1705
                                                // Split $extractedRange
1706 1
                                                $extractedRange = explode(',', $extractedRange);
1707
1708
                                                // Set print titles
1709 1
                                                foreach ($extractedRange as $range) {
1710 1
                                                    $matches = [];
1711 1
                                                    $range = str_replace('$', '', $range);
1712
1713
                                                    // check for repeating columns, e g. 'A:A' or 'A:D'
1714 1
                                                    if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
1715
                                                        $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]);
1716 1
                                                    } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
1717
                                                        // check for repeating rows, e.g. '1:1' or '1:5'
1718 1
                                                        $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]);
1719
                                                    }
1720
                                                }
1721
1722 1
                                                break;
1723
                                            case '_xlnm.Print_Area':
1724
                                                $rangeSets = preg_split("/'(.*?)'(?:![A-Z0-9]+:[A-Z0-9]+,?)/", $extractedRange, PREG_SPLIT_NO_EMPTY);
1725
                                                $newRangeSets = [];
1726
                                                foreach ($rangeSets as $rangeSet) {
1727
                                                    $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark?
1728
                                                    $rangeSet = isset($range[1]) ? $range[1] : $range[0];
1729
                                                    if (strpos($rangeSet, ':') === false) {
1730
                                                        $rangeSet = $rangeSet . ':' . $rangeSet;
1731
                                                    }
1732
                                                    $newRangeSets[] = str_replace('$', '', $rangeSet);
1733
                                                }
1734
                                                $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
1735
1736
                                                break;
1737
                                            default:
1738 1
                                                break;
1739
                                        }
1740
                                    }
1741
                                }
1742
                            }
1743
1744
                            // Next sheet id
1745 16
                            ++$sheetId;
1746
                        }
1747
1748
                        // Loop through definedNames
1749 16
                        if ($xmlWorkbook->definedNames) {
1750 9
                            foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1751
                                // Extract range
1752 1
                                $extractedRange = (string) $definedName;
1753 1
                                if (($spos = strpos($extractedRange, '!')) !== false) {
1754 1
                                    $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1755
                                } else {
1756
                                    $extractedRange = str_replace('$', '', $extractedRange);
1757
                                }
1758
1759
                                // Valid range?
1760 1
                                if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') {
1761
                                    continue;
1762
                                }
1763
1764
                                // Some definedNames are only applicable if we are on the same sheet...
1765 1
                                if ((string) $definedName['localSheetId'] != '') {
1766
                                    // Local defined name
1767
                                    // Switch on type
1768 1
                                    switch ((string) $definedName['name']) {
1769 1
                                        case '_xlnm._FilterDatabase':
1770 1
                                        case '_xlnm.Print_Titles':
1771
                                        case '_xlnm.Print_Area':
1772 1
                                            break;
1773
                                        default:
1774
                                            if ($mapSheetId[(int) $definedName['localSheetId']] !== null) {
1775
                                                $range = explode('!', (string) $definedName);
1776
                                                if (count($range) == 2) {
1777
                                                    $range[0] = str_replace("''", "'", $range[0]);
1778
                                                    $range[0] = str_replace("'", '', $range[0]);
1779
                                                    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...
1780
                                                        $extractedRange = str_replace('$', '', $range[1]);
1781
                                                        $scope = $docSheet->getParent()->getSheet($mapSheetId[(int) $definedName['localSheetId']]);
1782
                                                        $excel->addNamedRange(new NamedRange((string) $definedName['name'], $worksheet, $extractedRange, true, $scope));
1783
                                                    }
1784
                                                }
1785
                                            }
1786
1787 1
                                            break;
1788
                                    }
1789
                                } elseif (!isset($definedName['localSheetId'])) {
1790
                                    // "Global" definedNames
1791
                                    $locatedSheet = null;
1792
                                    $extractedSheetName = '';
1793
                                    if (strpos((string) $definedName, '!') !== false) {
1794
                                        // Extract sheet name
1795
                                        $extractedSheetName = Worksheet::extractSheetTitle((string) $definedName, true);
1796
                                        $extractedSheetName = $extractedSheetName[0];
1797
1798
                                        // Locate sheet
1799
                                        $locatedSheet = $excel->getSheetByName($extractedSheetName);
1800
1801
                                        // Modify range
1802
                                        $range = explode('!', $extractedRange);
1803
                                        $extractedRange = isset($range[1]) ? $range[1] : $range[0];
1804
                                    }
1805
1806
                                    if ($locatedSheet !== null) {
1807 1
                                        $excel->addNamedRange(new NamedRange((string) $definedName['name'], $locatedSheet, $extractedRange, false));
1808
                                    }
1809
                                }
1810
                            }
1811
                        }
1812
                    }
1813
1814 16
                    if ((!$this->readDataOnly) || (!empty($this->loadSheetsOnly))) {
1815
                        // active sheet index
1816 16
                        $activeTab = (int) ($xmlWorkbook->bookViews->workbookView['activeTab']); // refers to old sheet index
1817
1818
                        // keep active sheet index if sheet is still loaded, else first sheet is set as the active
1819 16
                        if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
1820 16
                            $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
1821
                        } else {
1822
                            if ($excel->getSheetCount() == 0) {
1823
                                $excel->createSheet();
1824
                            }
1825
                            $excel->setActiveSheetIndex(0);
1826
                        }
1827
                    }
1828
1829 16
                    break;
1830
            }
1831
        }
1832
1833 16
        if (!$this->readDataOnly) {
1834 16
            $contentTypes = simplexml_load_string(
1835 16
                $this->securityScan(
1836 16
                    $this->getFromZipArchive($zip, '[Content_Types].xml')
1837
                ),
1838 16
                'SimpleXMLElement',
1839 16
                Settings::getLibXmlLoaderOptions()
1840
            );
1841 16
            foreach ($contentTypes->Override as $contentType) {
1842 16
                switch ($contentType['ContentType']) {
1843 16
                    case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
1844 2
                        if ($this->includeCharts) {
1845 2
                            $chartEntryRef = ltrim($contentType['PartName'], '/');
1846 2
                            $chartElements = simplexml_load_string(
1847 2
                                $this->securityScan(
1848 2
                                    $this->getFromZipArchive($zip, $chartEntryRef)
1849
                                ),
1850 2
                                'SimpleXMLElement',
1851 2
                                Settings::getLibXmlLoaderOptions()
1852
                            );
1853 2
                            $objChart = Chart::readChart($chartElements, basename($chartEntryRef, '.xml'));
1854
1855 2
                            if (isset($charts[$chartEntryRef])) {
1856 2
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
1857 2
                                if (isset($chartDetails[$chartPositionRef])) {
1858 2
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
1859 2
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
1860 2
                                    $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
1861 16
                                    $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
1862
                                }
1863
                            }
1864
                        }
1865
                }
1866
            }
1867
        }
1868
1869 16
        $zip->close();
1870
1871 16
        return $excel;
1872
    }
1873
1874 16
    private static function readColor($color, $background = false)
1875
    {
1876 16
        if (isset($color['rgb'])) {
1877 12
            return (string) $color['rgb'];
1878 9
        } elseif (isset($color['indexed'])) {
1879 7
            return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
1880 6
        } elseif (isset($color['theme'])) {
1881 5
            if (self::$theme !== null) {
1882 5
                $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
1883 5
                if (isset($color['tint'])) {
1884 1
                    $tintAdjust = (float) $color['tint'];
1885 1
                    $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
1886
                }
1887
1888 5
                return 'FF' . $returnColour;
1889
            }
1890
        }
1891
1892 2
        if ($background) {
1893
            return 'FFFFFFFF';
1894
        }
1895
1896 2
        return 'FF000000';
1897
    }
1898
1899
    /**
1900
     * @param Style $docStyle
1901
     * @param \SimpleXMLElement|\stdClass $style
1902
     */
1903 16
    private static function readStyle(Style $docStyle, $style)
1904
    {
1905 16
        $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
1906
1907
        // font
1908 16
        if (isset($style->font)) {
1909 16
            $docStyle->getFont()->setName((string) $style->font->name['val']);
1910 16
            $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

1910
            $docStyle->getFont()->setSize(/** @scrutinizer ignore-type */ (string) $style->font->sz['val']);
Loading history...
1911 16
            if (isset($style->font->b)) {
1912 13
                $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val']));
1913
            }
1914 16
            if (isset($style->font->i)) {
1915 10
                $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val']));
1916
            }
1917 16
            if (isset($style->font->strike)) {
1918 9
                $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val']));
1919
            }
1920 16
            $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color));
1921
1922 16
            if (isset($style->font->u) && !isset($style->font->u['val'])) {
1923
                $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
1924 16
            } elseif (isset($style->font->u, $style->font->u['val'])) {
1925 9
                $docStyle->getFont()->setUnderline((string) $style->font->u['val']);
1926
            }
1927
1928 16
            if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) {
1929
                $vertAlign = strtolower((string) $style->font->vertAlign['val']);
1930
                if ($vertAlign == 'superscript') {
1931
                    $docStyle->getFont()->setSuperscript(true);
1932
                }
1933
                if ($vertAlign == 'subscript') {
1934
                    $docStyle->getFont()->setSubscript(true);
1935
                }
1936
            }
1937
        }
1938
1939
        // fill
1940 16
        if (isset($style->fill)) {
1941 16
            if ($style->fill->gradientFill) {
1942
                /** @var \SimpleXMLElement $gradientFill */
1943 2
                $gradientFill = $style->fill->gradientFill[0];
1944 2
                if (!empty($gradientFill['type'])) {
1945 2
                    $docStyle->getFill()->setFillType((string) $gradientFill['type']);
1946
                }
1947 2
                $docStyle->getFill()->setRotation((float) ($gradientFill['degree']));
1948 2
                $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
1949 2
                $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
1950 2
                $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
1951 16
            } elseif ($style->fill->patternFill) {
1952 16
                $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid';
1953 16
                $docStyle->getFill()->setFillType($patternType);
1954 16
                if ($style->fill->patternFill->fgColor) {
1955 4
                    $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true));
1956
                } else {
1957 16
                    $docStyle->getFill()->getStartColor()->setARGB('FF000000');
1958
                }
1959 16
                if ($style->fill->patternFill->bgColor) {
1960 5
                    $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true));
1961
                }
1962
            }
1963
        }
1964
1965
        // border
1966 16
        if (isset($style->border)) {
1967 16
            $diagonalUp = self::boolean((string) $style->border['diagonalUp']);
1968 16
            $diagonalDown = self::boolean((string) $style->border['diagonalDown']);
1969 16
            if (!$diagonalUp && !$diagonalDown) {
1970 16
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
1971
            } elseif ($diagonalUp && !$diagonalDown) {
1972
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
1973
            } elseif (!$diagonalUp && $diagonalDown) {
1974
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
1975
            } else {
1976
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
1977
            }
1978 16
            self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
1979 16
            self::readBorder($docStyle->getBorders()->getRight(), $style->border->right);
1980 16
            self::readBorder($docStyle->getBorders()->getTop(), $style->border->top);
1981 16
            self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
1982 16
            self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
1983
        }
1984
1985
        // alignment
1986 16
        if (isset($style->alignment)) {
1987 16
            $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']);
1988 16
            $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']);
1989
1990 16
            $textRotation = 0;
1991 16
            if ((int) $style->alignment['textRotation'] <= 90) {
1992 16
                $textRotation = (int) $style->alignment['textRotation'];
1993
            } elseif ((int) $style->alignment['textRotation'] > 90) {
1994
                $textRotation = 90 - (int) $style->alignment['textRotation'];
1995
            }
1996
1997 16
            $docStyle->getAlignment()->setTextRotation((int) $textRotation);
1998 16
            $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText']));
1999 16
            $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit']));
2000 16
            $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0);
2001 16
            $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0);
2002
        }
2003
2004
        // protection
2005 16
        if (isset($style->protection)) {
2006 16
            if (isset($style->protection['locked'])) {
2007 2
                if (self::boolean((string) $style->protection['locked'])) {
2008
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
2009
                } else {
2010 2
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
2011
                }
2012
            }
2013
2014 16
            if (isset($style->protection['hidden'])) {
2015
                if (self::boolean((string) $style->protection['hidden'])) {
2016
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
2017
                } else {
2018
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
2019
                }
2020
            }
2021
        }
2022
2023
        // top-level style settings
2024 16
        if (isset($style->quotePrefix)) {
2025 16
            $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

2025
            $docStyle->setQuotePrefix(/** @scrutinizer ignore-type */ $style->quotePrefix);
Loading history...
2026
        }
2027 16
    }
2028
2029
    /**
2030
     * @param Border $docBorder
2031
     * @param \SimpleXMLElement $eleBorder
2032
     */
2033 16
    private static function readBorder(Border $docBorder, $eleBorder)
2034
    {
2035 16
        if (isset($eleBorder['style'])) {
2036 3
            $docBorder->setBorderStyle((string) $eleBorder['style']);
2037
        }
2038 16
        if (isset($eleBorder->color)) {
2039 3
            $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
2040
        }
2041 16
    }
2042
2043
    /**
2044
     * @param \SimpleXMLElement | null $is
2045
     *
2046
     * @return RichText
2047
     */
2048 3
    private function parseRichText($is)
2049
    {
2050 3
        $value = new RichText();
2051
2052 3
        if (isset($is->t)) {
2053
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
2054
        } else {
2055 3
            if (is_object($is->r)) {
2056 3
                foreach ($is->r as $run) {
2057 3
                    if (!isset($run->rPr)) {
2058 3
                        $objText = $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
0 ignored issues
show
Unused Code introduced by
The assignment to $objText is dead and can be removed.
Loading history...
2059
                    } else {
2060 3
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2061
2062 3
                        if (isset($run->rPr->rFont['val'])) {
2063 3
                            $objText->getFont()->setName((string) $run->rPr->rFont['val']);
2064
                        }
2065 3
                        if (isset($run->rPr->sz['val'])) {
2066 3
                            $objText->getFont()->setSize((string) $run->rPr->sz['val']);
0 ignored issues
show
Bug introduced by
(string)$run->rPr->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

2066
                            $objText->getFont()->setSize(/** @scrutinizer ignore-type */ (string) $run->rPr->sz['val']);
Loading history...
2067
                        }
2068 3
                        if (isset($run->rPr->color)) {
2069 3
                            $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
2070
                        }
2071 3
                        if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
2072 3
                            (isset($run->rPr->b) && !isset($run->rPr->b['val']))) {
2073 3
                            $objText->getFont()->setBold(true);
2074
                        }
2075 3
                        if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
2076 3
                            (isset($run->rPr->i) && !isset($run->rPr->i['val']))) {
2077 2
                            $objText->getFont()->setItalic(true);
2078
                        }
2079 3
                        if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
2080
                            $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
2081
                            if ($vertAlign == 'superscript') {
2082
                                $objText->getFont()->setSuperscript(true);
2083
                            }
2084
                            if ($vertAlign == 'subscript') {
2085
                                $objText->getFont()->setSubscript(true);
2086
                            }
2087
                        }
2088 3
                        if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
2089
                            $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2090 3
                        } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
2091 2
                            $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
2092
                        }
2093 3
                        if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
2094 3
                            (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) {
2095 3
                            $objText->getFont()->setStrikethrough(true);
2096
                        }
2097
                    }
2098
                }
2099
            }
2100
        }
2101
2102 3
        return $value;
2103
    }
2104
2105
    /**
2106
     * @param Spreadsheet $excel
2107
     * @param mixed $customUITarget
2108
     * @param mixed $zip
2109
     */
2110
    private function readRibbon(Spreadsheet $excel, $customUITarget, $zip)
2111
    {
2112
        $baseDir = dirname($customUITarget);
2113
        $nameCustomUI = basename($customUITarget);
2114
        // get the xml file (ribbon)
2115
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
2116
        $customUIImagesNames = [];
2117
        $customUIImagesBinaries = [];
2118
        // something like customUI/_rels/customUI.xml.rels
2119
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
2120
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
2121
        if ($dataRels) {
2122
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
2123
            $UIRels = simplexml_load_string(
2124
                $this->securityScan($dataRels),
2125
                'SimpleXMLElement',
2126
                Settings::getLibXmlLoaderOptions()
2127
            );
2128
            if ($UIRels) {
2129
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
2130
                foreach ($UIRels->Relationship as $ele) {
2131
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
2132
                        // an image ?
2133
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
2134
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
2135
                    }
2136
                }
2137
            }
2138
        }
2139
        if ($localRibbon) {
2140
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
2141
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2142
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
2143
            } else {
2144
                $excel->setRibbonBinObjects(null);
0 ignored issues
show
Bug introduced by
The call to PhpOffice\PhpSpreadsheet...::setRibbonBinObjects() has too few arguments starting with BinObjectsData. ( Ignorable by Annotation )

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

2144
                $excel->/** @scrutinizer ignore-call */ 
2145
                        setRibbonBinObjects(null);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
2145
            }
2146
        } else {
2147
            $excel->setRibbonXMLData(null);
0 ignored issues
show
Bug introduced by
The call to PhpOffice\PhpSpreadsheet...eet::setRibbonXMLData() has too few arguments starting with xmlData. ( Ignorable by Annotation )

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

2147
            $excel->/** @scrutinizer ignore-call */ 
2148
                    setRibbonXMLData(null);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
2148
            $excel->setRibbonBinObjects(null);
2149
        }
2150
    }
2151
2152 17
    private static function getArrayItem($array, $key = 0)
2153
    {
2154 17
        return isset($array[$key]) ? $array[$key] : null;
2155
    }
2156
2157 4
    private static function dirAdd($base, $add)
2158
    {
2159 4
        return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
2160
    }
2161
2162
    private static function toCSSArray($style)
2163
    {
2164
        $style = trim(str_replace(["\r", "\n"], '', $style), ';');
2165
2166
        $temp = explode(';', $style);
2167
        $style = [];
2168
        foreach ($temp as $item) {
2169
            $item = explode(':', $item);
2170
2171
            if (strpos($item[1], 'px') !== false) {
2172
                $item[1] = str_replace('px', '', $item[1]);
2173
            }
2174
            if (strpos($item[1], 'pt') !== false) {
2175
                $item[1] = str_replace('pt', '', $item[1]);
2176
                $item[1] = Font::fontSizeToPixels($item[1]);
2177
            }
2178
            if (strpos($item[1], 'in') !== false) {
2179
                $item[1] = str_replace('in', '', $item[1]);
2180
                $item[1] = Font::inchSizeToPixels($item[1]);
2181
            }
2182
            if (strpos($item[1], 'cm') !== false) {
2183
                $item[1] = str_replace('cm', '', $item[1]);
2184
                $item[1] = Font::centimeterSizeToPixels($item[1]);
2185
            }
2186
2187
            $style[$item[0]] = $item[1];
2188
        }
2189
2190
        return $style;
2191
    }
2192
2193 16
    private static function boolean($value)
2194
    {
2195 16
        if (is_object($value)) {
2196 1
            $value = (string) $value;
2197
        }
2198 16
        if (is_numeric($value)) {
2199 13
            return (bool) $value;
2200
        }
2201
2202 16
        return $value === 'true' || $value === 'TRUE';
2203
    }
2204
}
2205