Completed
Push — develop ( 7e9f43...b509b6 )
by Adrien
37:50
created

Xlsx::setRowAttributes()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 7.7305

Importance

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

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

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

718
                    $this->readProtection($excel, /** @scrutinizer ignore-type */ $xmlWorkbook);
Loading history...
719
720 33
                    $sheetId = 0; // keep track of new sheet id in final workbook
721 33
                    $oldSheetId = -1; // keep track of old sheet id in final workbook
722 33
                    $countSkippedSheets = 0; // keep track of number of skipped sheets
723 33
                    $mapSheetId = []; // mapping of sheet ids from old to new
724
725 33
                    $charts = $chartDetails = [];
726
727 33
                    if ($xmlWorkbook->sheets) {
728
                        /** @var SimpleXMLElement $eleSheet */
729 33
                        foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
730 33
                            ++$oldSheetId;
731
732
                            // Check if sheet should be skipped
733 33
                            if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) {
734 1
                                ++$countSkippedSheets;
735 1
                                $mapSheetId[$oldSheetId] = null;
736
737 1
                                continue;
738
                            }
739
740
                            // Map old sheet id in original workbook to new sheet id.
741
                            // They will differ if loadSheetsOnly() is being used
742 33
                            $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
743
744
                            // Load sheet
745 33
                            $docSheet = $excel->createSheet();
746
                            //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet
747
                            //        references in formula cells... during the load, all formulae should be correct,
748
                            //        and we're simply bringing the worksheet name in line with the formula, not the
749
                            //        reverse
750 33
                            $docSheet->setTitle((string) $eleSheet['name'], false, false);
751 33
                            $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
752
                            //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
753 33
                            $xmlSheet = simplexml_load_string(
754 33
                                $this->securityScan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")),
755 33
                                'SimpleXMLElement',
756 33
                                Settings::getLibXmlLoaderOptions()
757
                            );
758
759 33
                            $sharedFormulas = [];
760
761 33
                            if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') {
762 1
                                $docSheet->setSheetState((string) $eleSheet['state']);
763
                            }
764
765 33
                            if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) {
766 33
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) {
767
                                    $zoomScale = (int) ($xmlSheet->sheetViews->sheetView['zoomScale']);
768
                                    if ($zoomScale <= 0) {
769
                                        // setZoomScale will throw an Exception if the scale is less than or equals 0
770
                                        // that is OK when manually creating documents, but we should be able to read all documents
771
                                        $zoomScale = 100;
772
                                    }
773
774
                                    $docSheet->getSheetView()->setZoomScale($zoomScale);
775
                                }
776 33
                                if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) {
777
                                    $zoomScaleNormal = (int) ($xmlSheet->sheetViews->sheetView['zoomScaleNormal']);
778
                                    if ($zoomScaleNormal <= 0) {
779
                                        // setZoomScaleNormal will throw an Exception if the scale is less than or equals 0
780
                                        // that is OK when manually creating documents, but we should be able to read all documents
781
                                        $zoomScaleNormal = 100;
782
                                    }
783
784
                                    $docSheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal);
785
                                }
786 33
                                if (isset($xmlSheet->sheetViews->sheetView['view'])) {
787
                                    $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']);
788
                                }
789 33
                                if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) {
790 25
                                    $docSheet->setShowGridLines(self::boolean((string) $xmlSheet->sheetViews->sheetView['showGridLines']));
791
                                }
792 33
                                if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) {
793 25
                                    $docSheet->setShowRowColHeaders(self::boolean((string) $xmlSheet->sheetViews->sheetView['showRowColHeaders']));
794
                                }
795 33
                                if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) {
796
                                    $docSheet->setRightToLeft(self::boolean((string) $xmlSheet->sheetViews->sheetView['rightToLeft']));
797
                                }
798 33
                                if (isset($xmlSheet->sheetViews->sheetView->pane)) {
799 2
                                    $xSplit = 0;
800 2
                                    $ySplit = 0;
801 2
                                    $topLeftCell = null;
802
803 2
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) {
804 1
                                        $xSplit = (int) ($xmlSheet->sheetViews->sheetView->pane['xSplit']);
805
                                    }
806
807 2
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) {
808 2
                                        $ySplit = (int) ($xmlSheet->sheetViews->sheetView->pane['ySplit']);
809
                                    }
810
811 2
                                    if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) {
812 2
                                        $topLeftCell = (string) $xmlSheet->sheetViews->sheetView->pane['topLeftCell'];
813
                                    }
814
815 2
                                    $docSheet->freezePane(Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1), $topLeftCell);
816
                                }
817
818 33
                                if (isset($xmlSheet->sheetViews->sheetView->selection)) {
819 31
                                    if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) {
820 30
                                        $sqref = (string) $xmlSheet->sheetViews->sheetView->selection['sqref'];
821 30
                                        $sqref = explode(' ', $sqref);
822 30
                                        $sqref = $sqref[0];
823 30
                                        $docSheet->setSelectedCells($sqref);
824
                                    }
825
                                }
826
                            }
827
828 33
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->tabColor)) {
829 2
                                if (isset($xmlSheet->sheetPr->tabColor['rgb'])) {
830 2
                                    $docSheet->getTabColor()->setARGB((string) $xmlSheet->sheetPr->tabColor['rgb']);
831
                                }
832
                            }
833 33
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr['codeName'])) {
834 1
                                $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName'], false);
835
                            }
836 33
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->outlinePr)) {
837 25
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) &&
838 25
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) {
839
                                    $docSheet->setShowSummaryRight(false);
840
                                } else {
841 25
                                    $docSheet->setShowSummaryRight(true);
842
                                }
843
844 25
                                if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) &&
845 25
                                    !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) {
846
                                    $docSheet->setShowSummaryBelow(false);
847
                                } else {
848 25
                                    $docSheet->setShowSummaryBelow(true);
849
                                }
850
                            }
851
852 33
                            if (isset($xmlSheet->sheetPr, $xmlSheet->sheetPr->pageSetUpPr)) {
853
                                if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) &&
854
                                    !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) {
855
                                    $docSheet->getPageSetup()->setFitToPage(false);
856
                                } else {
857
                                    $docSheet->getPageSetup()->setFitToPage(true);
858
                                }
859
                            }
860
861 33
                            if (isset($xmlSheet->sheetFormatPr)) {
862 33
                                if (isset($xmlSheet->sheetFormatPr['customHeight']) &&
863 33
                                    self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) &&
864 33
                                    isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) {
865 1
                                    $docSheet->getDefaultRowDimension()->setRowHeight((float) $xmlSheet->sheetFormatPr['defaultRowHeight']);
866
                                }
