Completed
Push — develop ( 5f0365...e5e8be )
by Adrien
40:53
created

Xlsx::canRead()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 3
nop 1
dl 0
loc 32
ccs 19
cts 19
cp 1
crap 6
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
6
use PhpOffice\PhpSpreadsheet\Document\Properties;
7
use PhpOffice\PhpSpreadsheet\NamedRange;
8
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart;
9
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
10
use PhpOffice\PhpSpreadsheet\RichText\RichText;
11
use PhpOffice\PhpSpreadsheet\Settings;
12
use PhpOffice\PhpSpreadsheet\Shared\Date;
13
use PhpOffice\PhpSpreadsheet\Shared\Drawing;
14
use PhpOffice\PhpSpreadsheet\Shared\File;
15
use PhpOffice\PhpSpreadsheet\Shared\Font;
16
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
17
use PhpOffice\PhpSpreadsheet\Spreadsheet;
18
use PhpOffice\PhpSpreadsheet\Style\Border;
19
use PhpOffice\PhpSpreadsheet\Style\Borders;
20
use PhpOffice\PhpSpreadsheet\Style\Color;
21
use PhpOffice\PhpSpreadsheet\Style\Conditional;
22
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
23
use PhpOffice\PhpSpreadsheet\Style\Protection;
24
use PhpOffice\PhpSpreadsheet\Style\Style;
25
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
26
use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing;
27
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
28
use 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 33
    public function __construct()
51
    {
52 33
        $this->readFilter = new DefaultReadFilter();
53 33
        $this->referenceHelper = ReferenceHelper::getInstance();
54 33
    }
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 4
    private static function castToBoolean($c)
247
    {
248 4
        $value = isset($c->v) ? (string) $c->v : null;
249 4
        if ($value == '0') {
250
            return false;
251 4
        } elseif ($value == '1') {
252 4
            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 14
    private static function castToString($c)
264
    {
265 14
        return isset($c->v) ? (string) $c->v : null;
266
    }
267
268 7
    private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType)
269
    {
270 7
        $cellDataType = 'f';
271 7
        $value = "={$c->f}";
272 7
        $calculatedValue = self::$castBaseType($c);
273
274
        // Shared formula?
275 7
        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 7
    }
292
293
    /**
294
     * @param ZipArchive $archive
295
     * @param string $fileName
296
     *
297
     * @return string
298
     */
299 32
    private function getFromZipArchive(ZipArchive $archive, $fileName = '')
300
    {
301
        // Root-relative paths
302 32
        if (strpos($fileName, '//') !== false) {
303
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
304
        }
305 32
        $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 32
        $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
312 32
        if ($contents === false) {
313
            $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
314
        }
315
316 32
        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 29
    public function load($pFilename)
329
    {
330 29
        File::assertFile($pFilename);
331
332
        // Initialisations
333 29
        $excel = new Spreadsheet();
334 29
        $excel->removeSheetByIndex(0);
335 29
        if (!$this->readDataOnly) {
336 29
            $excel->removeCellStyleXfByIndex(0); // remove the default style
337 29
            $excel->removeCellXfByIndex(0); // remove the default style
338
        }
339
340 29
        $zip = new ZipArchive();
341 29
        $zip->open($pFilename);
342
343
        //    Read the theme first, because we need the colour scheme when reading the styles
344 29
        $wbRels = simplexml_load_string(
345
            //~ http://schemas.openxmlformats.org/package/2006/relationships"
346 29
            $this->securityScan($this->getFromZipArchive($zip, 'xl/_rels/workbook.xml.rels')),
347 29
            'SimpleXMLElement',
348 29
            Settings::getLibXmlLoaderOptions()
349
        );
350 29
        foreach ($wbRels->Relationship as $rel) {
351 29
            switch ($rel['Type']) {
352 29
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme':
353 29
                    $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
354 29
                    $themeOrderAdditional = count($themeOrderArray);
355
356 29
                    $xmlTheme = simplexml_load_string(
357 29
                        $this->securityScan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")),
358 29
                        'SimpleXMLElement',
359 29
                        Settings::getLibXmlLoaderOptions()
360
                    );
361 29
                    if (is_object($xmlTheme)) {
362 29
                        $xmlThemeName = $xmlTheme->attributes();
363 29
                        $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
364 29
                        $themeName = (string) $xmlThemeName['name'];
365
366 29
                        $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
367 29
                        $colourSchemeName = (string) $colourScheme['name'];
368 29
                        $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
369
370 29
                        $themeColours = [];
371 29
                        foreach ($colourScheme as $k => $xmlColour) {
372 29
                            $themePos = array_search($k, $themeOrderArray);
373 29
                            if ($themePos === false) {
374 29
                                $themePos = $themeOrderAdditional++;
375
                            }
376 29
                            if (isset($xmlColour->sysClr)) {
377 29
                                $xmlColourData = $xmlColour->sysClr->attributes();
378 29
                                $themeColours[$themePos] = $xmlColourData['lastClr'];
379 29
                            } elseif (isset($xmlColour->srgbClr)) {
380 29
                                $xmlColourData = $xmlColour->srgbClr->attributes();
381 29
                                $themeColours[$themePos] = $xmlColourData['val'];
382
                            }
383
                        }
384 29
                        self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours);
385
                    }
386
387 29
                    break;
388
            }
389
        }
390
391 29
        $rels = simplexml_load_string(
392
            //~ http://schemas.openxmlformats.org/package/2006/relationships"
393 29
            $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels')),
394 29
            'SimpleXMLElement',
395 29
            Settings::getLibXmlLoaderOptions()
396
        );
397 29
        foreach ($rels->Relationship as $rel) {
398 29
            switch ($rel['Type']) {
399 29
                case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties':
400 28
                    $xmlCore = simplexml_load_string(
401 28
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
402 28
                        'SimpleXMLElement',
403 28
                        Settings::getLibXmlLoaderOptions()
404
                    );
405 28
                    if (is_object($xmlCore)) {
406 28
                        $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/');
407 28
                        $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/');
408 28
                        $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
409 28
                        $docProps = $excel->getProperties();
410 28
                        $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator')));
411 28
                        $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy')));
412 28
                        $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type
413 28
                        $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type
414 28
                        $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title')));
415 28
                        $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description')));
416 28
                        $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject')));
417 28
                        $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath('cp:keywords')));
418 28
                        $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath('cp:category')));
419
                    }
420
421 28
                    break;
422 29
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties':
423 28
                    $xmlCore = simplexml_load_string(
424 28
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
425 28
                        'SimpleXMLElement',
426 28
                        Settings::getLibXmlLoaderOptions()
427
                    );
428 28
                    if (is_object($xmlCore)) {
429 28
                        $docProps = $excel->getProperties();
430 28
                        if (isset($xmlCore->Company)) {
431 26
                            $docProps->setCompany((string) $xmlCore->Company);
432
                        }
433 28
                        if (isset($xmlCore->Manager)) {
434 24
                            $docProps->setManager((string) $xmlCore->Manager);
435
                        }
436
                    }
