Failed Conditions
Push — develop ( 064076...83c759 )
by Adrien
63:09
created

Xlsx::readBorder()   A

Complexity

Conditions 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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

289
                $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], /** @scrutinizer ignore-type */ 'A1', $difference[0], $difference[1]);
Loading history...
290
            }
291 7
        }
292
    }
293
294
    /**
295
     * @param ZipArchive $archive
296
     * @param string $fileName
297
     *
298
     * @return string
299 32
     */
300
    private function getFromZipArchive(ZipArchive $archive, $fileName = '')
301
    {
302 32
        // Root-relative paths
303
        if (strpos($fileName, '//') !== false) {
304
            $fileName = substr($fileName, strpos($fileName, '//') + 1);
305 32
        }
306
        $fileName = File::realpath($fileName);
307
308
        // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
309
        //    so we need to load case-insensitively from the zip file
310
311 32
        // Apache POI fixes
312 32
        $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
313
        if ($contents === false) {
314
            $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
315
        }
316 32
317
        return $contents;
318
    }
319
320
    /**
321
     * Loads Spreadsheet from file.
322
     *
323
     * @param string $pFilename
324
     *
325
     * @throws Exception
326
     *
327
     * @return Spreadsheet
328 29
     */
329
    public function load($pFilename)
330 29
    {
331
        File::assertFile($pFilename);
332
333 29
        // Initialisations
334 29
        $excel = new Spreadsheet();
335 29
        $excel->removeSheetByIndex(0);
336 29
        if (!$this->readDataOnly) {
337 29
            $excel->removeCellStyleXfByIndex(0); // remove the default style
338
            $excel->removeCellXfByIndex(0); // remove the default style
339
        }
340 29
        $unparsedLoadedData = [];
341 29
342
        $zip = new ZipArchive();
343
        $zip->open($pFilename);
344 29
345
        //    Read the theme first, because we need the colour scheme when reading the styles
346 29
        $wbRels = simplexml_load_string(
347 29
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
348 29
            $this->securityScan($this->getFromZipArchive($zip, 'xl/_rels/workbook.xml.rels')),
349
            'SimpleXMLElement',
350 29
            Settings::getLibXmlLoaderOptions()
351 29
        );
352 29
        foreach ($wbRels->Relationship as $rel) {
353 29
            switch ($rel['Type']) {
354 29
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme':
355
                    $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
356 29
                    $themeOrderAdditional = count($themeOrderArray);
357 29
358 29
                    $xmlTheme = simplexml_load_string(
359 29
                        $this->securityScan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")),
360
                        'SimpleXMLElement',
361 29
                        Settings::getLibXmlLoaderOptions()
362 29
                    );
363 29
                    if (is_object($xmlTheme)) {
364 29
                        $xmlThemeName = $xmlTheme->attributes();
365
                        $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
366 29
                        $themeName = (string) $xmlThemeName['name'];
367 29
368 29
                        $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
369
                        $colourSchemeName = (string) $colourScheme['name'];
370 29
                        $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
371 29
372 29
                        $themeColours = [];
373 29
                        foreach ($colourScheme as $k => $xmlColour) {
374 29
                            $themePos = array_search($k, $themeOrderArray);
375
                            if ($themePos === false) {
376 29
                                $themePos = $themeOrderAdditional++;
377 29
                            }
378 29
                            if (isset($xmlColour->sysClr)) {
379 29
                                $xmlColourData = $xmlColour->sysClr->attributes();
380 29
                                $themeColours[$themePos] = $xmlColourData['lastClr'];
381 29
                            } elseif (isset($xmlColour->srgbClr)) {
382
                                $xmlColourData = $xmlColour->srgbClr->attributes();
383
                                $themeColours[$themePos] = $xmlColourData['val'];
384 29
                            }
385
                        }
386
                        self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours);
387 29
                    }
388
389
                    break;
390
            }
391 29
        }
392
393 29
        $rels = simplexml_load_string(
394 29
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
395 29
            $this->securityScan($this->getFromZipArchive($zip, '_rels/.rels')),
396
            'SimpleXMLElement',
397 29
            Settings::getLibXmlLoaderOptions()
398 29
        );
399 29
        foreach ($rels->Relationship as $rel) {
400 28
            switch ($rel['Type']) {
401 28
                case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties':
402 28
                    $xmlCore = simplexml_load_string(
403 28
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
404
                        'SimpleXMLElement',
405 28
                        Settings::getLibXmlLoaderOptions()
406 28
                    );
407 28
                    if (is_object($xmlCore)) {
408 28
                        $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/');
409 28
                        $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/');
410 28
                        $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
411 28
                        $docProps = $excel->getProperties();
412 28
                        $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator')));
413 28
                        $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy')));
414 28
                        $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type
415 28
                        $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type
416 28
                        $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title')));
417 28
                        $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description')));
418 28
                        $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject')));
419
                        $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath('cp:keywords')));
420
                        $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath('cp:category')));
421 28
                    }
422 29
423 28
                    break;
424 28
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties':
425 28
                    $xmlCore = simplexml_load_string(
426 28
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
427
                        'SimpleXMLElement',
428 28
                        Settings::getLibXmlLoaderOptions()
429 28
                    );
430 28
                    if (is_object($xmlCore)) {
431 26
                        $docProps = $excel->getProperties();
432
                        if (isset($xmlCore->Company)) {
433 28
                            $docProps->setCompany((string) $xmlCore->Company);
434 24
                        }
435
                        if (isset($xmlCore->Manager)) {
436
                            $docProps->setManager((string) $xmlCore->Manager);
437
                        }
438 28
                    }
439 29
440 3
                    break;
441 3
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties':
442 3
                    $xmlCore = simplexml_load_string(
443 3
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
444
                        'SimpleXMLElement',
445 3
                        Settings::getLibXmlLoaderOptions()
446 3
                    );
447
                    if (is_object($xmlCore)) {
448 3
                        $docProps = $excel->getProperties();
449 3
                        /** @var SimpleXMLElement $xmlProperty */
450 3
                        foreach ($xmlCore as $xmlProperty) {
451 3
                            $cellDataOfficeAttributes = $xmlProperty->attributes();
452 3
                            if (isset($cellDataOfficeAttributes['name'])) {
453 3
                                $propertyName = (string) $cellDataOfficeAttributes['name'];
454 3
                                $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
455 3
                                $attributeType = $cellDataOfficeChildren->getName();
456 3
                                $attributeValue = (string) $cellDataOfficeChildren->{$attributeType};
457 3
                                $attributeValue = Properties::convertProperty($attributeValue, $attributeType);
458
                                $attributeType = Properties::convertPropertyType($attributeType);
459
                                $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType);
460
                            }
461
                        }
462 3
                    }
463
464 29
                    break;
465
                //Ribbon
466
                case 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility':
467
                    $customUI = $rel['Target'];
468
                    if ($customUI !== null) {
469
                        $this->readRibbon($excel, $customUI, $zip);
470
                    }
471 29
472 29
                    break;
473 29
                case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
474
                    $dir = dirname($rel['Target']);
475 29
                    $relsWorkbook = simplexml_load_string(
476 29
                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
477 29
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')),
478
                        'SimpleXMLElement',
479 29
                        Settings::getLibXmlLoaderOptions()
480
                    );
481 29
                    $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
482 29
483 29
                    $sharedStrings = [];
484
                    $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
485 29
                    $xmlStrings = simplexml_load_string(
486 29
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
487 29
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
488
                        'SimpleXMLElement',
489 29
                        Settings::getLibXmlLoaderOptions()
490 14
                    );
491 14
                    if (isset($xmlStrings, $xmlStrings->si)) {
492 14
                        foreach ($xmlStrings->si as $val) {
493 3
                            if (isset($val->t)) {
494 14
                                $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
495
                            } elseif (isset($val->r)) {
496
                                $sharedStrings[] = $this->parseRichText($val);
497
                            }
498
                        }
499 29
                    }
500 29
501 29
                    $worksheets = [];
502 29
                    $macros = $customUI = null;
503 29
                    foreach ($relsWorkbook->Relationship as $ele) {
504 29
                        switch ($ele['Type']) {
505
                            case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet':
506 29
                                $worksheets[(string) $ele['Id']] = $ele['Target'];
507
508 29
                                break;
509
                            // a vbaProject ? (: some macros)
510
                            case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject':
511 29
                                $macros = $ele['Target'];
512
513
                                break;
514
                        }
515 29
                    }