867 33
                                if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) {
868 1
                                    $docSheet->getDefaultColumnDimension()->setWidth((float) $xmlSheet->sheetFormatPr['defaultColWidth']);
869
                                }
870 33
                                if (isset($xmlSheet->sheetFormatPr['zeroHeight']) &&
871 33
                                    ((string) $xmlSheet->sheetFormatPr['zeroHeight'] == '1')) {
872
                                    $docSheet->getDefaultRowDimension()->setZeroHeight(true);
873
                                }
874
                            }
875
876 33
                            if (isset($xmlSheet->printOptions) && !$this->readDataOnly) {
877 25
                                if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) {
878 25
                                    $docSheet->setShowGridlines(true);
879
                                }
880 25
                                if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) {
881
                                    $docSheet->setPrintGridlines(true);
882
                                }
883 25
                                if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) {
884
                                    $docSheet->getPageSetup()->setHorizontalCentered(true);
885
                                }
886 25
                                if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) {
887
                                    $docSheet->getPageSetup()->setVerticalCentered(true);
888
                                }
889
                            }
890
891 33
                            $columnsAttributes = [];
892 33
                            $rowsAttributes = [];
893 33
                            if (isset($xmlSheet->cols) && !$this->readDataOnly) {
894 8
                                foreach ($xmlSheet->cols->col as $col) {
895 8
                                    for ($i = (int) ($col['min']); $i <= (int) ($col['max']); ++$i) {
896 8
                                        if ($col['style'] && !$this->readDataOnly) {
897 3
                                            $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['xfIndex'] = (int) $col['style'];
898
                                        }
899 8
                                        if (self::boolean($col['hidden'])) {
900 1
                                            $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['visible'] = false;
901
                                        }
902 8
                                        if (self::boolean($col['collapsed'])) {
903 1
                                            $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['collapsed'] = true;
904
                                        }
905 8
                                        if ($col['outlineLevel'] > 0) {
906 1
                                            $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['outlineLevel'] = (int) $col['outlineLevel'];
907
                                        }
908 8
                                        $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['width'] = (float) $col['width'];
909
910 8
                                        if ((int) ($col['max']) == 16384) {
911
                                            break;
912
                                        }
913
                                    }
914
                                }
915
                            }
916
917 33
                            if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
918 28
                                foreach ($xmlSheet->sheetData->row as $row) {
919 28
                                    if ($row['ht'] && !$this->readDataOnly) {
920 3
                                        $rowsAttributes[(int) $row['r']]['rowHeight'] = (float) $row['ht'];
921
                                    }
922 28
                                    if (self::boolean($row['hidden']) && !$this->readDataOnly) {
923
                                        $rowsAttributes[(int) $row['r']]['visible'] = false;
924
                                    }
925 28
                                    if (self::boolean($row['collapsed'])) {
926
                                        $rowsAttributes[(int) $row['r']]['collapsed'] = true;
927
                                    }
928 28
                                    if ($row['outlineLevel'] > 0) {
929
                                        $rowsAttributes[(int) $row['r']]['outlineLevel'] = (int) $row['outlineLevel'];
930
                                    }
931 28
                                    if ($row['s'] && !$this->readDataOnly) {
932 28
                                        $rowsAttributes[(int) $row['r']]['xfIndex'] = (int) $row['s'];
933
                                    }
934
                                }
935
                            }
936
937
                            // set columns/rows attributes
938 33
                            $columnsAttributesSet = [];
939 33
                            $rowsAttributesSet = [];
940 33
                            foreach ($columnsAttributes as $coordColumn => $columnAttributes) {
941 8
                                foreach ($rowsAttributes as $coordRow => $rowAttributes) {
942 3
                                    if ($this->getReadFilter() !== null) {
943 3
                                        if (!$this->getReadFilter()->readCell($coordColumn, $coordRow, $docSheet->getTitle())) {
944
                                            continue;
945
                                        }
946
                                    }
947
948 3
                                    if (!isset($columnsAttributesSet[$coordColumn])) {
949 3
                                        $this->setColumnAttributes($docSheet, $coordColumn, $columnAttributes);
950 3
                                        $columnsAttributesSet[$coordColumn] = true;
951
                                    }
952 3
                                    if (!isset($rowsAttributesSet[$coordRow])) {
953 3
                                        $this->setRowAttributes($docSheet, $coordRow, $rowAttributes);
954 8
                                        $rowsAttributesSet[$coordRow] = true;
955
                                    }
956
                                }
957
                            }
958
959 33
                            if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
960 28
                                $cIndex = 1; // Cell Start from 1
961 28
                                foreach ($xmlSheet->sheetData->row as $row) {
962 28
                                    $rowIndex = 1;
963 28
                                    foreach ($row->c as $c) {
964 28
                                        $r = (string) $c['r'];
965 28
                                        if ($r == '') {
966 1
                                            $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
967
                                        }
968 28
                                        $cellDataType = (string) $c['t'];
969 28
                                        $value = null;
970 28
                                        $calculatedValue = null;
971
972
                                        // Read cell?
973 28
                                        if ($this->getReadFilter() !== null) {
974 28
                                            $coordinates = Coordinate::coordinateFromString($r);
975
976 28
                                            if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) {
977 2
                                                continue;
978
                                            }
979
                                        }
980
981
                                        // Read cell!
982
                                        switch ($cellDataType) {
983 28
                                            case 's':
984 18
                                                if ((string) $c->v != '') {
985 18
                                                    $value = $sharedStrings[(int) ($c->v)];
986
987 18
                                                    if ($value instanceof RichText) {
988 18
                                                        $value = clone $value;
989
                                                    }
990
                                                } else {
991
                                                    $value = '';
992
                                                }
993
994 18
                                                break;
995 19
                                            case 'b':
996 4
                                                if (!isset($c->f)) {
997 2
                                                    $value = self::castToBoolean($c);
998
                                                } else {
999
                                                    // Formula
1000 2
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean');
1001 2
                                                    if (isset($c->f['t'])) {
1002
                                                        $att = $c->f;
1003
                                                        $docSheet->getCell($r)->setFormulaAttributes($att);
1004
                                                    }
1005
                                                }
1006
1007 4
                                                break;
1008 16
                                            case 'inlineStr':
1009 2
                                                if (isset($c->f)) {
1010
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
1011
                                                } else {
1012 2
                                                    $value = $this->parseRichText($c->is);
1013
                                                }
1014
1015 2
                                                break;
1016 16
                                            case 'e':
1017
                                                if (!isset($c->f)) {
1018
                                                    $value = self::castToError($c);
1019
                                                } else {
1020
                                                    // Formula
1021
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
1022
                                                }
1023
1024
                                                break;
1025
                                            default:
1026 16
                                                if (!isset($c->f)) {
1027 14
                                                    $value = self::castToString($c);
1028
                                                } else {
1029
                                                    // Formula
1030 6
                                                    $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
1031
                                                }
1032
1033 16
                                                break;
1034
                                        }
1035
1036
                                        // Check for numeric values
1037 28
                                        if (is_numeric($value) && $cellDataType != 's') {
1038 14
                                            if ($value == (int) $value) {
1039 13
                                                $value = (int) $value;
1040 1
                                            } elseif ($value == (float) $value) {
1041 1
                                                $value = (float) $value;
1042
                                            } elseif ($value == (float) $value) {
1043
                                                $value = (float) $value;
1044
                                            }
1045
                                        }
1046
1047
                                        // Rich text?
1048 28
                                        if ($value instanceof RichText && $this->readDataOnly) {
1049
                                            $value = $value->getPlainText();
1050
                                        }
1051
1052 28
                                        $cell = $docSheet->getCell($r);
1053
                                        // Assign value
1054 28
                                        if ($cellDataType != '') {
1055 22
                                            $cell->setValueExplicit($value, $cellDataType);
1056
                                        } else {
1057 14
                                            $cell->setValue($value);
1058
                                        }
1059 28
                                        if ($calculatedValue !== null) {
1060 7
                                            $cell->setCalculatedValue($calculatedValue);
1061
                                        }
1062
1063
                                        // Style information?
1064 28
                                        if ($c['s'] && !$this->readDataOnly) {
1065
                                            // no style index means 0, it seems
1066 7
                                            $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
1067 7
                                                (int) ($c['s']) : 0);
1068
                                        }