437
438 28
                    break;
439 29
                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 29
                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 29
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
472 29
                    $dir = dirname($rel['Target']);
473 29
                    $relsWorkbook = simplexml_load_string(
474
                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
475 29
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')),
476 29
                        'SimpleXMLElement',
477 29
                        Settings::getLibXmlLoaderOptions()
478
                    );
479 29
                    $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
480
481 29
                    $sharedStrings = [];
482 29
                    $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
483 29
                    $xmlStrings = simplexml_load_string(
484
                        //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
485 29
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
486 29
                        'SimpleXMLElement',
487 29
                        Settings::getLibXmlLoaderOptions()
488
                    );
489 29
                    if (isset($xmlStrings, $xmlStrings->si)) {
490 14
                        foreach ($xmlStrings->si as $val) {
491 14
                            if (isset($val->t)) {
492 14
                                $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
493 3
                            } elseif (isset($val->r)) {
494 14
                                $sharedStrings[] = $this->parseRichText($val);
495
                            }
496
                        }
497
                    }
498
499 29
                    $worksheets = [];
500 29
                    $macros = $customUI = null;
501 29
                    foreach ($relsWorkbook->Relationship as $ele) {
502 29
                        switch ($ele['Type']) {
503 29
                            case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet':
504 29
                                $worksheets[(string) $ele['Id']] = $ele['Target'];
505
506 29
                                break;
507
                            // a vbaProject ? (: some macros)
508 29
                            case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject':
509
                                $macros = $ele['Target'];
510
511 29
                                break;
512
                        }
513
                    }
514
515 29
                    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 29
                    $styles = [];
528 29
                    $cellStyles = [];
529 29
                    $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
530 29
                    $xmlStyles = simplexml_load_string(
531
                        //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
532 29
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
533 29
                        'SimpleXMLElement',
534 29
                        Settings::getLibXmlLoaderOptions()
535
                    );
536 29
                    $numFmts = null;
537 29
                    if ($xmlStyles && $xmlStyles->numFmts[0]) {
538 23
                        $numFmts = $xmlStyles->numFmts[0];
539
                    }
540 29
                    if (isset($numFmts) && ($numFmts !== null)) {
541 23
                        $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
542
                    }
543 29
                    if (!$this->readDataOnly && $xmlStyles) {
544 29
                        foreach ($xmlStyles->cellXfs->xf as $xf) {
545 29
                            $numFmt = NumberFormat::FORMAT_GENERAL;
546
547 29
                            if ($xf['numFmtId']) {
548 29
                                if (isset($numFmts)) {
549 23
                                    $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
550
551 23
                                    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 29
                                if ((int) $xf['numFmtId'] < 164 &&
560 29
                                    NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '') {
561 29
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
562
                                }
563
                            }
564 29
                            $quotePrefix = false;
565 29
                            if (isset($xf['quotePrefix'])) {
566
                                $quotePrefix = (bool) $xf['quotePrefix'];
567
                            }
568
569
                            $style = (object) [
570 29
                                'numFmt' => $numFmt,
571 29
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
572 29
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
573 29
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
574 29
                                'alignment' => $xf->alignment,
575 29
                                'protection' => $xf->protection,
576 29
                                'quotePrefix' => $quotePrefix,
577
                            ];
578 29
                            $styles[] = $style;
579
580
                            // add style to cellXf collection
581 29
                            $objStyle = new Style();
582 29
                            self::readStyle($objStyle, $style);
583 29
                            $excel->addCellXf($objStyle);
584
                        }
585
586 29
                        foreach ($xmlStyles->cellStyleXfs->xf as $xf) {
587 29
                            $numFmt = NumberFormat::FORMAT_GENERAL;
588 29
                            if ($numFmts && $xf['numFmtId']) {
589 23
                                $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
590 23
                                if (isset($tmpNumFmt['formatCode'])) {
591 1
                                    $numFmt = (string) $tmpNumFmt['formatCode'];
592 23
                                } elseif ((int) $xf['numFmtId'] < 165) {
593 23
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
594
                                }
595
                            }
596
597
                            $cellStyle = (object) [
598 29
                                'numFmt' => $numFmt,
599 29
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
600 29
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
601 29
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
602 29
                                'alignment' => $xf->alignment,
603 29
                                'protection' => $xf->protection,
604 29
                                '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 29
                            $cellStyles[] = $cellStyle;
607
608
                            // add style to cellStyleXf collection
609 29
                            $objStyle = new Style();
610 29
                            self::readStyle($objStyle, $cellStyle);
611 29
                            $excel->addCellStyleXf($objStyle);
612
                        }
613
                    }
614
615 29
                    $dxfs = [];
616 29
                    if (!$this->readDataOnly && $xmlStyles) {
617
                        //    Conditional Styles
618 29
                        if ($xmlStyles->dxfs) {
619 29
                            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 29
                        if ($xmlStyles->cellStyles) {
627 29
                            foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) {
628 29
                                if ((int) ($cellStyle['builtinId']) == 0) {
629 29
                                    if (isset($cellStyles[(int) ($cellStyle['xfId'])])) {
630
                                        // Set default style
631 29
                                        $style = new Style();
632 29
                                        self::readStyle($style, $cellStyles[(int) ($cellStyle['xfId'])]);
633
634
                                        // normal style, currently not using it for anything
635
                                    }
636
                                }
637
                            }
638
                        }
639
                    }
640
641 29
                    $xmlWorkbook = simplexml_load_string(
642
                        //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
643 29
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
644 29
                        'SimpleXMLElement',
645 29
                        Settings::getLibXmlLoaderOptions()
646
                    );
647
648
                    // Set base date
649 29
                    if ($xmlWorkbook->workbookPr) {
650 28
                        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
651 28
                        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 29
                    $sheetId = 0; // keep track of new sheet id in final workbook
659 29
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
660 29
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
661 29
                    $mapSheetId = []; // mapping of sheet ids from old to new
662
663 29
                    $charts = $chartDetails = [];
664
665 29
                    if ($xmlWorkbook->sheets) {
666
                        /** @var \SimpleXMLElement $eleSheet */
667 29
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
668 29
                            ++$oldSheetId;
669
670
                            // Check if sheet should be skipped
671 29
                            if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) {
672 1
                                ++$countSkippedSheets;
673 1
                                $mapSheetId[$oldSheetId] = null;
674
675 1
                                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 29
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
681
682
                            // Load sheet
683 29
                            $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 29
                            $docSheet->setTitle((string) $eleSheet['name'], false, false);
689 29
                            $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
690 29
                            $xmlSheet = simplexml_load_string(
691
                                //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
692 29
                                $this->securityScan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")),
693 29
                                'SimpleXMLElement',
694 29
                                Settings::getLibXmlLoaderOptions()
695
                            );
696
697 29
                            $sharedFormulas = [];
698
699 29
                            if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') {
700
                                $docSheet->setSheetState((string) $eleSheet['state']);
701
                            }
702
703 29
                            if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) {
704 29
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) {
705
                                    $zoomScale = (int) ($xmlSheet->sheetViews->sheetView['zoomScale']);
706
                                    if ($zoomScale <= 0) {
707
                                        // setZoomScale will throw an Exception if the scale is less than or equals 0
708
                                        // that is OK when manually creating documents, but we should be able to read all documents
709
                                        $zoomScale = 100;
710
                                    }
711
712
                                    $docSheet->getSheetView()->setZoomScale($zoomScale);
713
                                }
714 29
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) {
715
                                    $zoomScaleNormal = (int) ($xmlSheet->sheetViews->sheetView['zoomScaleNormal']);
716
                                    if ($zoomScaleNormal <= 0) {
717
                                        // setZoomScaleNormal will throw an Exception if the scale is less than or equals 0
718
                                        // that is OK when manually creating documents, but we should be able to read all documents
719
                                        $zoomScaleNormal = 100;
720
                                    }
721
722
                                    $docSheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal);
723
                                }