516
517
                    if ($macros !== null) {
518
                        $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin
519
                        if ($macrosCode !== false) {
520
                            $excel->setMacrosCode($macrosCode);
521
                            $excel->setHasMacros(true);
522
                            //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir
523
                            $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin');
524
                            if ($Certificate !== false) {
525
                                $excel->setMacrosCertificate($Certificate);
526
                            }
527 29
                        }
528 29
                    }
529 29
                    $styles = [];
530 29
                    $cellStyles = [];
531
                    $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
532 29
                    $xmlStyles = simplexml_load_string(
533 29
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
534 29
                        $this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
535
                        'SimpleXMLElement',
536 29
                        Settings::getLibXmlLoaderOptions()
537 29
                    );
538 23
                    $numFmts = null;
539
                    if ($xmlStyles && $xmlStyles->numFmts[0]) {
540 29
                        $numFmts = $xmlStyles->numFmts[0];
541 23
                    }
542
                    if (isset($numFmts) && ($numFmts !== null)) {
543 29
                        $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
544 29
                    }
545 29
                    if (!$this->readDataOnly && $xmlStyles) {
546
                        foreach ($xmlStyles->cellXfs->xf as $xf) {
547 29
                            $numFmt = NumberFormat::FORMAT_GENERAL;
548 29
549 23
                            if ($xf['numFmtId']) {
550
                                if (isset($numFmts)) {
551 23
                                    $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
552 3
553
                                    if (isset($tmpNumFmt['formatCode'])) {
554
                                        $numFmt = (string) $tmpNumFmt['formatCode'];
555
                                    }
556
                                }
557
558
                                // We shouldn't override any of the built-in MS Excel values (values below id 164)
559 29
                                //  But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used
560 29
                                //  So we make allowance for them rather than lose formatting masks
561 29
                                if ((int) $xf['numFmtId'] < 164 &&
562
                                    NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '') {
563
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
564 29
                                }
565 29
                            }
566
                            $quotePrefix = false;
567
                            if (isset($xf['quotePrefix'])) {
568
                                $quotePrefix = (bool) $xf['quotePrefix'];
569
                            }
570 29
571 29
                            $style = (object) [
572 29
                                'numFmt' => $numFmt,
573 29
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
574 29
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
575 29
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
576 29
                                'alignment' => $xf->alignment,
577
                                'protection' => $xf->protection,
578 29
                                'quotePrefix' => $quotePrefix,
579
                            ];
580
                            $styles[] = $style;
581 29
582 29
                            // add style to cellXf collection
583 29
                            $objStyle = new Style();
584
                            self::readStyle($objStyle, $style);
585
                            $excel->addCellXf($objStyle);
586 29
                        }
587 29
588 29
                        foreach ($xmlStyles->cellStyleXfs->xf as $xf) {
589 23
                            $numFmt = NumberFormat::FORMAT_GENERAL;
590 23
                            if ($numFmts && $xf['numFmtId']) {
591 1
                                $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
592 23
                                if (isset($tmpNumFmt['formatCode'])) {
593 23
                                    $numFmt = (string) $tmpNumFmt['formatCode'];
594
                                } elseif ((int) $xf['numFmtId'] < 165) {
595
                                    $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
596
                                }
597
                            }
598 29
599 29
                            $cellStyle = (object) [
600 29
                                'numFmt' => $numFmt,
601 29
                                'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
602 29
                                'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
603 29
                                'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
604 29
                                'alignment' => $xf->alignment,
605
                                'protection' => $xf->protection,
606 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...
607
                            ];
608
                            $cellStyles[] = $cellStyle;
609 29
610 29
                            // add style to cellStyleXf collection
611 29
                            $objStyle = new Style();
612
                            self::readStyle($objStyle, $cellStyle);
613
                            $excel->addCellStyleXf($objStyle);
614
                        }
615 29
                    }
616 29
617
                    $dxfs = [];
618 29
                    if (!$this->readDataOnly && $xmlStyles) {
619 29
                        //    Conditional Styles
620 1
                        if ($xmlStyles->dxfs) {
621 1
                            foreach ($xmlStyles->dxfs->dxf as $dxf) {
622 1
                                $style = new Style(false, true);
623
                                self::readStyle($style, $dxf);
624
                                $dxfs[] = $style;
625
                            }
626 29
                        }
627 29
                        //    Cell Styles
628 29
                        if ($xmlStyles->cellStyles) {
629 29
                            foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) {
630
                                if ((int) ($cellStyle['builtinId']) == 0) {
631 29
                                    if (isset($cellStyles[(int) ($cellStyle['xfId'])])) {
632 29
                                        // Set default style
633
                                        $style = new Style();
634
                                        self::readStyle($style, $cellStyles[(int) ($cellStyle['xfId'])]);
635
636
                                        // normal style, currently not using it for anything
637
                                    }
638
                                }
639
                            }
640
                        }
641 29
                    }
642
643 29
                    $xmlWorkbook = simplexml_load_string(
644 29
                    //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
645 29
                        $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")),
646
                        'SimpleXMLElement',
647
                        Settings::getLibXmlLoaderOptions()
648
                    );
649 29
650 28
                    // Set base date
651 28
                    if ($xmlWorkbook->workbookPr) {
652
                        Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
653
                        if (isset($xmlWorkbook->workbookPr['date1904'])) {
654
                            if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) {
655
                                Date::setExcelCalendar(Date::CALENDAR_MAC_1904);
656
                            }
657
                        }
658 29
                    }
659 29
660 29
                    // Set protection
661 29
                    $this->readProtection($excel, $xmlWorkbook);
1 ignored issue
show
Bug introduced by
It seems like $xmlWorkbook can also be of type false; however, parameter $xmlWorkbook of PhpOffice\PhpSpreadsheet...\Xlsx::readProtection() does only seem to accept SimpleXMLElement, maybe add an additional type check? ( Ignorable by Annotation )

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

661
                    $this->readProtection($excel, /** @scrutinizer ignore-type */ $xmlWorkbook);
Loading history...
662
663 29
                    $sheetId = 0; // keep track of new sheet id in final workbook
664
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
665 29
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
666
                    $mapSheetId = []; // mapping of sheet ids from old to new
667 29
668 29
                    $charts = $chartDetails = [];
669
670
                    if ($xmlWorkbook->sheets) {
671 29
                        /** @var SimpleXMLElement $eleSheet */
672 1
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
673 1
                            ++$oldSheetId;
674
675 1
                            // Check if sheet should be skipped
676
                            if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) {
677
                                ++$countSkippedSheets;
678
                                $mapSheetId[$oldSheetId] = null;
679
680 29
                                continue;
681
                            }
682
683 29
                            // Map old sheet id in original workbook to new sheet id.
684
                            // They will differ if loadSheetsOnly() is being used
685
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
686
687
                            // Load sheet
688 29
                            $docSheet = $excel->createSheet();
689 29
                            //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet
690 29
                            //        references in formula cells... during the load, all formulae should be correct,
691
                            //        and we're simply bringing the worksheet name in line with the formula, not the
692 29
                            //        reverse
693 29
                            $docSheet->setTitle((string) $eleSheet['name'], false, false);
694 29
                            $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
695
                            $xmlSheet = simplexml_load_string(
696
                            //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
697 29
                                $this->securityScan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")),
698
                                'SimpleXMLElement',
699 29
                                Settings::getLibXmlLoaderOptions()
700
                            );
701
702
                            $sharedFormulas = [];
703 29
704 29
                            if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') {
705
                                $docSheet->setSheetState((string) $eleSheet['state']);
706
                            }
707
708
                            if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) {
709
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) {
710
                                    $zoomScale = (int) ($xmlSheet->sheetViews->sheetView['zoomScale']);
711
                                    if ($zoomScale <= 0) {
712
                                        // setZoomScale will throw an Exception if the scale is less than or equals 0
713
                                        // that is OK when manually creating documents, but we should be able to read all documents
714 29
                                        $zoomScale = 100;
715
                                    }
716
717
                                    $docSheet->getSheetView()->setZoomScale($zoomScale);
718
                                }
719
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) {
720
                                    $zoomScaleNormal = (int) ($xmlSheet->sheetViews->sheetView['zoomScaleNormal']);
721
                                    if ($zoomScaleNormal <= 0) {
722
                                        // setZoomScaleNormal will throw an Exception if the scale is less than or equals 0
723
                                        // that is OK when manually creating documents, but we should be able to read all documents
724 29
                                        $zoomScaleNormal = 100;
725
                                    }
726
727 29
                                    $docSheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal);
728 22
                                }
729
                                if (isset($xmlSheet->sheetViews->sheetView['view'])) {
730 29
                                    $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']);
731 22
                                }