1069 28
                                        $rowIndex += 1;
1070
                                    }
1071 28
                                    $cIndex += 1;
1072
                                }
1073
                            }
1074
1075 33
                            $conditionals = [];
1076 33
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
1077 1
                                foreach ($xmlSheet->conditionalFormatting as $conditional) {
1078 1
                                    foreach ($conditional->cfRule as $cfRule) {
1079 1
                                        if (((string) $cfRule['type'] == Conditional::CONDITION_NONE || (string) $cfRule['type'] == Conditional::CONDITION_CELLIS || (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSTEXT || (string) $cfRule['type'] == Conditional::CONDITION_EXPRESSION) && isset($dxfs[(int) ($cfRule['dxfId'])])) {
1080 1
                                            $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
1081
                                        }
1082
                                    }
1083
                                }
1084
1085 1
                                foreach ($conditionals as $ref => $cfRules) {
1086 1
                                    ksort($cfRules);
1087 1
                                    $conditionalStyles = [];
1088 1
                                    foreach ($cfRules as $cfRule) {
1089 1
                                        $objConditional = new Conditional();
1090 1
                                        $objConditional->setConditionType((string) $cfRule['type']);
1091 1
                                        $objConditional->setOperatorType((string) $cfRule['operator']);
1092
1093 1
                                        if ((string) $cfRule['text'] != '') {
1094
                                            $objConditional->setText((string) $cfRule['text']);
1095
                                        }
1096
1097 1
                                        if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
1098 1
                                            $objConditional->setStopIfTrue(true);
1099
                                        }
1100
1101 1
                                        if (count($cfRule->formula) > 1) {
1102
                                            foreach ($cfRule->formula as $formula) {
1103
                                                $objConditional->addCondition((string) $formula);
1104
                                            }
1105
                                        } else {
1106 1
                                            $objConditional->addCondition((string) $cfRule->formula);
1107
                                        }
1108 1
                                        $objConditional->setStyle(clone $dxfs[(int) ($cfRule['dxfId'])]);
1109 1
                                        $conditionalStyles[] = $objConditional;
1110
                                    }
1111
1112
                                    // Extract all cell references in $ref
1113 1
                                    $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
1114 1
                                    foreach ($cellBlocks as $cellBlock) {
1115 1
                                        $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
1116
                                    }
1117
                                }
1118
                            }
1119
1120 33
                            $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
1121 33
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1122 28
                                foreach ($aKeys as $key) {
1123 28
                                    $method = 'set' . ucfirst($key);
1124 28
                                    $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
1125
                                }
1126
                            }
1127
1128 33
                            if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
1129 28
                                $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true);
1130 28
                                if ($xmlSheet->protectedRanges->protectedRange) {
1131 2
                                    foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
1132 2
                                        $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
1133
                                    }
1134
                                }
1135
                            }
1136
1137 33
                            if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
1138
                                $autoFilterRange = (string) $xmlSheet->autoFilter['ref'];
1139
                                if (strpos($autoFilterRange, ':') !== false) {
1140
                                    $autoFilter = $docSheet->getAutoFilter();
1141
                                    $autoFilter->setRange($autoFilterRange);
1142
1143
                                    foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
1144
                                        $column = $autoFilter->getColumnByOffset((int) $filterColumn['colId']);
1145
                                        //    Check for standard filters
1146
                                        if ($filterColumn->filters) {
1147
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
1148
                                            $filters = $filterColumn->filters;
1149
                                            if ((isset($filters['blank'])) && ($filters['blank'] == 1)) {
1150
                                                //    Operator is undefined, but always treated as EQUAL
1151
                                                $column->createRule()->setRule(null, '')->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1152
                                            }
1153
                                            //    Standard filters are always an OR join, so no join rule needs to be set
1154
                                            //    Entries can be either filter elements
1155
                                            foreach ($filters->filter as $filterRule) {
1156
                                                //    Operator is undefined, but always treated as EQUAL
1157
                                                $column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
1158
                                            }
1159
                                            //    Or Date Group elements
1160
                                            foreach ($filters->dateGroupItem as $dateGroupItem) {
1161
                                                //    Operator is undefined, but always treated as EQUAL
1162
                                                $column->createRule()->setRule(
1163
                                                    null,
1164
                                                    [
1165
                                                        'year' => (string) $dateGroupItem['year'],
1166
                                                        'month' => (string) $dateGroupItem['month'],
1167
                                                        'day' => (string) $dateGroupItem['day'],
1168
                                                        'hour' => (string) $dateGroupItem['hour'],
1169
                                                        'minute' => (string) $dateGroupItem['minute'],
1170
                                                        'second' => (string) $dateGroupItem['second'],
1171
                                                    ],
1172
                                                    (string) $dateGroupItem['dateTimeGrouping']
1173
                                                )
1174
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP);
1175
                                            }
1176
                                        }
1177
                                        //    Check for custom filters