724 29
                                if (isset($xmlSheet->sheetViews->sheetView['view'])) {
725
                                    $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']);
726
                                }
727 29
                                if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
728 22
                                    $docSheet->setShowGridLines(self::boolean((string) $xmlSheet->sheetViews->sheetView['showGridLines']));
729
                                }
730 29
                                if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
731 22
                                    $docSheet->setShowRowColHeaders(self::boolean((string) $xmlSheet->sheetViews->sheetView['showRowColHeaders']));
732
                                }
733 29
                                if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
734
                                    $docSheet->setRightToLeft(self::boolean((string) $xmlSheet->sheetViews->sheetView['rightToLeft']));
735
                                }
736 29
                                if (isset($xmlSheet->sheetViews->sheetView->pane)) {
737 2
                                    $xSplit = 0;
738 2
                                    $ySplit = 0;
739 2
                                    $topLeftCell = null;
740
741 2
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
742 1
                                        $xSplit = (int) ($xmlSheet->sheetViews->sheetView->pane['xSplit']);
743
                                    }
744
745 2
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
746 2
                                        $ySplit = (int) ($xmlSheet->sheetViews->sheetView->pane['ySplit']);
747
                                    }
748
749 2
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
750 2
                                        $topLeftCell = (string) $xmlSheet->sheetViews->sheetView->pane['topLeftCell'];
751
                                    }
752
753 2
                                    $docSheet->freezePane(Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1), $topLeftCell);
754
                                }
755
756 29
                                if (isset($xmlSheet->sheetViews->sheetView->selection)) {
757 27
                                    if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
758 26
                                        $sqref = (string) $xmlSheet->sheetViews->sheetView->selection['sqref'];
759 26
                                        $sqref = explode(' ', $sqref);
760 26
                                        $sqref = $sqref[0];
761 26
                                        $docSheet->setSelectedCells($sqref);
762
                                    }
763
                                }
764
                            }
765
766 29
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->tabColor)) {
767 2
                                if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
768 2
                                    $docSheet->getTabColor()->setARGB((string) $xmlSheet->sheetPr->tabColor['rgb']);
769
                                }
770
                            }
771 29
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr['codeName'])) {
772
                                $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName'], false);
773
                            }
774 29
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->outlinePr)) {
775 22
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) &&
776 22
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) {
777
                                    $docSheet->setShowSummaryRight(false);
778
                                } else {
779 22
                                    $docSheet->setShowSummaryRight(true);
780
                                }
781
782 22
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) &&
783 22
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) {
784
                                    $docSheet->setShowSummaryBelow(false);
785
                                } else {
786 22
                                    $docSheet->setShowSummaryBelow(true);
787
                                }
788
                            }
789
790 29
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->pageSetUpPr)) {
791
                                if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) &&
792
                                    !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) {
793
                                    $docSheet->getPageSetup()->setFitToPage(false);
794
                                } else {
795
                                    $docSheet->getPageSetup()->setFitToPage(true);
796
                                }
797
                            }
798
799 29
                            if (isset($xmlSheet->sheetFormatPr)) {
800 29
                                if (isset($xmlSheet->sheetFormatPr['customHeight']) &&
801 29
                                    self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) &&
802 29
                                    isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
803 1
                                    $docSheet->getDefaultRowDimension()->setRowHeight((float) $xmlSheet->sheetFormatPr['defaultRowHeight']);
804
                                }
805 29
                                if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
806 1
                                    $docSheet->getDefaultColumnDimension()->setWidth((float) $xmlSheet->sheetFormatPr['defaultColWidth']);
807
                                }
808 29
                                if (isset($xmlSheet->sheetFormatPr['zeroHeight']) &&
809 29
                                    ((string) $xmlSheet->sheetFormatPr['zeroHeight'] == '1')) {
810
                                    $docSheet->getDefaultRowDimension()->setZeroHeight(true);
811
                                }
812
                            }
813
814 29
                            if (isset($xmlSheet->cols) && !$this->readDataOnly) {
815 7
                                foreach ($xmlSheet->cols->col as $col) {
816 7
                                    for ($i = (int) ($col['min']); $i <= (int) ($col['max']); ++$i) {
817 7
                                        if ($col['style'] && !$this->readDataOnly) {
818 3
                                            $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setXfIndex((int) ($col['style']));
819
                                        }
820 7
                                        if (self::boolean($col['hidden'])) {
821 1
                                            $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setVisible(false);
822
                                        }
823 7
                                        if (self::boolean($col['collapsed'])) {
824 1
                                            $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setCollapsed(true);
825
                                        }
826 7
                                        if ($col['outlineLevel'] > 0) {
827 1
                                            $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setOutlineLevel((int) ($col['outlineLevel']));
828
                                        }
829 7
                                        $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setWidth((float) ($col['width']));
830
831 7
                                        if ((int) ($col['max']) == 16384) {
832
                                            break;
833
                                        }
834
                                    }
835
                                }
836
                            }
837
838 29
                            if (isset($xmlSheet->printOptions) && !$this->readDataOnly) {
839 22
                                if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) {
840 22
                                    $docSheet->setShowGridlines(true);
841
                                }
842 22
                                if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) {
843
                                    $docSheet->setPrintGridlines(true);
844
                                }
845 22
                                if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) {
846
                                    $docSheet->getPageSetup()->setHorizontalCentered(true);
847
                                }
848 22
                                if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) {
849
                                    $docSheet->getPageSetup()->setVerticalCentered(true);
850
                                }
851
                            }
852
853 29
                            if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
854 24
                                $cIndex = 1; // Cell Start from 1