732
                                if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
733 29
                                    $docSheet->setShowGridLines(self::boolean((string) $xmlSheet->sheetViews->sheetView['showGridLines']));
734
                                }
735
                                if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
736 29
                                    $docSheet->setShowRowColHeaders(self::boolean((string) $xmlSheet->sheetViews->sheetView['showRowColHeaders']));
737 2
                                }
738 2
                                if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
739 2
                                    $docSheet->setRightToLeft(self::boolean((string) $xmlSheet->sheetViews->sheetView['rightToLeft']));
740
                                }
741 2
                                if (isset($xmlSheet->sheetViews->sheetView->pane)) {
742 1
                                    $xSplit = 0;
743
                                    $ySplit = 0;
744
                                    $topLeftCell = null;
745 2
746 2
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
747
                                        $xSplit = (int) ($xmlSheet->sheetViews->sheetView->pane['xSplit']);
748
                                    }
749 2
750 2
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
751
                                        $ySplit = (int) ($xmlSheet->sheetViews->sheetView->pane['ySplit']);
752
                                    }
753 2
754
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
755
                                        $topLeftCell = (string) $xmlSheet->sheetViews->sheetView->pane['topLeftCell'];
756 29
                                    }
757 27
758 26
                                    $docSheet->freezePane(Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1), $topLeftCell);
759 26
                                }
760 26
761 26
                                if (isset($xmlSheet->sheetViews->sheetView->selection)) {
762
                                    if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
763
                                        $sqref = (string) $xmlSheet->sheetViews->sheetView->selection['sqref'];
764
                                        $sqref = explode(' ', $sqref);
765
                                        $sqref = $sqref[0];
766 29
                                        $docSheet->setSelectedCells($sqref);
767 2
                                    }
768 2
                                }
769
                            }
770
771 29
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->tabColor)) {
772
                                if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
773
                                    $docSheet->getTabColor()->setARGB((string) $xmlSheet->sheetPr->tabColor['rgb']);
774 29
                                }
775 22
                            }
776 22
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr['codeName'])) {
777
                                $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName'], false);
778
                            }
779 22
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->outlinePr)) {
780
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) &&
781
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) {
782 22
                                    $docSheet->setShowSummaryRight(false);
783 22
                                } else {
784
                                    $docSheet->setShowSummaryRight(true);
785
                                }
786 22
787
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) &&
788
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) {
789
                                    $docSheet->setShowSummaryBelow(false);
790 29
                                } else {
791
                                    $docSheet->setShowSummaryBelow(true);
792
                                }
793
                            }
794
795
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->pageSetUpPr)) {
796
                                if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) &&
797
                                    !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) {
798
                                    $docSheet->getPageSetup()->setFitToPage(false);
799 29
                                } else {
800 29
                                    $docSheet->getPageSetup()->setFitToPage(true);
801 29
                                }
802 29
                            }
803 1
804
                            if (isset($xmlSheet->sheetFormatPr)) {
805 29
                                if (isset($xmlSheet->sheetFormatPr['customHeight']) &&
806 1
                                    self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) &&
807
                                    isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
808 29
                                    $docSheet->getDefaultRowDimension()->setRowHeight((float) $xmlSheet->sheetFormatPr['defaultRowHeight']);
809 29
                                }
810
                                if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
811
                                    $docSheet->getDefaultColumnDimension()->setWidth((float) $xmlSheet->sheetFormatPr['defaultColWidth']);
812
                                }
813
                                if (isset($xmlSheet->sheetFormatPr['zeroHeight']) &&
814 29
                                    ((string) $xmlSheet->sheetFormatPr['zeroHeight'] == '1')) {
815 7
                                    $docSheet->getDefaultRowDimension()->setZeroHeight(true);
816 7
                                }
817 7
                            }
818 3
819
                            if (isset($xmlSheet->cols) && !$this->readDataOnly) {
820 7
                                foreach ($xmlSheet->cols->col as $col) {
821 1
                                    for ($i = (int) ($col['min']); $i <= (int) ($col['max']); ++$i) {
822
                                        if ($col['style'] && !$this->readDataOnly) {
823 7
                                            $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setXfIndex((int) ($col['style']));
824 1
                                        }
825
                                        if (self::boolean($col['hidden'])) {
826 7
                                            $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setVisible(false);
827 1
                                        }
828
                                        if (self::boolean($col['collapsed'])) {
829 7
                                            $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setCollapsed(true);
830
                                        }
831 7
                                        if ($col['outlineLevel'] > 0) {
832
                                            $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setOutlineLevel((int) ($col['outlineLevel']));
833
                                        }
834
                                        $docSheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setWidth((float) ($col['width']));
835
836
                                        if ((int) ($col['max']) == 16384) {
837
                                            break;
838 29
                                        }
839 22
                                    }
840 22
                                }
841
                            }
842 22
843
                            if (isset($xmlSheet->printOptions) && !$this->readDataOnly) {
844
                                if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) {
845 22
                                    $docSheet->setShowGridlines(true);
846
                                }
847
                                if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) {
848 22
                                    $docSheet->setPrintGridlines(true);
849
                                }
850
                                if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) {
851
                                    $docSheet->getPageSetup()->setHorizontalCentered(true);
852
                                }
853 29
                                if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) {
854 24
                                    $docSheet->getPageSetup()->setVerticalCentered(true);
855 24
                                }
856 24
                            }
857 2
858
                            if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
859 24
                                $cIndex = 1; // Cell Start from 1
860
                                foreach ($xmlSheet->sheetData->row as $row) {
861
                                    if ($row['ht'] && !$this->readDataOnly) {
862 24
                                        $docSheet->getRowDimension((int) ($row['r']))->setRowHeight((float) ($row['ht']));
863
                                    }
864
                                    if (self::boolean($row['hidden']) && !$this->readDataOnly) {
865 24
                                        $docSheet->getRowDimension((int) ($row['r']))->setVisible(false);
866
                                    }
867
                                    if (self::boolean($row['collapsed'])) {
868 24
                                        $docSheet->getRowDimension((int) ($row['r']))->setCollapsed(true);
869
                                    }
870
                                    if ($row['outlineLevel'] > 0) {
871
                                        $docSheet->getRowDimension((int) ($row['r']))->setOutlineLevel((int) ($row['outlineLevel']));
872 24
                                    }
873 24
                                    if ($row['s'] && !$this->readDataOnly) {
874 24
                                        $docSheet->getRowDimension((int) ($row['r']))->setXfIndex((int) ($row['s']));
875 24
                                    }
876 1
877
                                    $rowIndex = 1;
878 24
                                    foreach ($row->c as $c) {
879 24
                                        $r = (string) $c['r'];
880 24
                                        if ($r == '') {
881
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
882
                                        }
883 24
                                        $cellDataType = (string) $c['t'];
884 24
                                        $value = null;
885
                                        $calculatedValue = null;
886 24
887 1
                                        // Read cell?
888
                                        if ($this->getReadFilter() !== null) {
889
                                            $coordinates = Coordinate::coordinateFromString($r);
890
891
                                            if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) {
892
                                                continue;
893 24
                                            }
894 14
                                        }
895 14
896
                                        // Read cell!
897 14
                                        switch ($cellDataType) {
898 14
                                            case 's':
899
                                                if ((string) $c->v != '') {
900
                                                    $value = $sharedStrings[(int) ($c->v)];
901
902
                                                    if ($value instanceof RichText) {
903
                                                        $value = clone $value;
904 14
                                                    }
905 17
                                                } else {
906 4
                                                    $value = '';
907 2
                                                }
908
909
                                                break;
910 2
                                            case 'b':
911 2
                                                if (!isset($c->f)) {
912
                                                    $value = self::castToBoolean($c);
913
                                                } else {
914
                                                    // Formula
915
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean');
916
                                                    if (isset($c->f['t'])) {
917 4
                                                        $att = $c->f;
918 14
                                                        $docSheet->getCell($r)->setFormulaAttributes($att);
919 2
                                                    }
920
                                                }
921
922 2
                                                break;
923
                                            case 'inlineStr':
924
                                                if (isset($c->f)) {
925 2
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
926 14
                                                } else {
927
                                                    $value = $this->parseRichText($c->is);
928
                                                }
929
930
                                                break;
931
                                            case 'e':
932
                                                if (!isset($c->f)) {
933
                                                    $value = self::castToError($c);
934
                                                } else {
935
                                                    // Formula
936 14
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
937 12
                                                }
938
939
                                                break;
940 6
                                            default:
941
                                                if (!isset($c->f)) {
942
                                                    $value = self::castToString($c);
943 14
                                                } else {
944
                                                    // Formula
945
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
946
                                                }
947 24
948 12
                                                break;
949 11
                                        }
950 1
951 1
                                        // Check for numeric values
952
                                        if (is_numeric($value) && $cellDataType != 's') {
953
                                            if ($value == (int) $value) {
954
                                                $value = (int) $value;
955
                                            } elseif ($value == (float) $value) {
956
                                                $value = (float) $value;
957
                                            } elseif ($value == (float) $value) {
958 24
                                                $value = (float) $value;
959
                                            }
960
                                        }
961
962 24
                                        // Rich text?
963
                                        if ($value instanceof RichText && $this->readDataOnly) {
964 24
                                            $value = $value->getPlainText();
965 18
                                        }
966
967 12
                                        $cell = $docSheet->getCell($r);
968
                                        // Assign value
969 24
                                        if ($cellDataType != '') {
970 7
                                            $cell->setValueExplicit($value, $cellDataType);
971
                                        } else {
972
                                            $cell->setValue($value);
973
                                        }
974 24
                                        if ($calculatedValue !== null) {
975
                                            $cell->setCalculatedValue($calculatedValue);
976 7
                                        }
977 7
978
                                        // Style information?
979 24
                                        if ($c['s'] && !$this->readDataOnly) {
980
                                            // no style index means 0, it seems
981 24
                                            $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
982
                                                (int) ($c['s']) : 0);
983
                                        }