1178
                                        if ($filterColumn->customFilters) {
1179
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
1180
                                            $customFilters = $filterColumn->customFilters;
1181
                                            //    Custom filters can an AND or an OR join;
1182
                                            //        and there should only ever be one or two entries
1183
                                            if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
1184
                                                $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
1185
                                            }
1186
                                            foreach ($customFilters->customFilter as $filterRule) {
1187
                                                $column->createRule()->setRule(
1188
                                                    (string) $filterRule['operator'],
1189
                                                    (string) $filterRule['val']
1190
                                                )
1191
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
1192
                                            }
1193
                                        }
1194
                                        //    Check for dynamic filters
1195
                                        if ($filterColumn->dynamicFilter) {
1196
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
1197
                                            //    We should only ever have one dynamic filter
1198
                                            foreach ($filterColumn->dynamicFilter as $filterRule) {
1199
                                                //    Operator is undefined, but always treated as EQUAL
1200
                                                $column->createRule()->setRule(
1201
                                                    null,
1202
                                                    (string) $filterRule['val'],
1203
                                                    (string) $filterRule['type']
1204
                                                )
1205
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
1206
                                                if (isset($filterRule['val'])) {
1207
                                                    $column->setAttribute('val', (string) $filterRule['val']);
1208
                                                }
1209
                                                if (isset($filterRule['maxVal'])) {
1210
                                                    $column->setAttribute('maxVal', (string) $filterRule['maxVal']);
1211
                                                }
1212
                                            }
1213
                                        }
1214
                                        //    Check for dynamic filters
1215
                                        if ($filterColumn->top10) {
1216
                                            $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
1217
                                            //    We should only ever have one top10 filter
1218
                                            foreach ($filterColumn->top10 as $filterRule) {
1219
                                                $column->createRule()->setRule(
1220
                                                    (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
1221
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
1222
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
1223
                                                    ),
1224
                                                    (string) $filterRule['val'],
1225
                                                    (((isset($filterRule['top'])) && ($filterRule['top'] == 1))
1226
                                                        ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
1227
                                                        : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
1228
                                                    )
1229
                                                )
1230
                                                ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
1231
                                            }
1232
                                        }
1233
                                    }
1234
                                }
1235
                            }
1236
1237 33
                            if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
1238 6
                                foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
1239 6
                                    $mergeRef = (string) $mergeCell['ref'];
1240 6
                                    if (strpos($mergeRef, ':') !== false) {
1241 6
                                        $docSheet->mergeCells((string) $mergeCell['ref']);
1242
                                    }
1243
                                }
1244
                            }
1245
1246 33
                            if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) {
1247 32
                                $docPageMargins = $docSheet->getPageMargins();
1248 32
                                $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
1249 32
                                $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
1250 32
                                $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
1251 32
                                $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
1252 32
                                $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
1253 32
                                $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
1254
                            }
1255
1256 33
                            if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) {
1257 32
                                $docPageSetup = $docSheet->getPageSetup();
1258
1259 32
                                if (isset($xmlSheet->pageSetup['orientation'])) {
1260 32
                                    $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
1261
                                }
1262 32
                                if (isset($xmlSheet->pageSetup['paperSize'])) {
1263 29
                                    $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
1264
                                }
1265 32
                                if (isset($xmlSheet->pageSetup['scale'])) {
1266 25
                                    $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
1267
                                }
1268 32
                                if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
1269 25
                                    $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
1270
                                }
1271 32
                                if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
1272 25
                                    $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
1273
                                }
1274 32
                                if (isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) &&
1275 32
                                    self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) {
1276
                                    $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
1277
                                }
1278
1279 32
                                $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1280 32
                                if (isset($relAttributes['id'])) {
1281 7
                                    $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id'];
1282
                                }
1283
                            }
1284
1285 33
                            if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) {
1286 27
                                $docHeaderFooter = $docSheet->getHeaderFooter();
1287
1288 27
                                if (isset($xmlSheet->headerFooter['differentOddEven']) &&
1289 27
                                    self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) {
1290
                                    $docHeaderFooter->setDifferentOddEven(true);
1291
                                } else {
1292 27
                                    $docHeaderFooter->setDifferentOddEven(false);
1293
                                }
1294 27
                                if (isset($xmlSheet->headerFooter['differentFirst']) &&
1295 27
                                    self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) {
1296
                                    $docHeaderFooter->setDifferentFirst(true);
1297
                                } else {
1298 27
                                    $docHeaderFooter->setDifferentFirst(false);
1299
                                }
1300 27
                                if (isset($xmlSheet->headerFooter['scaleWithDoc']) &&
1301 27
                                    !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) {
1302
                                    $docHeaderFooter->setScaleWithDocument(false);
1303
                                } else {
1304 27
                                    $docHeaderFooter->setScaleWithDocument(true);
1305
                                }
1306 27
                                if (isset($xmlSheet->headerFooter['alignWithMargins']) &&
1307 27
                                    !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) {
1308 3
                                    $docHeaderFooter->setAlignWithMargins(false);
1309
                                } else {
1310 24
                                    $docHeaderFooter->setAlignWithMargins(true);
1311
                                }
1312
1313 27
                                $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
1314 27
                                $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
1315 27
                                $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
1316 27
                                $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
1317 27
                                $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
1318 27
                                $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
1319
                            }
1320
1321 33
                            if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) {
1322
                                foreach ($xmlSheet->rowBreaks->brk as $brk) {
1323
                                    if ($brk['man']) {
1324
                                        $docSheet->setBreak("A$brk[id]", Worksheet::BREAK_ROW);
1325
                                    }
1326
                                }
1327
                            }
1328 33
                            if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) {
1329
                                foreach ($xmlSheet->colBreaks->brk as $brk) {
1330
                                    if ($brk['man']) {
1331
                                        $docSheet->setBreak(Coordinate::stringFromColumnIndex((string) $brk['id'] + 1) . '1', Worksheet::BREAK_COLUMN);
1332
                                    }
1333
                                }
1334
                            }
1335
1336 33
                            if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
1337
                                foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
1338
                                    // Uppercase coordinate
1339
                                    $range = strtoupper($dataValidation['sqref']);
1340
                                    $rangeSet = explode(' ', $range);
1341
                                    foreach ($rangeSet as $range) {
1342
                                        $stRange = $docSheet->shrinkRangeToFit($range);
1343
1344
                                        // Extract all cell references in $range
1345
                                        foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) {
1346
                                            // Create validation
1347
                                            $docValidation = $docSheet->getCell($reference)->getDataValidation();
1348
                                            $docValidation->setType((string) $dataValidation['type']);
1349
                                            $docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
1350
                                            $docValidation->setOperator((string) $dataValidation['operator']);
1351
                                            $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
1352
                                            $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
1353
                                            $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
1354
                                            $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
1355
                                            $docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
1356
                                            $docValidation->setError((string) $dataValidation['error']);
1357
                                            $docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
1358
                                            $docValidation->setPrompt((string) $dataValidation['prompt']);
1359
                                            $docValidation->setFormula1((string) $dataValidation->formula1);
1360
                                            $docValidation->setFormula2((string) $dataValidation->formula2);
1361
                                        }