855 24
                                foreach ($xmlSheet->sheetData->row as $row) {
856 24
                                    if ($row['ht'] && !$this->readDataOnly) {
857 2
                                        $docSheet->getRowDimension((int) ($row['r']))->setRowHeight((float) ($row['ht']));
858
                                    }
859 24
                                    if (self::boolean($row['hidden']) && !$this->readDataOnly) {
860
                                        $docSheet->getRowDimension((int) ($row['r']))->setVisible(false);
861
                                    }
862 24
                                    if (self::boolean($row['collapsed'])) {
863
                                        $docSheet->getRowDimension((int) ($row['r']))->setCollapsed(true);
864
                                    }
865 24
                                    if ($row['outlineLevel'] > 0) {
866
                                        $docSheet->getRowDimension((int) ($row['r']))->setOutlineLevel((int) ($row['outlineLevel']));
867
                                    }
868 24
                                    if ($row['s'] && !$this->readDataOnly) {
869
                                        $docSheet->getRowDimension((int) ($row['r']))->setXfIndex((int) ($row['s']));
870
                                    }
871
872 24
                                    $rowIndex = 1;
873 24
                                    foreach ($row->c as $c) {
874 24
                                        $r = (string) $c['r'];
875 24
                                        if ($r == '') {
876 1
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
877
                                        }
878 24
                                        $cellDataType = (string) $c['t'];
879 24
                                        $value = null;
880 24
                                        $calculatedValue = null;
881
882
                                        // Read cell?
883 24
                                        if ($this->getReadFilter() !== null) {
884 24
                                            $coordinates = Coordinate::coordinateFromString($r);
885
886 24
                                            if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) {
887 1
                                                continue;
888
                                            }
889
                                        }
890
891
                                        // Read cell!
892
                                        switch ($cellDataType) {
893 24
                                            case 's':
894 14
                                                if ((string) $c->v != '') {
895 14
                                                    $value = $sharedStrings[(int) ($c->v)];
896
897 14
                                                    if ($value instanceof RichText) {
898 14
                                                        $value = clone $value;
899
                                                    }
900
                                                } else {
901
                                                    $value = '';
902
                                                }
903
904 14
                                                break;
905 17
                                            case 'b':
906 4
                                                if (!isset($c->f)) {
907 2
                                                    $value = self::castToBoolean($c);
908
                                                } else {
909
                                                    // Formula
910 2
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean');
911 2
                                                    if (isset($c->f['t'])) {
912
                                                        $att = $c->f;
913
                                                        $docSheet->getCell($r)->setFormulaAttributes($att);
914
                                                    }
915
                                                }
916
917 4
                                                break;
918 14
                                            case 'inlineStr':
919 2
                                                if (isset($c->f)) {
920
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
921
                                                } else {
922 2
                                                    $value = $this->parseRichText($c->is);
923
                                                }
924
925 2
                                                break;
926 14
                                            case 'e':
927
                                                if (!isset($c->f)) {
928
                                                    $value = self::castToError($c);
929
                                                } else {
930
                                                    // Formula
931
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
932
                                                }
933
934
                                                break;
935
                                            default:
936 14
                                                if (!isset($c->f)) {
937 12
                                                    $value = self::castToString($c);
938
                                                } else {
939
                                                    // Formula
940 6
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
941
                                                }
942
943 14
                                                break;
944
                                        }
945
946
                                        // Check for numeric values
947 24
                                        if (is_numeric($value) && $cellDataType != 's') {
948 12
                                            if ($value == (int) $value) {
949 11
                                                $value = (int) $value;
950 1
                                            } elseif ($value == (float) $value) {
951 1
                                                $value = (float) $value;
952
                                            } elseif ($value == (float) $value) {
953
                                                $value = (float) $value;
954
                                            }
955
                                        }
956
957
                                        // Rich text?
958 24
                                        if ($value instanceof RichText && $this->readDataOnly) {
959
                                            $value = $value->getPlainText();
960
                                        }
961
962 24
                                        $cell = $docSheet->getCell($r);
963
                                        // Assign value
964 24
                                        if ($cellDataType != '') {
965 18
                                            $cell->setValueExplicit($value, $cellDataType);
966
                                        } else {
967 12
                                            $cell->setValue($value);
968
                                        }
969 24
                                        if ($calculatedValue !== null) {
970 7
                                            $cell->setCalculatedValue($calculatedValue);
971
                                        }
972
973
                                        // Style information?
974 24
                                        if ($c['s'] && !$this->readDataOnly) {
975
                                            // no style index means 0, it seems
976 7
                                            $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
977 7
                                                (int) ($c['s']) : 0);
978
                                        }
979 24
                                        $rowIndex += 1;
980
                                    }
981 24
                                    $cIndex += 1;
982
                                }
983
                            }
984
985 29
                            $conditionals = [];
986 29
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
987 1
                                foreach ($xmlSheet->conditionalFormatting as $conditional) {
988 1
                                    foreach ($conditional->cfRule as $cfRule) {
989 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'])])) {
990 1
                                            $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
991
                                        }
992
                                    }
993
                                }
994
995 1
                                foreach ($conditionals as $ref => $cfRules) {
996 1
                                    ksort($cfRules);
997 1
                                    $conditionalStyles = [];
998 1
                                    foreach ($cfRules as $cfRule) {
999 1
                                        $objConditional = new Conditional();
1000 1
                                        $objConditional->setConditionType((string) $cfRule['type']);
1001 1
                                        $objConditional->setOperatorType((string) $cfRule['operator']);
1002
1003 1
                                        if ((string) $cfRule['text'] != '') {
1004
                                            $objConditional->setText((string) $cfRule['text']);
1005
                                        }
1006
1007 1
                                        if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
1008 1
                                            $objConditional->setStopIfTrue(true);
1009
                                        }
1010
1011 1
                                        if (count($cfRule->formula) > 1) {
1012
                                            foreach ($cfRule->formula as $formula) {
1013
                                                $objConditional->addCondition((string) $formula);
1014
                                            }
1015
                                        } else {
1016 1
                                            $objConditional->addCondition((string) $cfRule->formula);
1017
                                        }
1018 1
                                        $objConditional->setStyle(clone $dxfs[(int) ($cfRule['dxfId'])]);
1019 1
                                        $conditionalStyles[] = $objConditional;
1020
                                    }
1021
1022
                                    // Extract all cell references in $ref
1023 1
                                    $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
1024 1
                                    foreach ($cellBlocks as $cellBlock) {
1025 1
                                        $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
1026
                                    }
1027
                                }
1028
                            }
1029
1030 29
                            $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
1031 29
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1032 24
                                foreach ($aKeys as $key) {
1033 24
                                    $method = 'set' . ucfirst($key);
1034 24
                                    $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
1035
                                }
1036
                            }
1037
1038 29
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1039 24
                                $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true);
1040 24
                                if ($xmlSheet->protectedRanges->protectedRange) {
1041 2
                                    foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
1042 2
                                        $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
1043
                                    }
1044
                                }
1045
                            }
1046
1047 29
                            if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
1048
                                $autoFilterRange = (string) $xmlSheet->autoFilter['ref'];