984
                                        $rowIndex += 1;
985 29
                                    }
986 29
                                    $cIndex += 1;
987 1
                                }
988 1
                            }
989 1
990 1
                            $conditionals = [];
991
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
992
                                foreach ($xmlSheet->conditionalFormatting as $conditional) {
993
                                    foreach ($conditional->cfRule as $cfRule) {
994
                                        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'])])) {
995 1
                                            $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
996 1
                                        }
997 1
                                    }
998 1
                                }
999 1
1000 1
                                foreach ($conditionals as $ref => $cfRules) {
1001 1
                                    ksort($cfRules);
1002
                                    $conditionalStyles = [];
1003 1
                                    foreach ($cfRules as $cfRule) {
1004
                                        $objConditional = new Conditional();
1005
                                        $objConditional->setConditionType((string) $cfRule['type']);
1006
                                        $objConditional->setOperatorType((string) $cfRule['operator']);
1007 1
1008 1
                                        if ((string) $cfRule['text'] != '') {
1009
                                            $objConditional->setText((string) $cfRule['text']);
1010
                                        }
1011 1
1012
                                        if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
1013
                                            $objConditional->setStopIfTrue(true);
1014
                                        }
1015
1016 1
                                        if (count($cfRule->formula) > 1) {
1017
                                            foreach ($cfRule->formula as $formula) {
1018 1
                                                $objConditional->addCondition((string) $formula);
1019 1
                                            }
1020
                                        } else {
1021
                                            $objConditional->addCondition((string) $cfRule->formula);
1022
                                        }
1023 1
                                        $objConditional->setStyle(clone $dxfs[(int) ($cfRule['dxfId'])]);
1024 1
                                        $conditionalStyles[] = $objConditional;
1025 1
                                    }
1026
1027
                                    // Extract all cell references in $ref
1028
                                    $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
1029
                                    foreach ($cellBlocks as $cellBlock) {
1030 29
                                        $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
1031 29
                                    }
1032 24
                                }
1033 24
                            }
1034 24
1035
                            $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
1036
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1037
                                foreach ($aKeys as $key) {
1038 29
                                    $method = 'set' . ucfirst($key);
1039 24
                                    $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
1040 24
                                }
1041 2
                            }
1042 2
1043
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1044
                                $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true);
1045
                                if ($xmlSheet->protectedRanges->protectedRange) {
1046
                                    foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
1047 29
                                        $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
1048
                                    }
1049
                                }
1050
                            }
1051
1052
                            if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
1053
                                $autoFilterRange = (string) $xmlSheet->autoFilter['ref'];
1054
                                if (strpos($autoFilterRange, ':') !== false) {
1055
                                    $autoFilter = $docSheet->getAutoFilter();
1056
                                    $autoFilter->setRange($autoFilterRange);
1057
1058
                                    foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
1059
                                        $column = $autoFilter->getColumnByOffset((int) $filterColumn['colId']);
1060
                                        //    Check for standard filters
1061
                                        if ($filterColumn->filters) {
1062
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
1063
                                            $filters = $filterColumn->filters;
1064
                                            if ((isset($filters['blank'])) && ($filters['blank'] == 1)) {
1065
                                                //    Operator is undefined, but always treated as EQUAL
1066
                                                $column->createRule()->setRule(null, '')->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1067
                                            }
1068
                                            //    Standard filters are always an OR join, so no join rule needs to be set
1069
                                            //    Entries can be either filter elements
1070
                                            foreach ($filters->filter as $filterRule) {
1071
                                                //    Operator is undefined, but always treated as EQUAL
1072
                                                $column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1073
                                            }
1074
                                            //    Or Date Group elements
1075
                                            foreach ($filters->dateGroupItem as $dateGroupItem) {
1076
                                                $column->createRule()->setRule(
1077
                                                //    Operator is undefined, but always treated as EQUAL
1078
                                                    null,
1079
                                                    [
1080
                                                        'year' => (string) $dateGroupItem['year'],
1081
                                                        'month' => (string) $dateGroupItem['month'],
1082
                                                        'day' => (string) $dateGroupItem['day'],
1083
                                                        'hour' => (string) $dateGroupItem['hour'],
1084
                                                        'minute' => (string) $dateGroupItem['minute'],
1085
                                                        'second' => (string) $dateGroupItem['second'],
1086
                                                    ],
1087
                                                    (string) $dateGroupItem['dateTimeGrouping']
1088
                                                )
1089
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP);
1090
                                            }
1091
                                        }
1092
                                        //    Check for custom filters
1093
                                        if ($filterColumn->customFilters) {
1094
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
1095
                                            $customFilters = $filterColumn->customFilters;
1096
                                            //    Custom filters can an AND or an OR join;
1097
                                            //        and there should only ever be one or two entries
1098
                                            if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
1099
                                                $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
1100
                                            }
1101
                                            foreach ($customFilters->customFilter as $filterRule) {
1102
                                                $column->createRule()->setRule(
1103
                                                    (string) $filterRule['operator'],
1104
                                                    (string) $filterRule['val']
1105
                                                )
1106
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
1107
                                            }
1108
                                        }
1109
                                        //    Check for dynamic filters
1110
                                        if ($filterColumn->dynamicFilter) {
1111
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
1112
                                            //    We should only ever have one dynamic filter
1113
                                            foreach ($filterColumn->dynamicFilter as $filterRule) {
1114
                                                $column->createRule()->setRule(
1115
                                                //    Operator is undefined, but always treated as EQUAL
1116
                                                    null,
1117
                                                    (string) $filterRule['val'],
1118
                                                    (string) $filterRule['type']
1119
                                                )
1120
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
1121
                                                if (isset($filterRule['val'])) {
1122
                                                    $column->setAttribute('val', (string) $filterRule['val']);
1123
                                                }
1124
                                                if (isset($filterRule['maxVal'])) {
1125
                                                    $column->setAttribute('maxVal', (string) $filterRule['maxVal']);
1126
                                                }
1127
                                            }
1128
                                        }
1129
                                        //    Check for dynamic filters
1130
                                        if ($filterColumn->top10) {
1131
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
1132
                                            //    We should only ever have one top10 filter
1133
                                            foreach ($filterColumn->top10 as $filterRule) {
1134
                                                $column->createRule()->setRule(
1135
                                                    (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
1136
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
1137
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
1138
                                                    ),
1139
                                                    (string) $filterRule['val'],
1140
                                                    (((isset($filterRule['top'])) && ($filterRule['top'] == 1))
1141
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
1142
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
1143
                                                    )
1144
                                                )
1145
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
1146
                                            }
1147 29
                                        }
1148 6
                                    }
1149 6
                                }
1150 6
                            }
1151 6
1152
                            if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
1153
                                foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
1154
                                    $mergeRef = (string) $mergeCell['ref'];
1155
                                    if (strpos($mergeRef, ':') !== false) {
1156 29
                                        $docSheet->mergeCells((string) $mergeCell['ref']);
1157 28
                                    }
1158 28
                                }
1159 28
                            }
1160 28
1161 28
                            if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) {
1162 28
                                $docPageMargins = $docSheet->getPageMargins();
1163 28
                                $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
1164
                                $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
1165
                                $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
1166 29
                                $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
1167 28
                                $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
1168
                                $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
1169 28
                            }