1362
                                    }
1363
                                }
1364
                            }
1365
1366
                            // unparsed sheet AlternateContent
1367 33
                            if ($xmlSheet && !$this->readDataOnly) {
1368 33
                                $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
1369 33
                                if ($mc->AlternateContent) {
1370 1
                                    foreach ($mc->AlternateContent as $alternateContent) {
1371 1
                                        $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
1372
                                    }
1373
                                }
1374
                            }
1375
1376
                            // Add hyperlinks
1377 33
                            $hyperlinks = [];
1378 33
                            if (!$this->readDataOnly) {
1379
                                // Locate hyperlink relations
1380 33
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1381
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1382 32
                                    $relsWorksheet = simplexml_load_string(
1383 32
                                        $this->securityScan(
1384 32
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1385
                                        ),
1386 32
                                        'SimpleXMLElement',
1387 32
                                        Settings::getLibXmlLoaderOptions()
1388
                                    );
1389 32
                                    foreach ($relsWorksheet->Relationship as $ele) {
1390 10
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1391 10
                                            $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1392
                                        }
1393
                                    }
1394
                                }
1395
1396
                                // Loop through hyperlinks
1397 33
                                if ($xmlSheet && $xmlSheet->hyperlinks) {
1398
                                    /** @var SimpleXMLElement $hyperlink */
1399 2
                                    foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
1400
                                        // Link url
1401 2
                                        $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1402
1403 2
                                        foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
1404 2
                                            $cell = $docSheet->getCell($cellReference);
1405 2
                                            if (isset($linkRel['id'])) {
1406 2
                                                $hyperlinkUrl = $hyperlinks[(string) $linkRel['id']];
1407 2
                                                if (isset($hyperlink['location'])) {
1408
                                                    $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
1409
                                                }
1410 2
                                                $cell->getHyperlink()->setUrl($hyperlinkUrl);
1411 2
                                            } elseif (isset($hyperlink['location'])) {
1412 2
                                                $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
1413
                                            }
1414
1415
                                            // Tooltip
1416 2
                                            if (isset($hyperlink['tooltip'])) {
1417 2
                                                $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
1418
                                            }
1419
                                        }
1420
                                    }
1421
                                }
1422
                            }
1423
1424
                            // Add comments
1425 33
                            $comments = [];
1426 33
                            $vmlComments = [];
1427 33
                            if (!$this->readDataOnly) {
1428
                                // Locate comment relations
1429 33
                                if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1430
                                    //~ http://schemas.openxmlformats.org/package/2006/relationships"
1431 32
                                    $relsWorksheet = simplexml_load_string(
1432 32
                                        $this->securityScan(
1433 32
                                            $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1434
                                        ),
1435 32
                                        'SimpleXMLElement',
1436 32
                                        Settings::getLibXmlLoaderOptions()
1437
                                    );
1438 32
                                    foreach ($relsWorksheet->Relationship as $ele) {
1439 10
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
1440 3
                                            $comments[(string) $ele['Id']] = (string) $ele['Target'];
1441
                                        }
1442 10
                                        if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1443 10
                                            $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
1444
                                        }
1445
                                    }
1446
                                }
1447
1448
                                // Loop through comments
1449 33
                                foreach ($comments as $relName => $relPath) {
1450
                                    // Load comments file
1451 3
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1452 3
                                    $commentsFile = simplexml_load_string(
1453 3
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1454 3
                                        'SimpleXMLElement',
1455 3
                                        Settings::getLibXmlLoaderOptions()
1456
                                    );
1457
1458
                                    // Utility variables
1459 3
                                    $authors = [];
1460
1461
                                    // Loop through authors
1462 3
                                    foreach ($commentsFile->authors->author as $author) {
1463 3
                                        $authors[] = (string) $author;
1464
                                    }
1465
1466
                                    // Loop through contents
1467 3
                                    foreach ($commentsFile->commentList->comment as $comment) {
1468 3
                                        if (!empty($comment['authorId'])) {
1469
                                            $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]);
1470
                                        }
1471 3
                                        $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text));
1472
                                    }
1473
                                }
1474
1475
                                // later we will remove from it real vmlComments
1476 33
                                $unparsedVmlDrawings = $vmlComments;
1477
1478
                                // Loop through VML comments
1479 33
                                foreach ($vmlComments as $relName => $relPath) {
1480
                                    // Load VML comments file
1481 4
                                    $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
1482 4
                                    $vmlCommentsFile = simplexml_load_string(
1483 4
                                        $this->securityScan($this->getFromZipArchive($zip, $relPath)),
1484 4
                                        'SimpleXMLElement',
1485 4
                                        Settings::getLibXmlLoaderOptions()
1486
                                    );
1487 4
                                    $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1488
1489 4
                                    $shapes = $vmlCommentsFile->xpath('//v:shape');
1490 4
                                    foreach ($shapes as $shape) {
1491 4
                                        $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1492
1493 4
                                        if (isset($shape['style'])) {
1494 4
                                            $style = (string) $shape['style'];
1495 4
                                            $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
1496 4
                                            $column = null;
1497 4
                                            $row = null;
1498
1499 4
                                            $clientData = $shape->xpath('.//x:ClientData');
1500 4
                                            if (is_array($clientData) && !empty($clientData)) {
1501 4
                                                $clientData = $clientData[0];
1502
1503 4
                                                if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
1504 3
                                                    $temp = $clientData->xpath('.//x:Row');
1505 3
                                                    if (is_array($temp)) {
1506 3
                                                        $row = $temp[0];
1507
                                                    }
1508
1509 3
                                                    $temp = $clientData->xpath('.//x:Column');
1510 3
                                                    if (is_array($temp)) {
1511 3
                                                        $column = $temp[0];
1512
                                                    }
1513
                                                }
1514
                                            }
1515
1516 4
                                            if (($column !== null) && ($row !== null)) {
1517
                                                // Set comment properties
1518 3
                                                $comment = $docSheet->getCommentByColumnAndRow($column + 1, $row + 1);
1519 3
                                                $comment->getFillColor()->setRGB($fillColor);
1520
1521
                                                // Parse style
1522 3
                                                $styleArray = explode(';', str_replace(' ', '', $style));
1523 3
                                                foreach ($styleArray as $stylePair) {
1524 3
                                                    $stylePair = explode(':', $stylePair);
1525
1526 3
                                                    if ($stylePair[0] == 'margin-left') {
1527 3
                                                        $comment->setMarginLeft($stylePair[1]);
1528
                                                    }
1529 3
                                                    if ($stylePair[0] == 'margin-top') {
1530 3
                                                        $comment->setMarginTop($stylePair[1]);
1531
                                                    }
1532 3
                                                    if ($stylePair[0] == 'width') {
1533 3
                                                        $comment->setWidth($stylePair[1]);
1534
                                                    }
1535 3
                                                    if ($stylePair[0] == 'height') {
1536 3
                                                        $comment->setHeight($stylePair[1]);
1537
                                                    }
1538 3
                                                    if ($stylePair[0] == 'visibility') {
1539 3
                                                        $comment->setVisible($stylePair[1] == 'visible');
1540
                                                    }
1541
                                                }
1542
1543 4
                                                unset($unparsedVmlDrawings[$relName]);
1544
                                            }
1545
                                        }
1546
                                    }