1049
                                if (strpos($autoFilterRange, ':') !== false) {
1050
                                    $autoFilter = $docSheet->getAutoFilter();
1051
                                    $autoFilter->setRange($autoFilterRange);
1052
1053
                                    foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
1054
                                        $column = $autoFilter->getColumnByOffset((int) $filterColumn['colId']);
1055
                                        //    Check for standard filters
1056
                                        if ($filterColumn->filters) {
1057
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
1058
                                            $filters = $filterColumn->filters;
1059
                                            if ((isset($filters['blank'])) && ($filters['blank'] == 1)) {
1060
                                                //    Operator is undefined, but always treated as EQUAL
1061
                                                $column->createRule()->setRule(null, '')->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1062
                                            }
1063
                                            //    Standard filters are always an OR join, so no join rule needs to be set
1064
                                            //    Entries can be either filter elements
1065
                                            foreach ($filters->filter as $filterRule) {
1066
                                                //    Operator is undefined, but always treated as EQUAL
1067
                                                $column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1068
                                            }
1069
                                            //    Or Date Group elements
1070
                                            foreach ($filters->dateGroupItem as $dateGroupItem) {
1071
                                                $column->createRule()->setRule(
1072
                                                    //    Operator is undefined, but always treated as EQUAL
1073
                                                    null,
1074
                                                    [
1075
                                                        'year' => (string) $dateGroupItem['year'],
1076
                                                        'month' => (string) $dateGroupItem['month'],
1077
                                                        'day' => (string) $dateGroupItem['day'],
1078
                                                        'hour' => (string) $dateGroupItem['hour'],
1079
                                                        'minute' => (string) $dateGroupItem['minute'],
1080
                                                        'second' => (string) $dateGroupItem['second'],
1081
                                                    ],
1082
                                                    (string) $dateGroupItem['dateTimeGrouping']
1083
                                                )
1084
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP);
1085
                                            }
1086
                                        }
1087
                                        //    Check for custom filters
1088
                                        if ($filterColumn->customFilters) {
1089
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
1090
                                            $customFilters = $filterColumn->customFilters;
1091
                                            //    Custom filters can an AND or an OR join;
1092
                                            //        and there should only ever be one or two entries
1093
                                            if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
1094
                                                $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
1095
                                            }
1096
                                            foreach ($customFilters->customFilter as $filterRule) {
1097
                                                $column->createRule()->setRule(
1098
                                                    (string) $filterRule['operator'],
1099
                                                    (string) $filterRule['val']
1100
                                                )
1101
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
1102
                                            }
1103
                                        }
1104
                                        //    Check for dynamic filters
1105
                                        if ($filterColumn->dynamicFilter) {
1106
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
1107
                                            //    We should only ever have one dynamic filter
1108
                                            foreach ($filterColumn->dynamicFilter as $filterRule) {
1109
                                                $column->createRule()->setRule(
1110
                                                    //    Operator is undefined, but always treated as EQUAL
1111
                                                    null,
1112
                                                    (string) $filterRule['val'],
1113
                                                    (string) $filterRule['type']
1114
                                                )
1115
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
1116
                                                if (isset($filterRule['val'])) {
1117
                                                    $column->setAttribute('val', (string) $filterRule['val']);
1118
                                                }
1119
                                                if (isset($filterRule['maxVal'])) {
1120
                                                    $column->setAttribute('maxVal', (string) $filterRule['maxVal']);
1121
                                                }
1122
                                            }
1123
                                        }
1124
                                        //    Check for dynamic filters
1125
                                        if ($filterColumn->top10) {
1126
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
1127
                                            //    We should only ever have one top10 filter
1128
                                            foreach ($filterColumn->top10 as $filterRule) {
1129
                                                $column->createRule()->setRule(
1130
                                                    (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
1131
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
1132
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
1133
                                                    ),
1134
                                                    (string) $filterRule['val'],
1135
                                                    (((isset($filterRule['top'])) && ($filterRule['top'] == 1))
1136
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
1137
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
1138
                                                    )
1139
                                                )
1140
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
1141
                                            }
1142
                                        }
1143
                                    }
1144
                                }
1145
                            }
1146
1147 29
                            if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
1148 6
                                foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
1149 6
                                    $mergeRef = (string) $mergeCell['ref'];
1150 6
                                    if (strpos($mergeRef, ':') !== false) {
1151 6
                                        $docSheet->mergeCells((string) $mergeCell['ref']);
1152
                                    }
1153
                                }
1154
                            }
1155
1156 29
                            if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) {
1157 28
                                $docPageMargins = $docSheet->getPageMargins();
1158 28
                                $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
1159 28
                                $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
1160 28
                                $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
1161 28
                                $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
1162 28
                                $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
1163 28
                                $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
1164
                            }
1165
1166 29
                            if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) {
1167 28
                                $docPageSetup = $docSheet->getPageSetup();
1168
1169 28
                                if (isset($xmlSheet->pageSetup['orientation'])) {
1170 28
                                    $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
1171
                                }
1172 28
                                if (isset($xmlSheet->pageSetup['paperSize'])) {
1173 26
                                    $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
1174
                                }
1175 28
                                if (isset($xmlSheet->pageSetup['scale'])) {
1176 22
                                    $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
1177
                                }
1178 28
                                if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
1179 22
                                    $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
1180
                                }
1181 28
                                if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
1182 22
                                    $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
1183
                                }
1184 28
                                if (isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) &&
1185 28
                                    self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) {
1186
                                    $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
1187
                                }
1188
                            }
1189
1190 29
                            if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) {
1191 24
                                $docHeaderFooter = $docSheet->getHeaderFooter();
1192
1193 24
                                if (isset($xmlSheet->headerFooter['differentOddEven']) &&
1194 24
                                    self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) {
1195
                                    $docHeaderFooter->setDifferentOddEven(true);
1196
                                } else {
1197 24
                                    $docHeaderFooter->setDifferentOddEven(false);
1198
                                }
1199 24
                                if (isset($xmlSheet->headerFooter['differentFirst']) &&
1200 24
                                    self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) {
1201
                                    $docHeaderFooter->setDifferentFirst(true);
1202
                                } else {
1203 24
                                    $docHeaderFooter->setDifferentFirst(false);
1204
                                }
1205 24
                                if (isset($xmlSheet->headerFooter['scaleWithDoc']) &&
1206 24
                                    !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) {
1207
                                    $docHeaderFooter->setScaleWithDocument(false);
1208
                                } else {
1209 24
                                    $docHeaderFooter->setScaleWithDocument(true);
1210
                                }
1211 24
                                if (isset($xmlSheet->headerFooter['alignWithMargins']) &&
1212 24
                                    !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) {
1213 3
                                    $docHeaderFooter->setAlignWithMargins(false);
1214
                                } else {
1215 21
                                    $docHeaderFooter->setAlignWithMargins(true);
1216
                                }
1217
1218 24
                                $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
1219 24
                                $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
1220 24
                                $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
1221 24
                                $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
1222 24
                                $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
1223 24
                                $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
1224
                            }
1225
1226 29
                            if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) {
1227
                                foreach ($xmlSheet->rowBreaks->brk as $brk) {
1228
                                    if ($brk['man']) {
1229
                                        $docSheet->setBreak("A$brk[id]", Worksheet::BREAK_ROW);
1230
                                    }
1231
                                }
1232
                            }