1170 28
1171
                            if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) {
1172 28
                                $docPageSetup = $docSheet->getPageSetup();
1173 26
1174
                                if (isset($xmlSheet->pageSetup['orientation'])) {
1175 28
                                    $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
1176 22
                                }
1177
                                if (isset($xmlSheet->pageSetup['paperSize'])) {
1178 28
                                    $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
1179 22
                                }
1180
                                if (isset($xmlSheet->pageSetup['scale'])) {
1181 28
                                    $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
1182 22
                                }
1183
                                if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
1184 28
                                    $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
1185 28
                                }
1186
                                if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
1187
                                    $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
1188
                                }
1189
                                if (isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) &&
1190 29
                                    self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) {
1191 24
                                    $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
1192
                                }
1193 24
1194 24
                                $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1195
                                if (isset($relAttributes['id'])) {
1196
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id'];
1197 24
                                }
1198
                            }
1199 24
1200 24
                            if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) {
1201
                                $docHeaderFooter = $docSheet->getHeaderFooter();
1202
1203 24
                                if (isset($xmlSheet->headerFooter['differentOddEven']) &&
1204
                                    self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) {
1205 24
                                    $docHeaderFooter->setDifferentOddEven(true);
1206 24
                                } else {
1207
                                    $docHeaderFooter->setDifferentOddEven(false);
1208
                                }
1209 24
                                if (isset($xmlSheet->headerFooter['differentFirst']) &&
1210
                                    self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) {
1211 24
                                    $docHeaderFooter->setDifferentFirst(true);
1212 24
                                } else {
1213 3
                                    $docHeaderFooter->setDifferentFirst(false);
1214
                                }
1215 21
                                if (isset($xmlSheet->headerFooter['scaleWithDoc']) &&
1216
                                    !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) {
1217
                                    $docHeaderFooter->setScaleWithDocument(false);
1218 24
                                } else {
1219 24
                                    $docHeaderFooter->setScaleWithDocument(true);
1220 24
                                }
1221 24
                                if (isset($xmlSheet->headerFooter['alignWithMargins']) &&
1222 24
                                    !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) {
1223 24
                                    $docHeaderFooter->setAlignWithMargins(false);
1224
                                } else {
1225
                                    $docHeaderFooter->setAlignWithMargins(true);
1226 29
                                }
1227
1228
                                $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
1229
                                $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
1230
                                $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
1231
                                $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
1232
                                $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
1233 29
                                $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
1234
                            }
1235
1236
                            if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) {
1237
                                foreach ($xmlSheet->rowBreaks->brk as $brk) {
1238
                                    if ($brk['man']) {
1239
                                        $docSheet->setBreak("A$brk[id]", Worksheet::BREAK_ROW);
1240
                                    }
1241 29
                                }
1242
                            }
1243
                            if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) {
1244
                                foreach ($xmlSheet->colBreaks->brk as $brk) {
1245
                                    if ($brk['man']) {
1246
                                        $docSheet->setBreak(Coordinate::stringFromColumnIndex((string) $brk['id'] + 1) . '1', Worksheet::BREAK_COLUMN);
1247
                                    }
1248
                                }
1249
                            }
1250
1251
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
1252
                                foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
1253
                                    // Uppercase coordinate
1254
                                    $range = strtoupper($dataValidation['sqref']);
1255
                                    $rangeSet = explode(' ', $range);
1256
                                    foreach ($rangeSet as $range) {
1257
                                        $stRange = $docSheet->shrinkRangeToFit($range);
1258
1259
                                        // Extract all cell references in $range
1260
                                        foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) {
1261
                                            // Create validation
1262
                                            $docValidation = $docSheet->getCell($reference)->getDataValidation();
1263
                                            $docValidation->setType((string) $dataValidation['type']);
1264
                                            $docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
1265
                                            $docValidation->setOperator((string) $dataValidation['operator']);
1266
                                            $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
1267
                                            $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
1268
                                            $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
1269
                                            $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
1270
                                            $docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
1271
                                            $docValidation->setError((string) $dataValidation['error']);
1272 29
                                            $docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
1273 29
                                            $docValidation->setPrompt((string) $dataValidation['prompt']);
1274
                                            $docValidation->setFormula1((string) $dataValidation->formula1);
1275 29
                                            $docValidation->setFormula2((string) $dataValidation->formula2);
1276 28
                                        }
1277
                                    }
1278 28
                                }
1279 28
                            }
1280
1281 28
                            // unparsed sheet AlternateContent
1282 28
                            if ($xmlSheet && !$this->readDataOnly) {
1283
                                $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
1284 28
                                if ($mc->AlternateContent) {
1285 8
                                    foreach ($mc->AlternateContent as $alternateContent) {
1286 8
                                        $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
1287
                                    }
1288
                                }
1289
                            }
1290
1291
                            // Add hyperlinks
1292 29
                            $hyperlinks = [];
1293
                            if (!$this->readDataOnly) {
1294 2
                                // Locate hyperlink relations
1295
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1296 2
                                    $relsWorksheet = simplexml_load_string(
1297
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1298 2
                                        $this->securityScan(
1299 2
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1300 2
                                        ),
1301 2
                                        'SimpleXMLElement',
1302 2
                                        Settings::getLibXmlLoaderOptions()
1303
                                    );
1304
                                    foreach ($relsWorksheet->Relationship as $ele) {
1305 2
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1306 2
                                            $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1307 2
                                        }
1308
                                    }
1309
                                }
1310
1311 2
                                // Loop through hyperlinks
1312 2
                                if ($xmlSheet && $xmlSheet->hyperlinks) {
1313
                                    /** @var SimpleXMLElement $hyperlink */
1314
                                    foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
1315
                                        // Link url
1316
                                        $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1317
1318
                                        foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
1319
                                            $cell = $docSheet->getCell($cellReference);
1320 29
                                            if (isset($linkRel['id'])) {
1321 29
                                                $hyperlinkUrl = $hyperlinks[(string) $linkRel['id']];
1322 29
                                                if (isset($hyperlink['location'])) {
1323
                                                    $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
1324 29
                                                }
1325 28
                                                $cell->getHyperlink()->setUrl($hyperlinkUrl);
1326
                                            } elseif (isset($hyperlink['location'])) {
1327 28
                                                $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
1328 28
                                            }
1329
1330 28
                                            // Tooltip
1331 28
                                            if (isset($hyperlink['tooltip'])) {
1332
                                                $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
1333 28
                                            }
1334 8
                                        }
1335 2
                                    }
1336
                                }
1337 8
                            }
1338 8
1339
                            // Add comments
1340
                            $comments = [];
1341
                            $vmlComments = [];
1342
                            if (!$this->readDataOnly) {
1343
                                // Locate comment relations
1344 29
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1345
                                    $relsWorksheet = simplexml_load_string(
1346 2
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1347 2
                                        $this->securityScan(
1348 2
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1349 2
                                        ),
1350 2
                                        'SimpleXMLElement',
1351
                                        Settings::getLibXmlLoaderOptions()
1352
                                    );
1353
                                    foreach ($relsWorksheet->Relationship as $ele) {
1354 2
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
1355
                                            $comments[(string) $ele['Id']] = (string) $ele['Target'];
1356
                                        }
1357 2
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1358 2
                                            $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
1359
                                        }
1360
                                    }
1361
                                }
1362 2
1363 2
                                // Loop through comments
1364
                                foreach ($comments as $relName => $relPath) {
1365
                                    // Load comments file
1366 2
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1367
                                    $commentsFile = simplexml_load_string(
1368
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1369
                                        'SimpleXMLElement',
1370
                                        Settings::getLibXmlLoaderOptions()
1371 29
                                    );
1372
1373 2
                                    // Utility variables
1374 2
                                    $authors = [];
1375 2
1376 2
                                    // Loop through authors
1377 2
                                    foreach ($commentsFile->authors->author as $author) {
1378
                                        $authors[] = (string) $author;
1379 2
                                    }
1380
1381 2
                                    // Loop through contents
1382 2
                                    foreach ($commentsFile->commentList->comment as $comment) {
1383 2
                                        if (!empty($comment['authorId'])) {
1384
                                            $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]);
1385 2
                                        }
1386 2
                                        $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text));
1387 2
                                    }
1388 2
                                }
1389 2
1390
                                // later we will remove from it real vmlComments
1391 2
                                $unparsedVmlDrawings = $vmlComments;
1392 2
1393 2
                                // Loop through VML comments