1547
                                }
1548
1549
                                // unparsed vmlDrawing
1550 33
                                if ($unparsedVmlDrawings) {
1551 1
                                    foreach ($unparsedVmlDrawings as $rId => $relPath) {
1552 1
                                        $rId = substr($rId, 3); // rIdXXX
1553 1
                                        $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
1554 1
                                        $unparsedVmlDrawing[$rId] = [];
1555 1
                                        $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
1556 1
                                        $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
1557 1
                                        $unparsedVmlDrawing[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
1558 1
                                        unset($unparsedVmlDrawing);
1559
                                    }
1560
                                }
1561
1562
                                // Header/footer images
1563 33
                                if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
1564
                                    if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1565
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1566
                                        $relsWorksheet = simplexml_load_string(
1567
                                            $this->securityScan(
1568
                                                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1569
                                            ),
1570
                                            'SimpleXMLElement',
1571
                                            Settings::getLibXmlLoaderOptions()
1572
                                        );
1573
                                        $vmlRelationship = '';
1574
1575
                                        foreach ($relsWorksheet->Relationship as $ele) {
1576
                                            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
1577
                                                $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1578
                                            }
1579
                                        }
1580
1581
                                        if ($vmlRelationship != '') {
1582
                                            // Fetch linked images
1583
                                            //~ http://schemas.openxmlformats.org/package/2006/relationships"
1584
                                            $relsVML = simplexml_load_string(
1585
                                                $this->securityScan(
1586
                                                    $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
1587
                                                ),
1588
                                                'SimpleXMLElement',
1589
                                                Settings::getLibXmlLoaderOptions()
1590
                                            );
1591
                                            $drawings = [];
1592
                                            foreach ($relsVML->Relationship as $ele) {
1593
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1594
                                                    $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
1595
                                                }
1596
                                            }
1597
1598
                                            // Fetch VML document
1599
                                            $vmlDrawing = simplexml_load_string(
1600
                                                $this->securityScan($this->getFromZipArchive($zip, $vmlRelationship)),
1601
                                                'SimpleXMLElement',
1602
                                                Settings::getLibXmlLoaderOptions()
1603
                                            );
1604
                                            $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1605
1606
                                            $hfImages = [];
1607
1608
                                            $shapes = $vmlDrawing->xpath('//v:shape');
1609
                                            foreach ($shapes as $idx => $shape) {
1610
                                                $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1611
                                                $imageData = $shape->xpath('//v:imagedata');
1612
1613
                                                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...
1614
                                                    continue;
1615
                                                }
1616
1617
                                                $imageData = $imageData[$idx];
1618
1619
                                                $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
1620
                                                $style = self::toCSSArray((string) $shape['style']);
1621
1622
                                                $hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
1623
                                                if (isset($imageData['title'])) {
1624
                                                    $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
1625
                                                }
1626
1627
                                                $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
1628
                                                $hfImages[(string) $shape['id']]->setResizeProportional(false);
1629
                                                $hfImages[(string) $shape['id']]->setWidth($style['width']);
1630
                                                $hfImages[(string) $shape['id']]->setHeight($style['height']);
1631
                                                if (isset($style['margin-left'])) {
1632
                                                    $hfImages[(string) $shape['id']]->setOffsetX($style['margin-left']);
1633
                                                }
1634
                                                $hfImages[(string) $shape['id']]->setOffsetY($style['margin-top']);
1635
                                                $hfImages[(string) $shape['id']]->setResizeProportional(true);
1636
                                            }
1637
1638
                                            $docSheet->getHeaderFooter()->setImages($hfImages);
1639
                                        }
1640
                                    }
1641
                                }
1642
                            }
1643
1644
                            // TODO: Autoshapes from twoCellAnchors!
1645 33
                            if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1646
                                //~ http://schemas.openxmlformats.org/package/2006/relationships"
1647 32
                                $relsWorksheet = simplexml_load_string(
1648 32
                                    $this->securityScan(
1649 32
                                        $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1650
                                    ),
1651 32
                                    'SimpleXMLElement',
1652 32
                                    Settings::getLibXmlLoaderOptions()
1653
                                );
1654 32
                                $drawings = [];
1655 32
                                foreach ($relsWorksheet->Relationship as $ele) {
1656 10
                                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1657 10
                                        $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1658
                                    }
1659
                                }
1660 32
                                if ($xmlSheet->drawing && !$this->readDataOnly) {
1661 5
                                    foreach ($xmlSheet->drawing as $drawing) {
1662 5
                                        $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
1663
                                        //~ http://schemas.openxmlformats.org/package/2006/relationships"
1664 5
                                        $relsDrawing = simplexml_load_string(
1665 5
                                            $this->securityScan(
1666 5
                                                $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
1667
                                            ),
1668 5
                                            'SimpleXMLElement',
1669 5
                                            Settings::getLibXmlLoaderOptions()
1670
                                        );
1671 5
                                        $images = [];
1672
1673 5
                                        if ($relsDrawing && $relsDrawing->Relationship) {
1674 4
                                            foreach ($relsDrawing->Relationship as $ele) {
1675 4
                                                if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1676 4
                                                    $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
1677 2
                                                } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
1678 2
                                                    if ($this->includeCharts) {
1679 2
                                                        $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
1680 2
                                                            'id' => (string) $ele['Id'],
1681 4
                                                            'sheet' => $docSheet->getTitle(),
1682
                                                        ];
1683
                                                    }
1684
                                                }
1685
                                            }
1686
                                        }