1233 29
                            if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) {
1234
                                foreach ($xmlSheet->colBreaks->brk as $brk) {
1235
                                    if ($brk['man']) {
1236
                                        $docSheet->setBreak(Coordinate::stringFromColumnIndex((string) $brk['id'] + 1) . '1', Worksheet::BREAK_COLUMN);
1237
                                    }
1238
                                }
1239
                            }
1240
1241 29
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
1242
                                foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
1243
                                    // Uppercase coordinate
1244
                                    $range = strtoupper($dataValidation['sqref']);
1245
                                    $rangeSet = explode(' ', $range);
1246
                                    foreach ($rangeSet as $range) {
1247
                                        $stRange = $docSheet->shrinkRangeToFit($range);
1248
1249
                                        // Extract all cell references in $range
1250
                                        foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) {
1251
                                            // Create validation
1252
                                            $docValidation = $docSheet->getCell($reference)->getDataValidation();
1253
                                            $docValidation->setType((string) $dataValidation['type']);
1254
                                            $docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
1255
                                            $docValidation->setOperator((string) $dataValidation['operator']);
1256
                                            $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
1257
                                            $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
1258
                                            $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
1259
                                            $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
1260
                                            $docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
1261
                                            $docValidation->setError((string) $dataValidation['error']);
1262
                                            $docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
1263
                                            $docValidation->setPrompt((string) $dataValidation['prompt']);
1264
                                            $docValidation->setFormula1((string) $dataValidation->formula1);
1265
                                            $docValidation->setFormula2((string) $dataValidation->formula2);
1266
                                        }
1267
                                    }
1268
                                }
1269
                            }
1270
1271
                            // Add hyperlinks
1272 29
                            $hyperlinks = [];
1273 29
                            if (!$this->readDataOnly) {
1274
                                // Locate hyperlink relations
1275 29
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1276 28
                                    $relsWorksheet = simplexml_load_string(
1277
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1278 28
                                        $this->securityScan(
1279 28
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1280
                                        ),
1281 28
                                        'SimpleXMLElement',
1282 28
                                        Settings::getLibXmlLoaderOptions()
1283
                                    );
1284 28
                                    foreach ($relsWorksheet->Relationship as $ele) {
1285 8
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1286 8
                                            $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1287
                                        }
1288
                                    }
1289
                                }
1290
1291
                                // Loop through hyperlinks
1292 29
                                if ($xmlSheet && $xmlSheet->hyperlinks) {
1293
                                    /** @var \SimpleXMLElement $hyperlink */
1294 2
                                    foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
1295
                                        // Link url
1296 2
                                        $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1297
1298 2
                                        foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
1299 2
                                            $cell = $docSheet->getCell($cellReference);
1300 2
                                            if (isset($linkRel['id'])) {
1301 2
                                                $hyperlinkUrl = $hyperlinks[(string) $linkRel['id']];
1302 2
                                                if (isset($hyperlink['location'])) {
1303
                                                    $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
1304
                                                }
1305 2
                                                $cell->getHyperlink()->setUrl($hyperlinkUrl);
1306 2
                                            } elseif (isset($hyperlink['location'])) {
1307 2
                                                $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
1308
                                            }
1309
1310
                                            // Tooltip
1311 2
                                            if (isset($hyperlink['tooltip'])) {
1312 2
                                                $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
1313
                                            }
1314
                                        }
1315
                                    }
1316
                                }
1317
                            }
1318
1319
                            // Add comments
1320 29
                            $comments = [];
1321 29
                            $vmlComments = [];
1322 29
                            if (!$this->readDataOnly) {
1323
                                // Locate comment relations
1324 29
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1325 28
                                    $relsWorksheet = simplexml_load_string(
1326
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1327 28
                                        $this->securityScan(
1328 28
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1329
                                        ),
1330 28
                                        'SimpleXMLElement',
1331 28
                                        Settings::getLibXmlLoaderOptions()
1332
                                    );
1333 28
                                    foreach ($relsWorksheet->Relationship as $ele) {
1334 8
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
1335 2
                                            $comments[(string) $ele['Id']] = (string) $ele['Target'];
1336
                                        }
1337 8
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1338 8
                                            $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
1339
                                        }
1340
                                    }
1341
                                }
1342
1343
                                // Loop through comments
1344 29
                                foreach ($comments as $relName => $relPath) {
1345
                                    // Load comments file
1346 2
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1347 2
                                    $commentsFile = simplexml_load_string(
1348 2
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1349 2
                                        'SimpleXMLElement',
1350 2
                                        Settings::getLibXmlLoaderOptions()
1351
                                    );
1352
1353
                                    // Utility variables
1354 2
                                    $authors = [];
1355
1356
                                    // Loop through authors
1357 2
                                    foreach ($commentsFile->authors->author as $author) {
1358 2
                                        $authors[] = (string) $author;
1359
                                    }
1360
1361
                                    // Loop through contents
1362 2
                                    foreach ($commentsFile->commentList->comment as $comment) {
1363 2
                                        if (!empty($comment['authorId'])) {
1364
                                            $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]);
1365
                                        }
1366 2
                                        $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text));
1367
                                    }
1368
                                }
1369
1370
                                // Loop through VML comments
1371 29
                                foreach ($vmlComments as $relName => $relPath) {
1372
                                    // Load VML comments file
1373 2
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1374 2
                                    $vmlCommentsFile = simplexml_load_string(
1375 2
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1376 2
                                        'SimpleXMLElement',
1377 2
                                        Settings::getLibXmlLoaderOptions()
1378
                                    );
1379 2
                                    $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1380
1381 2
                                    $shapes = $vmlCommentsFile->xpath('//v:shape');
1382 2
                                    foreach ($shapes as $shape) {
1383 2
                                        $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1384
1385 2
                                        if (isset($shape['style'])) {
1386 2
                                            $style = (string) $shape['style'];
1387 2
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
1388 2
                                            $column = null;
1389 2
                                            $row = null;
1390
1391 2
                                            $clientData = $shape->xpath('.//x:ClientData');
1392 2
                                            if (is_array($clientData) && !empty($clientData)) {
1393 2
                                                $clientData = $clientData[0];
1394
1395 2
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
1396 2
                                                    $temp = $clientData->xpath('.//x:Row');
1397 2
                                                    if (is_array($temp)) {
1398 2
                                                        $row = $temp[0];
1399
                                                    }
1400
1401 2
                                                    $temp = $clientData->xpath('.//x:Column');
1402 2
                                                    if (is_array($temp)) {
1403 2
                                                        $column = $temp[0];
1404
                                                    }
1405
                                                }
1406
                                            }
1407
1408 2
                                            if (($column !== null) && ($row !== null)) {
1409
                                                // Set comment properties
1410 2
                                                $comment = $docSheet->getCommentByColumnAndRow((string) $column, $row + 1);
0 ignored issues
show
Bug introduced by
(string)$column of type string is incompatible with the type integer expected by parameter $columnIndex of PhpOffice\PhpSpreadsheet...CommentByColumnAndRow(). ( Ignorable by Annotation )

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

1410
                                                $comment = $docSheet->getCommentByColumnAndRow(/** @scrutinizer ignore-type */ (string) $column, $row + 1);
Loading history...
1411 2
                                                $comment->getFillColor()->setRGB($fillColor);
1412
1413
                                                // Parse style
1414 2
                                                $styleArray = explode(';', str_replace(' ', '', $style));
1415 2
                                                foreach ($styleArray as $stylePair) {
1416 2
                                                    $stylePair = explode(':', $stylePair);
1417
1418 2
                                                    if ($stylePair[0] == 'margin-left') {
1419 2
                                                        $comment->setMarginLeft($stylePair[1]);
1420
                                                    }
1421 2
                                                    if ($stylePair[0] == 'margin-top') {
1422 2
                                                        $comment->setMarginTop($stylePair[1]);
1423
                                                    }
1424 2
                                                    if ($stylePair[0] == 'width') {
1425 2
                                                        $comment->setWidth($stylePair[1]);
1426
                                                    }
1427 2
                                                    if ($stylePair[0] == 'height') {
1428 2
                                                        $comment->setHeight($stylePair[1]);
1429
                                                    }
1430 2
                                                    if ($stylePair[0] == 'visibility') {
1431 2
                                                        $comment->setVisible($stylePair[1] == 'visible');
1432
                                                    }
1433
                                                }
1434
                                            }
1435
                                        }
1436
                                    }