1394
                                foreach ($vmlComments as $relName => $relPath) {
1395 2
                                    // Load VML comments file
1396 2
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1397 2
                                    $vmlCommentsFile = simplexml_load_string(
1398 2
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1399
                                        'SimpleXMLElement',
1400
                                        Settings::getLibXmlLoaderOptions()
1401 2
                                    );
1402 2
                                    $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1403 2
1404
                                    $shapes = $vmlCommentsFile->xpath('//v:shape');
1405
                                    foreach ($shapes as $shape) {
1406
                                        $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1407
1408 2
                                        if (isset($shape['style'])) {
1409
                                            $style = (string) $shape['style'];
1410 2
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
1411 2
                                            $column = null;
1412
                                            $row = null;
1413
1414 2
                                            $clientData = $shape->xpath('.//x:ClientData');
1415 2
                                            if (is_array($clientData) && !empty($clientData)) {
1416 2
                                                $clientData = $clientData[0];
1417
1418 2
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
1419 2
                                                    $temp = $clientData->xpath('.//x:Row');
1420
                                                    if (is_array($temp)) {
1421 2
                                                        $row = $temp[0];
1422 2
                                                    }
1423
1424 2
                                                    $temp = $clientData->xpath('.//x:Column');
1425 2
                                                    if (is_array($temp)) {
1426
                                                        $column = $temp[0];
1427 2
                                                    }
1428 2
                                                }
1429
                                            }
1430 2
1431 2
                                            if (($column !== null) && ($row !== null)) {
1432
                                                // Set comment properties
1433
                                                $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

1433
                                                $comment = $docSheet->getCommentByColumnAndRow(/** @scrutinizer ignore-type */ (string) $column, $row + 1);
Loading history...
1434
                                                $comment->getFillColor()->setRGB($fillColor);
1435
1436
                                                // Parse style
1437
                                                $styleArray = explode(';', str_replace(' ', '', $style));
1438
                                                foreach ($styleArray as $stylePair) {
1439
                                                    $stylePair = explode(':', $stylePair);
1440 29
1441
                                                    if ($stylePair[0] == 'margin-left') {
1442
                                                        $comment->setMarginLeft($stylePair[1]);
1443
                                                    }
1444
                                                    if ($stylePair[0] == 'margin-top') {
1445
                                                        $comment->setMarginTop($stylePair[1]);
1446
                                                    }
1447
                                                    if ($stylePair[0] == 'width') {
1448
                                                        $comment->setWidth($stylePair[1]);
1449
                                                    }
1450
                                                    if ($stylePair[0] == 'height') {
1451
                                                        $comment->setHeight($stylePair[1]);
1452
                                                    }
1453
                                                    if ($stylePair[0] == 'visibility') {
1454
                                                        $comment->setVisible($stylePair[1] == 'visible');
1455
                                                    }
1456
                                                }
1457
1458
                                                unset($unparsedVmlDrawings[$relName]);
1459
                                            }
1460
                                        }
1461
                                    }
1462
                                }
1463
1464
                                // unparsed vmlDrawing
1465
                                if ($unparsedVmlDrawings) {
1466
                                    foreach ($unparsedVmlDrawings as $rId => $relPath) {
1467
                                        $rId = substr($rId, 3);  // rIdXXX
1468
                                        $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
1469
                                        $unparsedVmlDrawing[$rId] = [];
1470
                                        $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
1471
                                        $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
1472
                                        $unparsedVmlDrawing[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
1473
                                        unset($unparsedVmlDrawing);
1474
                                    }
1475
                                }
1476
1477
                                // Header/footer images
1478
                                if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
1479
                                    if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1480
                                        $relsWorksheet = simplexml_load_string(
1481
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1482
                                            $this->securityScan(
1483
                                                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1484
                                            ),
1485
                                            'SimpleXMLElement',
1486
                                            Settings::getLibXmlLoaderOptions()
1487
                                        );
1488
                                        $vmlRelationship = '';
1489
1490
                                        foreach ($relsWorksheet->Relationship as $ele) {
1491
                                            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1492
                                                $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1493
                                            }
1494
                                        }
1495
1496
                                        if ($vmlRelationship != '') {
1497
                                            // Fetch linked images
1498
                                            $relsVML = simplexml_load_string(
1499
                                            //~ http://schemas.openxmlformats.org/package/2006/relationships"
1500
                                                $this->securityScan(
1501
                                                    $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
1502
                                                ),
1503
                                                'SimpleXMLElement',
1504
                                                Settings::getLibXmlLoaderOptions()
1505
                                            );
1506
                                            $drawings = [];
1507
                                            foreach ($relsVML->Relationship as $ele) {
1508
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1509
                                                    $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
1510
                                                }
1511
                                            }
1512
1513
                                            // Fetch VML document
1514
                                            $vmlDrawing = simplexml_load_string(
1515
                                                $this->securityScan($this->getFromZipArchive($zip, $vmlRelationship)),
1516
                                                'SimpleXMLElement',
1517
                                                Settings::getLibXmlLoaderOptions()
1518
                                            );
1519
                                            $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1520
1521
                                            $hfImages = [];
1522 29
1523 28
                                            $shapes = $vmlDrawing->xpath('//v:shape');
1524
                                            foreach ($shapes as $idx => $shape) {
1525 28
                                                $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1526 28
                                                $imageData = $shape->xpath('//v:imagedata');
1527
1528 28
                                                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...
1529 28
                                                    continue;
1530
                                                }
1531 28
1532 28
                                                $imageData = $imageData[$idx];
1533 8
1534 8
                                                $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
1535
                                                $style = self::toCSSArray((string) $shape['style']);
1536
1537 28
                                                $hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
1538 4
                                                if (isset($imageData['title'])) {
1539 4
                                                    $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
1540 4
                                                }
1541
1542 4
                                                $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
1543 4
                                                $hfImages[(string) $shape['id']]->setResizeProportional(false);
1544
                                                $hfImages[(string) $shape['id']]->setWidth($style['width']);
1545 4
                                                $hfImages[(string) $shape['id']]->setHeight($style['height']);
1546 4
                                                if (isset($style['margin-left'])) {
1547
                                                    $hfImages[(string) $shape['id']]->setOffsetX($style['margin-left']);
1548 4
                                                }
1549
                                                $hfImages[(string) $shape['id']]->setOffsetY($style['margin-top']);
1550 4
                                                $hfImages[(string) $shape['id']]->setResizeProportional(true);
1551 4
                                            }
1552 4
1553 4
                                            $docSheet->getHeaderFooter()->setImages($hfImages);
1554 2
                                        }
1555 2
                                    }
1556 2
                                }
1557 2
                            }
1558 4
1559
                            // TODO: Autoshapes from twoCellAnchors!
1560
                            if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1561
                                $relsWorksheet = simplexml_load_string(
1562
                                //~ http://schemas.openxmlformats.org/package/2006/relationships"
1563
                                    $this->securityScan(
1564 4
                                        $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1565 4
                                    ),
1566 4
                                    'SimpleXMLElement',
1567 4
                                    Settings::getLibXmlLoaderOptions()
1568 4
                                );
1569
                                $drawings = [];
1570 4
                                foreach ($relsWorksheet->Relationship as $ele) {
1571 2
                                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1572 2
                                        $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1573
                                    }
1574 2
                                }
1575
                                if ($xmlSheet->drawing && !$this->readDataOnly) {
1576 2
                                    foreach ($xmlSheet->drawing as $drawing) {
1577
                                        $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
1578 2
                                        $relsDrawing = simplexml_load_string(
1579 2
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1580 2
                                            $this->securityScan(
1581 2
                                                $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
1582 2
                                            ),
1583 2
                                            'SimpleXMLElement',
1584 2
                                            Settings::getLibXmlLoaderOptions()
1585 2
                                        );
1586 2
                                        $images = [];
1587
1588 2
                                        if ($relsDrawing && $relsDrawing->Relationship) {
1589
                                            foreach ($relsDrawing->Relationship as $ele) {
1590 2
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1591 2
                                                    $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
1592 2
                                                } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
1593 2
                                                    if ($this->includeCharts) {
1594 2
                                                        $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
1595 2
                                                            'id' => (string) $ele['Id'],
1596 2
                                                            'sheet' => $docSheet->getTitle(),
1597 2
                                                        ];
1598
                                                    }
1599 2
                                                }
1600 2
                                            }
1601 2
                                        }
1602 2
                                        $xmlDrawing = simplexml_load_string(
1603 2
                                            $this->securityScan($this->getFromZipArchive($zip, $fileDrawing)),
1604 2
                                            'SimpleXMLElement',
1605 2
                                            Settings::getLibXmlLoaderOptions()
1606 2
                                        )->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