1687 5
                                        $xmlDrawing = simplexml_load_string(
1688 5
                                            $this->securityScan($this->getFromZipArchive($zip, $fileDrawing)),
1689 5
                                            'SimpleXMLElement',
1690 5
                                            Settings::getLibXmlLoaderOptions()
1691 5
                                        )->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
1692
1693 5
                                        if ($xmlDrawing->oneCellAnchor) {
1694 2
                                            foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
1695 2
                                                if ($oneCellAnchor->pic->blipFill) {
1696
                                                    /** @var SimpleXMLElement $blip */
1697 2
                                                    $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1698
                                                    /** @var SimpleXMLElement $xfrm */
1699 2
                                                    $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1700
                                                    /** @var SimpleXMLElement $outerShdw */
1701 2
                                                    $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1702 2
                                                    $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1703 2
                                                    $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1704 2
                                                    $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1705 2
                                                    $objDrawing->setPath(
1706 2
                                                        'zip://' . File::realpath($pFilename) . '#' .
1707 2
                                                        $images[(string) self::getArrayItem(
1708 2
                                                            $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1709 2
                                                            'embed'
1710
                                                        )],
1711 2
                                                        false
1712
                                                    );
1713 2
                                                    $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
1714 2
                                                    $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
1715 2
                                                    $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
1716 2
                                                    $objDrawing->setResizeProportional(false);
1717 2
                                                    $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
1718 2
                                                    $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
1719 2
                                                    if ($xfrm) {
1720 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

1720
                                                        $objDrawing->setRotation(Drawing::angleToDegrees(/** @scrutinizer ignore-type */ self::getArrayItem($xfrm->attributes(), 'rot')));
Loading history...
1721
                                                    }
1722 2
                                                    if ($outerShdw) {
1723 2
                                                        $shadow = $objDrawing->getShadow();
1724 2
                                                        $shadow->setVisible(true);
1725 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

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

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

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

2026
                            $objChart = Chart::readChart(/** @scrutinizer ignore-type */ $chartElements, basename($chartEntryRef, '.xml'));
Loading history...
2027
2028 2
                            if (isset($charts[$chartEntryRef])) {
2029 2
                                $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
2030 2
                                if (isset($chartDetails[$chartPositionRef])) {
2031 2
                                    $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
2032 2
                                    $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
2033 2
                                    $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
2034 2
                                    $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
2035
                                }
2036
                            }
2037
                        }
2038
2039 2
                        break;
2040
2041
                    // unparsed
2042 33
                    case 'application/vnd.ms-excel.controlproperties+xml':
2043 1
                        $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
2044
2045 33
                        break;
2046
                }
2047
            }
2048
        }
2049
2050 33
        $excel->setUnparsedLoadedData($unparsedLoadedData);
2051
2052 33
        $zip->close();
2053
2054 33
        return $excel;
2055
    }
2056
2057 33
    private static function readColor($color, $background = false)
2058
    {
2059 33
        if (isset($color['rgb'])) {
2060 28
            return (string) $color['rgb'];
2061 10
        } elseif (isset($color['indexed'])) {
2062 7
            return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
2063 7
        } elseif (isset($color['theme'])) {
2064 6
            if (self::$theme !== null) {
2065 6
                $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
2066 6
                if (isset($color['tint'])) {
2067 1
                    $tintAdjust = (float) $color['tint'];
2068 1
                    $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
2069
                }
2070
2071 6
                return 'FF' . $returnColour;
2072
            }
2073
        }
2074
2075 2
        if ($background) {
2076
            return 'FFFFFFFF';
2077
        }
2078
2079 2
        return 'FF000000';
2080
    }
2081
2082
    /**
2083
     * @param Style $docStyle
2084
     * @param SimpleXMLElement|\stdClass $style
2085
     */
2086 33
    private static function readStyle(Style $docStyle, $style)
2087
    {
2088 33
        $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
2089
2090
        // font
2091 33
        if (isset($style->font)) {
2092 33
            $docStyle->getFont()->setName((string) $style->font->name['val']);
2093 33
            $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

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

2208
            $docStyle->setQuotePrefix(/** @scrutinizer ignore-type */ $style->quotePrefix);
Loading history...
2209
        }
2210 33
    }
2211
2212
    /**
2213
     * @param Border $docBorder
2214
     * @param SimpleXMLElement $eleBorder
2215
     */
2216 33
    private static function readBorder(Border $docBorder, $eleBorder)
2217
    {
2218 33
        if (isset($eleBorder['style'])) {
2219 3
            $docBorder->setBorderStyle((string) $eleBorder['style']);
2220
        }
2221 33
        if (isset($eleBorder->color)) {
2222 3
            $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
2223
        }
2224 33
    }
2225
2226
    /**
2227
     * @param SimpleXMLElement | null $is
2228
     *
2229
     * @return RichText
2230
     */
2231 4
    private function parseRichText($is)
2232
    {
2233 4
        $value = new RichText();
2234
2235 4
        if (isset($is->t)) {
2236
            $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
2237
        } else {
2238 4
            if (is_object($is->r)) {
2239 4
                foreach ($is->r as $run) {
2240 4
                    if (!isset($run->rPr)) {
2241 4
                        $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2242
                    } else {
2243 3
                        $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
2244
2245 3
                        if (isset($run->rPr->rFont['val'])) {
2246 3
                            $objText->getFont()->setName((string) $run->rPr->rFont['val']);
2247
                        }
2248 3
                        if (isset($run->rPr->sz['val'])) {
2249 3
                            $objText->getFont()->setSize((float) $run->rPr->sz['val']);
2250
                        }
2251 3
                        if (isset($run->rPr->color)) {
2252 3
                            $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
2253
                        }
2254 3
                        if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
2255 3
                            (isset($run->rPr->b) && !isset($run->rPr->b['val']))) {
2256 3
                            $objText->getFont()->setBold(true);
2257
                        }
2258 3
                        if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
2259 3
                            (isset($run->rPr->i) && !isset($run->rPr->i['val']))) {
2260 2
                            $objText->getFont()->setItalic(true);
2261
                        }
2262 3
                        if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
2263
                            $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
2264
                            if ($vertAlign == 'superscript') {
2265
                                $objText->getFont()->setSuperscript(true);
2266
                            }
2267
                            if ($vertAlign == 'subscript') {
2268
                                $objText->getFont()->setSubscript(true);
2269
                            }
2270
                        }
2271 3
                        if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
2272
                            $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
2273 3
                        } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
2274 2
                            $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
2275
                        }
2276 3
                        if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
2277 3
                            (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) {
2278 4
                            $objText->getFont()->setStrikethrough(true);
2279
                        }
2280
                    }
2281
                }
2282
            }
2283
        }