1437
                                }
1438
1439
                                // Header/footer images
1440 29
                                if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
1441
                                    if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1442
                                        $relsWorksheet = simplexml_load_string(
1443
                                            //~ http://schemas.openxmlformats.org/package/2006/relationships"
1444
                                            $this->securityScan(
1445
                                                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1446
                                            ),
1447
                                            'SimpleXMLElement',
1448
                                            Settings::getLibXmlLoaderOptions()
1449
                                        );
1450
                                        $vmlRelationship = '';
1451
1452
                                        foreach ($relsWorksheet->Relationship as $ele) {
1453
                                            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1454
                                                $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1455
                                            }
1456
                                        }
1457
1458
                                        if ($vmlRelationship != '') {
1459
                                            // Fetch linked images
1460
                                            $relsVML = simplexml_load_string(
1461
                                                //~ http://schemas.openxmlformats.org/package/2006/relationships"
1462
                                                $this->securityScan(
1463
                                                    $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
1464
                                                ),
1465
                                                'SimpleXMLElement',
1466
                                                Settings::getLibXmlLoaderOptions()
1467
                                            );
1468
                                            $drawings = [];
1469
                                            foreach ($relsVML->Relationship as $ele) {
1470
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1471
                                                    $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
1472
                                                }
1473
                                            }
1474
1475
                                            // Fetch VML document
1476
                                            $vmlDrawing = simplexml_load_string(
1477
                                                $this->securityScan($this->getFromZipArchive($zip, $vmlRelationship)),
1478
                                                'SimpleXMLElement',
1479
                                                Settings::getLibXmlLoaderOptions()
1480
                                            );
1481
                                            $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1482
1483
                                            $hfImages = [];
1484
1485
                                            $shapes = $vmlDrawing->xpath('//v:shape');
1486
                                            foreach ($shapes as $idx => $shape) {
1487
                                                $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1488
                                                $imageData = $shape->xpath('//v:imagedata');
1489
1490
                                                if (!$imageData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $imageData of type SimpleXMLElement[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
1491
                                                    continue;
1492
                                                }
1493
1494
                                                $imageData = $imageData[$idx];
1495
1496
                                                $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
1497
                                                $style = self::toCSSArray((string) $shape['style']);
1498
1499
                                                $hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
1500
                                                if (isset($imageData['title'])) {
1501
                                                    $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
1502
                                                }
1503
1504
                                                $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
1505
                                                $hfImages[(string) $shape['id']]->setResizeProportional(false);
1506
                                                $hfImages[(string) $shape['id']]->setWidth($style['width']);
1507
                                                $hfImages[(string) $shape['id']]->setHeight($style['height']);
1508
                                                if (isset($style['margin-left'])) {
1509
                                                    $hfImages[(string) $shape['id']]->setOffsetX($style['margin-left']);
1510
                                                }
1511
                                                $hfImages[(string) $shape['id']]->setOffsetY($style['margin-top']);
1512
                                                $hfImages[(string) $shape['id']]->setResizeProportional(true);
1513
                                            }
1514
1515
                                            $docSheet->getHeaderFooter()->setImages($hfImages);
1516
                                        }
1517
                                    }
1518
                                }
1519
                            }
1520
1521
                            // TODO: Autoshapes from twoCellAnchors!
1522 29
                            if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1523 28
                                $relsWorksheet = simplexml_load_string(
1524
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1525 28
                                    $this->securityScan(
1526 28
                                        $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1527
                                    ),
1528 28
                                    'SimpleXMLElement',
1529 28
                                    Settings::getLibXmlLoaderOptions()
1530
                                );
1531 28
                                $drawings = [];
1532 28
                                foreach ($relsWorksheet->Relationship as $ele) {
1533 8
                                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1534 8
                                        $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1535
                                    }
1536
                                }
1537 28
                                if ($xmlSheet->drawing && !$this->readDataOnly) {
1538 4
                                    foreach ($xmlSheet->drawing as $drawing) {
1539 4
                                        $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
1540 4
                                        $relsDrawing = simplexml_load_string(
1541
                                            //~ http://schemas.openxmlformats.org/package/2006/relationships"
1542 4
                                            $this->securityScan(
1543 4
                                                $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
1544
                                            ),
1545 4
                                            'SimpleXMLElement',
1546 4
                                            Settings::getLibXmlLoaderOptions()
1547
                                        );
1548 4
                                        $images = [];
1549
1550 4
                                        if ($relsDrawing && $relsDrawing->Relationship) {
1551 4
                                            foreach ($relsDrawing->Relationship as $ele) {
1552 4
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1553 4
                                                    $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
1554 2
                                                } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
1555 2
                                                    if ($this->includeCharts) {
1556 2
                                                        $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
1557 2
                                                            'id' => (string) $ele['Id'],
1558 4
                                                            'sheet' => $docSheet->getTitle(),
1559
                                                        ];
1560
                                                    }
1561
                                                }
1562
                                            }
1563
                                        }
1564 4
                                        $xmlDrawing = simplexml_load_string(
1565 4
                                            $this->securityScan($this->getFromZipArchive($zip, $fileDrawing)),
1566 4
                                            'SimpleXMLElement',
1567 4
                                            Settings::getLibXmlLoaderOptions()
1568 4
                                        )->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