1607 2
1608
                                        if ($xmlDrawing->oneCellAnchor) {
1609 2
                                            foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
1610
                                                if ($oneCellAnchor->pic->blipFill) {
1611
                                                    /** @var SimpleXMLElement $blip */
1612
                                                    $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1613
                                                    /** @var SimpleXMLElement $xfrm */
1614
                                                    $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1615
                                                    /** @var SimpleXMLElement $outerShdw */
1616 2
                                                    $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1617
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1618
                                                    $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1619
                                                    $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1620 4
                                                    $objDrawing->setPath(
1621 2
                                                        'zip://' . File::realpath($pFilename) . '#' .
1622 2
                                                        $images[(string) self::getArrayItem(
1623 2
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1624 2
                                                            'embed'
1625 2
                                                        )],
1626 2
                                                        false
1627 2
                                                    );
1628 2
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
1629 2
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
1630 2
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
1631 2
                                                    $objDrawing->setResizeProportional(false);
1632 2
                                                    $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
1633 2
                                                    $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
1634
                                                    if ($xfrm) {
1635 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

1635
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(/** @scrutinizer ignore-type */ self::getArrayItem($xfrm->attributes(), 'rot')));
Loading history...
1636
                                                    }
1637 2
                                                    if ($outerShdw) {
1638 2
                                                        $shadow = $objDrawing->getShadow();
1639 2
                                                        $shadow->setVisible(true);
1640 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

1640
                                                        $shadow->setBlurRadius(Drawing::EMUTopixels(/** @scrutinizer ignore-type */ self::getArrayItem($outerShdw->attributes(), 'blurRad')));
Loading history...
1641
                                                        $shadow->setDistance(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
1642 2
                                                        $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
1643 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

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

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

1941
                            $objChart = Chart::readChart(/** @scrutinizer ignore-type */ $chartElements, basename($chartEntryRef, '.xml'));
Loading history...
1942 29
1943
                            if (isset($charts[$chartEntryRef])) {
1944
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
1945
                                if (isset($chartDetails[$chartPositionRef])) {
1946
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
1947
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
1948
                                    $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
1949
                                    $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
1950
                                }
1951
                            }
1952
                        }
1953
1954 29
                        break;
1955 29
1956
                    // unparsed
1957 2
                    case 'application/vnd.ms-excel.controlproperties+xml':
1958 2
                        $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
1959 2
1960
                        break;
1961 2
                }
1962 2
            }
1963 2
        }
1964 2
1965 29
        $excel->setUnparsedLoadedData($unparsedLoadedData);
1966 29
1967 29
        $zip->close();
1968 29
1969 4
        return $excel;
1970
    }
1971 29
1972
    private static function readColor($color, $background = false)
1973 29
    {
1974 5
        if (isset($color['rgb'])) {
1975
            return (string) $color['rgb'];
1976
        } elseif (isset($color['indexed'])) {
1977
            return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
1978
        } elseif (isset($color['theme'])) {
1979
            if (self::$theme !== null) {
1980 29
                $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
1981 29
                if (isset($color['tint'])) {
1982 29
                    $tintAdjust = (float) $color['tint'];
1983 29
                    $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
1984 29
                }
1985
1986
                return 'FF' . $returnColour;
1987
            }
1988
        }
1989
1990
        if ($background) {
1991
            return 'FFFFFFFF';
1992 29
        }
1993 29
1994 29
        return 'FF000000';
1995 29
    }
1996 29
1997
    /**
1998
     * @param Style $docStyle
1999
     * @param SimpleXMLElement|\stdClass $style
2000 29
     */
2001 29
    private static function readStyle(Style $docStyle, $style)
2002 29
    {
2003
        $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
2004 29
2005 29
        // font
2006 29
        if (isset($style->font)) {
2007
            $docStyle->getFont()->setName((string) $style->font->name['val']);
2008
            $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

2008
            $docStyle->getFont()->setSize(/** @scrutinizer ignore-type */ (string) $style->font->sz['val']);
Loading history...
2009
            if (isset($style->font->b)) {
2010
                $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val']));
2011 29
            }
2012 29
            if (isset($style->font->i)) {
2013 29
                $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val']));
2014 29
            }
2015 29
            if (isset($style->font->strike)) {
2016
                $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val']));
2017
            }
2018
            $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color));
2019 29
2020 29
            if (isset($style->font->u) && !isset($style->font->u['val'])) {
2021 2
                $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2022
            } elseif (isset($style->font->u, $style->font->u['val'])) {
2023
                $docStyle->getFont()->setUnderline((string) $style->font->u['val']);
2024 2
            }
2025
2026
            if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) {
2027
                $vertAlign = strtolower((string) $style->font->vertAlign['val']);
2028 29
                if ($vertAlign == 'superscript') {
2029
                    $docStyle->getFont()->setSuperscript(true);
2030
                }
2031
                if ($vertAlign == 'subscript') {
2032
                    $docStyle->getFont()->setSubscript(true);
2033
                }
2034
            }
2035
        }
2036
2037
        // fill
2038 29
        if (isset($style->fill)) {
2039 29
            if ($style->fill->gradientFill) {
2040
                /** @var SimpleXMLElement $gradientFill */
2041 29
                $gradientFill = $style->fill->gradientFill[0];
2042
                if (!empty($gradientFill['type'])) {
2043
                    $docStyle->getFill()->setFillType((string) $gradientFill['type']);
2044
                }
2045
                $docStyle->getFill()->setRotation((float) ($gradientFill['degree']));
2046
                $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
2047 29
                $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
2048
                $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
2049 29
            } elseif ($style->fill->patternFill) {
2050 3
                $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid';
2051
                $docStyle->getFill()->setFillType($patternType);
2052 29
                if ($style->fill->patternFill->fgColor) {
2053 3
                    $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true));
2054
                } else {
2055 29
                    $docStyle->getFill()->getStartColor()->setARGB('FF000000');
2056
                }
2057
                if ($style->fill->patternFill->bgColor) {
2058
                    $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true));
2059
                }
2060
            }
2061
        }
2062 3
2063
        // border
2064 3
        if (isset($style->border)) {
2065
            $diagonalUp = self::boolean((string) $style->border['diagonalUp']);
2066 3
            $diagonalDown = self::boolean((string) $style->border['diagonalDown']);
2067
            if (!$diagonalUp && !$diagonalDown) {
2068
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
2069 3
            } elseif ($diagonalUp && !$diagonalDown) {
2070 3
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
2071 3
            } elseif (!$diagonalUp && $diagonalDown) {
2072 3
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
2073
            } else {
2074 3
                $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
2075
            }
2076 3
            self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
2077 3
            self::readBorder($docStyle->getBorders()->getRight(), $style->border->right);
2078
            self::readBorder($docStyle->getBorders()->getTop(), $style->border->top);
2079 3
            self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
2080 3
            self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
2081
        }
2082 3
2083 3
        // alignment
2084
        if (isset($style->alignment)) {
2085 3
            $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']);
2086 3
            $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']);
2087 3
2088
            $textRotation = 0;
2089 3
            if ((int) $style->alignment['textRotation'] <= 90) {
2090 3
                $textRotation = (int) $style->alignment['textRotation'];
2091 2
            } elseif ((int) $style->alignment['textRotation'] > 90) {
2092
                $textRotation = 90 - (int) $style->alignment['textRotation'];
2093 3
            }
2094
2095
            $docStyle->getAlignment()->setTextRotation((int) $textRotation);
2096
            $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText']));
2097
            $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit']));
2098
            $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0);
2099
            $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0);
2100
        }
2101
2102 3
        // protection
2103
        if (isset($style->protection)) {
2104 3
            if (isset($style->protection['locked'])) {
2105 2
                if (self::boolean((string) $style->protection['locked'])) {
2106
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
2107 3
                } else {
2108 3
                    $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
2109 3
                }
2110
            }
2111
2112
            if (isset($style->protection['hidden'])) {
2113
                if (self::boolean((string) $style->protection['hidden'])) {
2114
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
2115
                } else {
2116 3
                    $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
2117
                }
2118
            }
2119
        }
2120
2121
        // top-level style settings
2122
        if (isset($style->quotePrefix)) {
2123
            $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

2123
            $docStyle->setQuotePrefix(/** @scrutinizer ignore-type */ $style->quotePrefix);
Loading history...
2124
        }
2125
    }
2126
2127
    /**
2128
     * @param Border $docBorder
2129
     * @param SimpleXMLElement $eleBorder
2130
     */