2284
2285 4
        return $value;
2286
    }
2287
2288
    /**
2289
     * @param Spreadsheet $excel
2290
     * @param mixed $customUITarget
2291
     * @param mixed $zip
2292
     */
2293
    private function readRibbon(Spreadsheet $excel, $customUITarget, $zip)
2294
    {
2295
        $baseDir = dirname($customUITarget);
2296
        $nameCustomUI = basename($customUITarget);
2297
        // get the xml file (ribbon)
2298
        $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
2299
        $customUIImagesNames = [];
2300
        $customUIImagesBinaries = [];
2301
        // something like customUI/_rels/customUI.xml.rels
2302
        $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
2303
        $dataRels = $this->getFromZipArchive($zip, $pathRels);
2304
        if ($dataRels) {
2305
            // exists and not empty if the ribbon have some pictures (other than internal MSO)
2306
            $UIRels = simplexml_load_string(
2307
                $this->securityScan($dataRels),
2308
                'SimpleXMLElement',
2309
                Settings::getLibXmlLoaderOptions()
2310
            );
2311
            if (false !== $UIRels) {
2312
                // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
2313
                foreach ($UIRels->Relationship as $ele) {
2314
                    if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
2315
                        // an image ?
2316
                        $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
2317
                        $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
2318
                    }
2319
                }
2320
            }
2321
        }
2322
        if ($localRibbon) {
2323
            $excel->setRibbonXMLData($customUITarget, $localRibbon);
2324
            if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
2325
                $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
2326
            } else {
2327
                $excel->setRibbonBinObjects(null, null);
2328
            }
2329
        } else {
2330
            $excel->setRibbonXMLData(null, null);
2331
            $excel->setRibbonBinObjects(null, null);
2332
        }
2333
    }
2334
2335 34
    private static function getArrayItem($array, $key = 0)
2336
    {
2337 34
        return isset($array[$key]) ? $array[$key] : null;
2338
    }
2339
2340 9
    private static function dirAdd($base, $add)
2341
    {
2342 9
        return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
2343
    }
2344
2345
    private static function toCSSArray($style)
2346
    {
2347
        $style = trim(str_replace(["\r", "\n"], '', $style), ';');
2348
2349
        $temp = explode(';', $style);
2350
        $style = [];
2351
        foreach ($temp as $item) {
2352
            $item = explode(':', $item);
2353
2354
            if (strpos($item[1], 'px') !== false) {
2355
                $item[1] = str_replace('px', '', $item[1]);
2356
            }
2357
            if (strpos($item[1], 'pt') !== false) {
2358
                $item[1] = str_replace('pt', '', $item[1]);
2359
                $item[1] = Font::fontSizeToPixels($item[1]);
2360
            }
2361
            if (strpos($item[1], 'in') !== false) {
2362
                $item[1] = str_replace('in', '', $item[1]);
2363
                $item[1] = Font::inchSizeToPixels($item[1]);
2364
            }
2365
            if (strpos($item[1], 'cm') !== false) {
2366
                $item[1] = str_replace('cm', '', $item[1]);
2367
                $item[1] = Font::centimeterSizeToPixels($item[1]);
2368
            }
2369
2370
            $style[$item[0]] = $item[1];
2371
        }
2372
2373
        return $style;
2374
    }
2375
2376 33
    private static function boolean($value)
2377
    {
2378 33
        if (is_object($value)) {
2379 1
            $value = (string) $value;
2380
        }
2381 33
        if (is_numeric($value)) {
2382 30
            return (bool) $value;
2383
        }
2384
2385 33
        return $value === 'true' || $value === 'TRUE';
2386
    }
2387
2388 33
    private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook)
2389
    {
2390 33
        if (!$xmlWorkbook->workbookProtection) {
2391 32
            return;
2392
        }
2393
2394 1
        if ($xmlWorkbook->workbookProtection['lockRevision']) {
2395
            $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']);
2396
        }
2397
2398 1
        if ($xmlWorkbook->workbookProtection['lockStructure']) {
2399 1
            $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']);
2400
        }
2401
2402 1
        if ($xmlWorkbook->workbookProtection['lockWindows']) {
2403
            $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']);
2404
        }
2405
2406 1
        if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
2407
            $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

2407
            $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...
2408
        }
2409
2410 1
        if ($xmlWorkbook->workbookProtection['workbookPassword']) {
2411 1
            $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true);
2412
        }
2413 1
    }
2414
2415 33
    private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2416
    {
2417 33
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2418 4
            return;
2419
        }
2420
2421
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2422 32
        $relsWorksheet = simplexml_load_string(
2423 32
            $this->securityScan(
2424 32
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2425
            ),
2426 32
            'SimpleXMLElement',
2427 32
            Settings::getLibXmlLoaderOptions()
2428
        );
2429 32
        $ctrlProps = [];
2430 32
        foreach ($relsWorksheet->Relationship as $ele) {
2431 10
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') {
2432 10
                $ctrlProps[(string) $ele['Id']] = $ele;
2433
            }
2434
        }
2435
2436 32
        $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
2437 32
        foreach ($ctrlProps as $rId => $ctrlProp) {
2438 1
            $rId = substr($rId, 3); // rIdXXX
2439 1
            $unparsedCtrlProps[$rId] = [];
2440 1
            $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
2441 1
            $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
2442 1
            $unparsedCtrlProps[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
2443
        }
2444 32
        unset($unparsedCtrlProps);
2445 32
    }
2446
2447 33
    private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
2448
    {
2449 33
        if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
2450 4
            return;
2451
        }
2452
2453
        //~ http://schemas.openxmlformats.org/package/2006/relationships"
2454 32
        $relsWorksheet = simplexml_load_string(
2455 32
            $this->securityScan(
2456 32
                $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
2457
            ),
2458 32
            'SimpleXMLElement',
2459 32
            Settings::getLibXmlLoaderOptions()
2460
        );
2461 32
        $sheetPrinterSettings = [];
2462 32
        foreach ($relsWorksheet->Relationship as $ele) {
2463 10
            if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') {
2464 10
                $sheetPrinterSettings[(string) $ele['Id']] = $ele;
2465
            }
2466
        }
2467
2468 32
        $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
2469 32
        foreach ($sheetPrinterSettings as $rId => $printerSettings) {
2470 7
            $rId = substr($rId, 3); // rIdXXX
2471 7
            $unparsedPrinterSettings[$rId] = [];
2472 7
            $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']);
2473 7
            $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target'];
2474 7
            $unparsedPrinterSettings[$rId]['content'] = $this->securityScan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
2475
        }
2476 32
        unset($unparsedPrinterSettings);
2477 32
    }
2478
}
2479