1569
1570 4
                                        if ($xmlDrawing->oneCellAnchor) {
1571 2
                                            foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
1572 2
                                                if ($oneCellAnchor->pic->blipFill) {
1573
                                                    /** @var \SimpleXMLElement $blip */
1574 2
                                                    $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1575
                                                    /** @var \SimpleXMLElement $xfrm */
1576 2
                                                    $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1577
                                                    /** @var \SimpleXMLElement $outerShdw */
1578 2
                                                    $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1579 2
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1580 2
                                                    $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1581 2
                                                    $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1582 2
                                                    $objDrawing->setPath(
1583 2
                                                        'zip://' . File::realpath($pFilename) . '#' .
1584 2
                                                        $images[(string) self::getArrayItem(
1585 2
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1586 2
                                                            'embed'
1587
                                                        )],
1588 2
                                                        false
1589
                                                    );
1590 2
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
1591 2
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
1592 2
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
1593 2
                                                    $objDrawing->setResizeProportional(false);
1594 2
                                                    $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
1595 2
                                                    $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
1596 2
                                                    if ($xfrm) {
1597 2
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
1 ignored issue
show
Bug introduced by
It seems like self::getArrayItem($xfrm->attributes(), 'rot') can also be of type SimpleXMLElement; however, parameter $pValue of PhpOffice\PhpSpreadsheet...awing::angleToDegrees() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

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

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

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

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

2039
            $docStyle->setQuotePrefix(/** @scrutinizer ignore-type */ $style->quotePrefix);
Loading history...
2040
        }
2041 29
    }
2042
2043
    /**
2044
     * @param Border $docBorder
2045
     * @param \SimpleXMLElement $eleBorder
2046
     */
2047 29
    private static function readBorder(Border $docBorder, $eleBorder)
2048
    {
2049 29
        if (isset($eleBorder['style'])) {
2050 3
            $docBorder->setBorderStyle((string) $eleBorder['style']);
2051
        }
2052 29
        if (isset($eleBorder->color)) {
2053 3
            $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
2054
        }
2055 29
    }
2056
2057
    /**
2058
     * @param \SimpleXMLElement | null $is
2059
     *
2060
     * @return RichText
2061
     */
2062 3
    private function parseRichText($is)
2063
    {
2064 3
        $value = new RichText();
2065
2066 3
        if (isset($is->t)) {
2067
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
2068
        } else {
2069 3
            if (is_object($is->r)) {
2070 3
                foreach ($is->r as $run) {
2071 3
                    if (!isset($run->rPr)) {
2072 3
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2073
                    } else {
2074 3
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2075
2076 3
                        if (isset($run->rPr->rFont['val'])) {
2077 3
                            $objText->getFont()->setName((string) $run->rPr->rFont['val']);
2078
                        }
2079 3
                        if (isset($run->rPr->sz['val'])) {
2080 3
                            $objText->getFont()->setSize((float) $run->rPr->sz['val']);
2081
                        }
2082 3
                        if (isset($run->rPr->color)) {
2083 3
                            $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
2084
                        }
2085 3
                        if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
2086 3
                            (isset($run->rPr->b) && !isset($run->rPr->b['val']))) {
2087 3
                            $objText->getFont()->setBold(true);
2088
                        }
2089 3
                        if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
2090 3
                            (isset($run->rPr->i) && !isset($run->rPr->i['val']))) {
2091 2
                            $objText->getFont()->setItalic(true);
2092
                        }
2093 3
                        if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
2094
                            $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
2095
                            if ($vertAlign == 'superscript') {
2096
                                $objText->getFont()->setSuperscript(true);
2097
                            }
2098
                            if ($vertAlign == 'subscript') {
2099
                                $objText->getFont()->setSubscript(true);
2100
                            }
2101
                        }
2102 3
                        if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
2103
                            $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2104 3
                        } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
2105 2
                            $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
2106
                        }
2107 3
                        if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
2108 3
                            (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) {
2109 3
                            $objText->getFont()->setStrikethrough(true);
2110
                        }
2111
                    }
2112
                }
2113
            }
2114
        }
2115
2116 3
        return $value;
2117
    }
2118
2119
    /**
2120
     * @param Spreadsheet $excel
2121
     * @param mixed $customUITarget
2122
     * @param mixed $zip
2123
     */
2124
    private function readRibbon(Spreadsheet $excel, $customUITarget, $zip)
2125
    {
2126
        $baseDir = dirname($customUITarget);
2127
        $nameCustomUI = basename($customUITarget);
2128
        // get the xml file (ribbon)
2129
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
2130
        $customUIImagesNames = [];
2131
        $customUIImagesBinaries = [];
2132
        // something like customUI/_rels/customUI.xml.rels
2133
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
2134
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
2135
        if ($dataRels) {
2136
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
2137
            $UIRels = simplexml_load_string(
2138
                $this->securityScan($dataRels),
2139
                'SimpleXMLElement',
2140
                Settings::getLibXmlLoaderOptions()
2141
            );
2142
            if (false !== $UIRels) {
2143
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
2144
                foreach ($UIRels->Relationship as $ele) {
2145
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
2146
                        // an image ?
2147
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
2148
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
2149
                    }
2150
                }
2151
            }
2152
        }
2153
        if ($localRibbon) {
2154
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
2155
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2156
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
2157
            } else {
2158
                $excel->setRibbonBinObjects(null, null);
2159
            }
2160
        } else {
2161
            $excel->setRibbonXMLData(null, null);
2162
            $excel->setRibbonBinObjects(null, null);
2163
        }
2164
    }
2165
2166 30
    private static function getArrayItem($array, $key = 0)
2167
    {
2168 30
        return isset($array[$key]) ? $array[$key] : null;
2169
    }
2170
2171 4
    private static function dirAdd($base, $add)
2172
    {
2173 4
        return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
2174
    }
2175
2176
    private static function toCSSArray($style)
2177
    {
2178
        $style = trim(str_replace(["\r", "\n"], '', $style), ';');
2179
2180
        $temp = explode(';', $style);
2181
        $style = [];
2182
        foreach ($temp as $item) {
2183
            $item = explode(':', $item);
2184
2185
            if (strpos($item[1], 'px') !== false) {
2186
                $item[1] = str_replace('px', '', $item[1]);
2187
            }
2188
            if (strpos($item[1], 'pt') !== false) {
2189
                $item[1] = str_replace('pt', '', $item[1]);
2190
                $item[1] = Font::fontSizeToPixels($item[1]);
2191
            }
2192
            if (strpos($item[1], 'in') !== false) {
2193
                $item[1] = str_replace('in', '', $item[1]);
2194
                $item[1] = Font::inchSizeToPixels($item[1]);
2195
            }
2196
            if (strpos($item[1], 'cm') !== false) {
2197
                $item[1] = str_replace('cm', '', $item[1]);
2198
                $item[1] = Font::centimeterSizeToPixels($item[1]);
2199
            }
2200
2201
            $style[$item[0]] = $item[1];
2202
        }
2203
2204
        return $style;
2205
    }
2206
2207 29
    private static function boolean($value)
2208
    {
2209 29
        if (is_object($value)) {
2210 1
            $value = (string) $value;
2211
        }
2212 29
        if (is_numeric($value)) {
2213 26
            return (bool) $value;
2214
        }
2215
2216 29
        return $value === 'true' || $value === 'TRUE';
2217
    }
2218
}
2219