2131
    private static function readBorder(Border $docBorder, $eleBorder)
2132
    {
2133
        if (isset($eleBorder['style'])) {
2134
            $docBorder->setBorderStyle((string) $eleBorder['style']);
2135
        }
2136
        if (isset($eleBorder->color)) {
2137
            $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
2138
        }
2139
    }
2140
2141
    /**
2142
     * @param SimpleXMLElement | null $is
2143
     *
2144
     * @return RichText
2145
     */
2146
    private function parseRichText($is)
2147
    {
2148
        $value = new RichText();
2149
2150
        if (isset($is->t)) {
2151
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
2152
        } else {
2153
            if (is_object($is->r)) {
2154
                foreach ($is->r as $run) {
2155
                    if (!isset($run->rPr)) {
2156
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2157
                    } else {
2158
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2159
2160
                        if (isset($run->rPr->rFont['val'])) {
2161
                            $objText->getFont()->setName((string) $run->rPr->rFont['val']);
2162
                        }
2163
                        if (isset($run->rPr->sz['val'])) {
2164
                            $objText->getFont()->setSize((float) $run->rPr->sz['val']);
2165
                        }
2166 30
                        if (isset($run->rPr->color)) {
2167
                            $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
2168 30
                        }
2169
                        if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
2170
                            (isset($run->rPr->b) && !isset($run->rPr->b['val']))) {
2171 4
                            $objText->getFont()->setBold(true);
2172
                        }
2173 4
                        if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
2174
                            (isset($run->rPr->i) && !isset($run->rPr->i['val']))) {
2175
                            $objText->getFont()->setItalic(true);
2176
                        }
2177
                        if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
2178
                            $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
2179
                            if ($vertAlign == 'superscript') {
2180
                                $objText->getFont()->setSuperscript(true);
2181
                            }
2182
                            if ($vertAlign == 'subscript') {
2183
                                $objText->getFont()->setSubscript(true);
2184
                            }
2185
                        }
2186
                        if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
2187
                            $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2188
                        } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
2189
                            $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
2190
                        }
2191
                        if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
2192
                            (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) {
2193
                            $objText->getFont()->setStrikethrough(true);
2194
                        }
2195
                    }
2196
                }
2197
            }
2198
        }
2199
2200
        return $value;
2201
    }
2202
2203
    /**
2204
     * @param Spreadsheet $excel
2205
     * @param mixed $customUITarget
2206
     * @param mixed $zip
2207 29
     */
2208
    private function readRibbon(Spreadsheet $excel, $customUITarget, $zip)
2209 29
    {
2210 1
        $baseDir = dirname($customUITarget);
2211
        $nameCustomUI = basename($customUITarget);
2212 29
        // get the xml file (ribbon)
2213 26
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
2214
        $customUIImagesNames = [];
2215
        $customUIImagesBinaries = [];
2216 29
        // something like customUI/_rels/customUI.xml.rels
2217
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
2218
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
2219
        if ($dataRels) {
2220
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
2221
            $UIRels = simplexml_load_string(
2222
                $this->securityScan($dataRels),
2223
                'SimpleXMLElement',
2224
                Settings::getLibXmlLoaderOptions()
2225
            );
2226
            if (false !== $UIRels) {
2227
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
2228
                foreach ($UIRels->Relationship as $ele) {
2229
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
2230
                        // an image ?
2231
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
2232
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
2233
                    }
2234
                }
2235
            }
2236
        }
2237
        if ($localRibbon) {
2238
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
2239
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2240
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
2241
            } else {
2242
                $excel->setRibbonBinObjects(null, null);
2243
            }
2244
        } else {
2245
            $excel->setRibbonXMLData(null, null);
2246
            $excel->setRibbonBinObjects(null, null);
2247
        }
2248
    }
2249
2250
    private static function getArrayItem($array, $key = 0)
2251
    {
2252
        return isset($array[$key]) ? $array[$key] : null;
2253
    }
2254
2255
    private static function dirAdd($base, $add)
2256
    {
2257
        return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
2258
    }
2259
2260
    private static function toCSSArray($style)
2261
    {
2262
        $style = trim(str_replace(["\r", "\n"], '', $style), ';');
2263
2264
        $temp = explode(';', $style);
2265
        $style = [];
2266
        foreach ($temp as $item) {
2267
            $item = explode(':', $item);
2268
2269
            if (strpos($item[1], 'px') !== false) {
2270
                $item[1] = str_replace('px', '', $item[1]);
2271
            }
2272
            if (strpos($item[1], 'pt') !== false) {
2273
                $item[1] = str_replace('pt', '', $item[1]);
2274
                $item[1] = Font::fontSizeToPixels($item[1]);
2275
            }
2276
            if (strpos($item[1], 'in') !== false) {
2277
                $item[1] = str_replace('in', '', $item[1]);
2278
                $item[1] = Font::inchSizeToPixels($item[1]);
2279
            }
2280
            if (strpos($item[1], 'cm') !== false) {
2281
                $item[1] = str_replace('cm', '', $item[1]);
2282
                $item[1] = Font::centimeterSizeToPixels($item[1]);
2283
            }
2284
2285
            $style[$item[0]] = $item[1];
2286
        }
2287
2288
        return $style;
2289
    }
2290
2291
    private static function boolean($value)
2292
    {
2293
        if (is_object($value)) {
2294
            $value = (string) $value;
2295
        }
2296
        if (is_numeric($value)) {
2297
            return (bool) $value;
2298
        }
2299
2300
        return $value === 'true' || $value === 'TRUE';
2301
    }
2302
2303
    private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook)
2304
    {
2305
        if (!$xmlWorkbook->workbookProtection) {
2306
            return;
2307
        }
2308
2309
        if ($xmlWorkbook->workbookProtection['lockRevision']) {
2310
            $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']);
2311
        }
2312
2313
        if ($xmlWorkbook->workbookProtection['lockStructure']) {
2314
            $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']);
2315
        }
2316
2317
        if ($xmlWorkbook->workbookProtection['lockWindows']) {
2318
            $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']);
2319
        }
2320
2321
        if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
2322
            $excel->getSecurity()->setRevisionPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true);
0 ignored issues
show
Bug introduced by
The method setRevisionPassword() does not exist on PhpOffice\PhpSpreadsheet\Document\Security. Did you maybe mean setRevisionsPassword()? ( Ignorable by Annotation )

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

2322
            $excel->getSecurity()->/** @scrutinizer ignore-call */ setRevisionPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2323
        }
2324
2325
        if ($xmlWorkbook->workbookProtection['workbookPassword']) {
2326
            $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true);
2327
        }
2328
    }
2329
2330
    private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2331
    {
2332
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2333
            return;
2334
        }
2335
2336
        $relsWorksheet = simplexml_load_string(
2337
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2338
            $this->securityScan(
2339
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2340
            ),
2341
            'SimpleXMLElement',
2342
            Settings::getLibXmlLoaderOptions()
2343
        );
2344
        $ctrlProps = [];
2345
        foreach ($relsWorksheet->Relationship as $ele) {
2346
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') {
2347
                $ctrlProps[(string) $ele['Id']] = $ele;
2348
            }
2349
        }
2350
2351
        $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
2352
        foreach ($ctrlProps as $rId => $ctrlProp) {
2353
            $rId = substr($rId, 3);  // rIdXXX
2354
            $unparsedCtrlProps[$rId] = [];
2355
            $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
2356
            $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
2357
            $unparsedCtrlProps[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
2358
        }
2359
        unset($unparsedCtrlProps);
2360
    }
2361
2362
    private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2363
    {
2364
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2365
            return;
2366
        }
2367
2368
        $relsWorksheet = simplexml_load_string(
2369
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2370
            $this->securityScan(
2371
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2372
            ),
2373
            'SimpleXMLElement',
2374
            Settings::getLibXmlLoaderOptions()
2375
        );
2376
        $sheetPrinterSettings = [];
2377
        foreach ($relsWorksheet->Relationship as $ele) {
2378
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') {
2379
                $sheetPrinterSettings[(string) $ele['Id']] = $ele;
2380
            }
2381
        }
2382
2383
        $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
2384
        foreach ($sheetPrinterSettings as $rId => $printerSettings) {
2385
            $rId = substr($rId, 3);  // rIdXXX
2386
            $unparsedPrinterSettings[$rId] = [];
2387
            $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']);
2388
            $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target'];
2389
            $unparsedPrinterSettings[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
2390
        }
2391
        unset($unparsedPrinterSettings);
2392
    }
2393
}
2394