ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
Xlsx.php
Go to the documentation of this file.
1<?php
2
4
35use SimpleXMLElement;
36use stdClass;
37use Throwable;
38use XMLReader;
39use ZipArchive;
40
41class Xlsx extends BaseReader
42{
49
55 private static $theme = null;
56
60 public function __construct()
61 {
62 parent::__construct();
63 $this->referenceHelper = ReferenceHelper::getInstance();
64 $this->securityScanner = XmlScanner::getInstance($this);
65 }
66
74 public function canRead($pFilename)
75 {
76 File::assertFile($pFilename);
77
78 $result = false;
79 $zip = new ZipArchive();
80
81 if ($zip->open($pFilename) === true) {
82 $workbookBasename = $this->getWorkbookBaseName($zip);
83 $result = !empty($workbookBasename);
84
85 $zip->close();
86 }
87
88 return $result;
89 }
90
98 public function listWorksheetNames($pFilename)
99 {
100 File::assertFile($pFilename);
101
102 $worksheetNames = [];
103
104 $zip = new ZipArchive();
105 $zip->open($pFilename);
106
107 // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader
108 //~ http://schemas.openxmlformats.org/package/2006/relationships");
109 $rels = simplexml_load_string(
110 $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels'))
111 );
112 foreach ($rels->Relationship as $rel) {
113 switch ($rel['Type']) {
114 case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
115 //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
116 $xmlWorkbook = simplexml_load_string(
117 $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}"))
118 );
119
120 if ($xmlWorkbook->sheets) {
121 foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
122 // Check if sheet should be skipped
123 $worksheetNames[] = (string) $eleSheet['name'];
124 }
125 }
126 }
127 }
128
129 $zip->close();
130
131 return $worksheetNames;
132 }
133
141 public function listWorksheetInfo($pFilename)
142 {
143 File::assertFile($pFilename);
144
145 $worksheetInfo = [];
146
147 $zip = new ZipArchive();
148 $zip->open($pFilename);
149
150 //~ http://schemas.openxmlformats.org/package/2006/relationships"
151 $rels = simplexml_load_string(
152 $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')),
153 'SimpleXMLElement',
155 );
156 foreach ($rels->Relationship as $rel) {
157 if ($rel['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument') {
158 $dir = dirname($rel['Target']);
159
160 //~ http://schemas.openxmlformats.org/package/2006/relationships"
161 $relsWorkbook = simplexml_load_string(
162 $this->securityScanner->scan(
163 $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')
164 ),
165 'SimpleXMLElement',
167 );
168 $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
169
170 $worksheets = [];
171 foreach ($relsWorkbook->Relationship as $ele) {
172 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet') {
173 $worksheets[(string) $ele['Id']] = $ele['Target'];
174 }
175 }
176
177 //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
178 $xmlWorkbook = simplexml_load_string(
179 $this->securityScanner->scan(
180 $this->getFromZipArchive($zip, "{$rel['Target']}")
181 ),
182 'SimpleXMLElement',
184 );
185 if ($xmlWorkbook->sheets) {
186 $dir = dirname($rel['Target']);
188 foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
189 $tmpInfo = [
190 'worksheetName' => (string) $eleSheet['name'],
191 'lastColumnLetter' => 'A',
192 'lastColumnIndex' => 0,
193 'totalRows' => 0,
194 'totalColumns' => 0,
195 ];
196
197 $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
198 $fileWorksheetPath = strpos($fileWorksheet, '/') === 0 ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet";
199
200 $xml = new XMLReader();
201 $xml->xml(
202 $this->securityScanner->scanFile(
203 'zip://' . File::realpath($pFilename) . '#' . $fileWorksheetPath
204 ),
205 null,
207 );
208 $xml->setParserProperty(2, true);
209
210 $currCells = 0;
211 while ($xml->read()) {
212 if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) {
213 $row = $xml->getAttribute('r');
214 $tmpInfo['totalRows'] = $row;
215 $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
216 $currCells = 0;
217 } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) {
218 ++$currCells;
219 }
220 }
221 $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
222 $xml->close();
223
224 $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
225 $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
226
227 $worksheetInfo[] = $tmpInfo;
228 }
229 }
230 }
231 }
232
233 $zip->close();
234
235 return $worksheetInfo;
236 }
237
238 private static function castToBoolean($c)
239 {
240 $value = isset($c->v) ? (string) $c->v : null;
241 if ($value == '0') {
242 return false;
243 } elseif ($value == '1') {
244 return true;
245 }
246
247 return (bool) $c->v;
248 }
249
250 private static function castToError($c)
251 {
252 return isset($c->v) ? (string) $c->v : null;
253 }
254
255 private static function castToString($c)
256 {
257 return isset($c->v) ? (string) $c->v : null;
258 }
259
260 private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType): void
261 {
262 $cellDataType = 'f';
263 $value = "={$c->f}";
264 $calculatedValue = self::$castBaseType($c);
265
266 // Shared formula?
267 if (isset($c->f['t']) && strtolower((string) $c->f['t']) == 'shared') {
268 $instance = (string) $c->f['si'];
269
270 if (!isset($sharedFormulas[(string) $c->f['si']])) {
271 $sharedFormulas[$instance] = ['master' => $r, 'formula' => $value];
272 } else {
273 $master = Coordinate::indexesFromString($sharedFormulas[$instance]['master']);
275
276 $difference = [0, 0];
277 $difference[0] = $current[0] - $master[0];
278 $difference[1] = $current[1] - $master[1];
279
280 $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], 'A1', $difference[0], $difference[1]);
281 }
282 }
283 }
284
290 private function getFromZipArchive(ZipArchive $archive, $fileName = '')
291 {
292 // Root-relative paths
293 if (strpos($fileName, '//') !== false) {
294 $fileName = substr($fileName, strpos($fileName, '//') + 1);
295 }
296 $fileName = File::realpath($fileName);
297
298 // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
299 // so we need to load case-insensitively from the zip file
300
301 // Apache POI fixes
302 $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE);
303 if ($contents === false) {
304 $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE);
305 }
306
307 return $contents;
308 }
309
317 public function load($pFilename)
318 {
319 File::assertFile($pFilename);
320
321 // Initialisations
322 $excel = new Spreadsheet();
323 $excel->removeSheetByIndex(0);
324 if (!$this->readDataOnly) {
325 $excel->removeCellStyleXfByIndex(0); // remove the default style
326 $excel->removeCellXfByIndex(0); // remove the default style
327 }
328 $unparsedLoadedData = [];
329
330 $zip = new ZipArchive();
331 $zip->open($pFilename);
332
333 // Read the theme first, because we need the colour scheme when reading the styles
334 //~ http://schemas.openxmlformats.org/package/2006/relationships"
335 $workbookBasename = $this->getWorkbookBaseName($zip);
336 $wbRels = simplexml_load_string(
337 $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/_rels/${workbookBasename}.rels")),
338 'SimpleXMLElement',
340 );
341 foreach ($wbRels->Relationship as $rel) {
342 switch ($rel['Type']) {
343 case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme':
344 $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
345 $themeOrderAdditional = count($themeOrderArray);
346
347 $xmlTheme = simplexml_load_string(
348 $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")),
349 'SimpleXMLElement',
351 );
352 if (is_object($xmlTheme)) {
353 $xmlThemeName = $xmlTheme->attributes();
354 $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
355 $themeName = (string) $xmlThemeName['name'];
356
357 $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
358 $colourSchemeName = (string) $colourScheme['name'];
359 $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
360
361 $themeColours = [];
362 foreach ($colourScheme as $k => $xmlColour) {
363 $themePos = array_search($k, $themeOrderArray);
364 if ($themePos === false) {
365 $themePos = $themeOrderAdditional++;
366 }
367 if (isset($xmlColour->sysClr)) {
368 $xmlColourData = $xmlColour->sysClr->attributes();
369 $themeColours[$themePos] = $xmlColourData['lastClr'];
370 } elseif (isset($xmlColour->srgbClr)) {
371 $xmlColourData = $xmlColour->srgbClr->attributes();
372 $themeColours[$themePos] = $xmlColourData['val'];
373 }
374 }
375 self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours);
376 }
377
378 break;
379 }
380 }
381
382 //~ http://schemas.openxmlformats.org/package/2006/relationships"
383 $rels = simplexml_load_string(
384 $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')),
385 'SimpleXMLElement',
387 );
388
389 $propertyReader = new PropertyReader($this->securityScanner, $excel->getProperties());
390 foreach ($rels->Relationship as $rel) {
391 switch ($rel['Type']) {
392 case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties':
393 $propertyReader->readCoreProperties($this->getFromZipArchive($zip, "{$rel['Target']}"));
394
395 break;
396 case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties':
397 $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, "{$rel['Target']}"));
398
399 break;
400 case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties':
401 $propertyReader->readCustomProperties($this->getFromZipArchive($zip, "{$rel['Target']}"));
402
403 break;
404 //Ribbon
405 case 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility':
406 $customUI = $rel['Target'];
407 if ($customUI !== null) {
408 $this->readRibbon($excel, $customUI, $zip);
409 }
410
411 break;
412 case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
413 $dir = dirname($rel['Target']);
414 //~ http://schemas.openxmlformats.org/package/2006/relationships"
415 $relsWorkbook = simplexml_load_string(
416 $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')),
417 'SimpleXMLElement',
419 );
420 $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
421
422 $sharedStrings = [];
423 $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
424 if ($xpath) {
425 //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
426 $xmlStrings = simplexml_load_string(
427 $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
428 'SimpleXMLElement',
430 );
431 if (isset($xmlStrings->si)) {
432 foreach ($xmlStrings->si as $val) {
433 if (isset($val->t)) {
434 $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
435 } elseif (isset($val->r)) {
436 $sharedStrings[] = $this->parseRichText($val);
437 }
438 }
439 }
440 }
441
442 $worksheets = [];
443 $macros = $customUI = null;
444 foreach ($relsWorkbook->Relationship as $ele) {
445 switch ($ele['Type']) {
446 case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet':
447 $worksheets[(string) $ele['Id']] = $ele['Target'];
448
449 break;
450 // a vbaProject ? (: some macros)
451 case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject':
452 $macros = $ele['Target'];
453
454 break;
455 }
456 }
457
458 if ($macros !== null) {
459 $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin'); //vbaProject.bin always in 'xl' dir and always named vbaProject.bin
460 if ($macrosCode !== false) {
461 $excel->setMacrosCode($macrosCode);
462 $excel->setHasMacros(true);
463 //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir
464 $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin');
465 if ($Certificate !== false) {
466 $excel->setMacrosCertificate($Certificate);
467 }
468 }
469 }
470
471 $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
472 //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
473 $xmlStyles = simplexml_load_string(
474 $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
475 'SimpleXMLElement',
477 );
478
479 $styles = [];
480 $cellStyles = [];
481 $numFmts = null;
482 if ($xmlStyles && $xmlStyles->numFmts[0]) {
483 $numFmts = $xmlStyles->numFmts[0];
484 }
485 if (isset($numFmts) && ($numFmts !== null)) {
486 $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
487 }
488 if (!$this->readDataOnly && $xmlStyles) {
489 foreach ($xmlStyles->cellXfs->xf as $xf) {
490 $numFmt = null;
491
492 if ($xf['numFmtId']) {
493 if (isset($numFmts)) {
494 $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
495
496 if (isset($tmpNumFmt['formatCode'])) {
497 $numFmt = (string) $tmpNumFmt['formatCode'];
498 }
499 }
500
501 // We shouldn't override any of the built-in MS Excel values (values below id 164)
502 // But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used
503 // So we make allowance for them rather than lose formatting masks
504 if (
505 $numFmt === null &&
506 (int) $xf['numFmtId'] < 164 &&
507 NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== ''
508 ) {
509 $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
510 }
511 }
512 $quotePrefix = (bool) ($xf['quotePrefix'] ?? false);
513
514 $style = (object) [
515 'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL,
516 'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
517 'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
518 'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
519 'alignment' => $xf->alignment,
520 'protection' => $xf->protection,
521 'quotePrefix' => $quotePrefix,
522 ];
523 $styles[] = $style;
524
525 // add style to cellXf collection
526 $objStyle = new Style();
527 self::readStyle($objStyle, $style);
528 $excel->addCellXf($objStyle);
529 }
530
531 foreach ($xmlStyles->cellStyleXfs->xf ?? [] as $xf) {
533 if ($numFmts && $xf['numFmtId']) {
534 $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
535 if (isset($tmpNumFmt['formatCode'])) {
536 $numFmt = (string) $tmpNumFmt['formatCode'];
537 } elseif ((int) $xf['numFmtId'] < 165) {
538 $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
539 }
540 }
541
542 $quotePrefix = (bool) ($xf['quotePrefix'] ?? false);
543
544 $cellStyle = (object) [
545 'numFmt' => $numFmt,
546 'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
547 'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
548 'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
549 'alignment' => $xf->alignment,
550 'protection' => $xf->protection,
551 'quotePrefix' => $quotePrefix,
552 ];
553 $cellStyles[] = $cellStyle;
554
555 // add style to cellStyleXf collection
556 $objStyle = new Style();
557 self::readStyle($objStyle, $cellStyle);
558 $excel->addCellStyleXf($objStyle);
559 }
560 }
561
562 $styleReader = new Styles($xmlStyles);
563 $styleReader->setStyleBaseData(self::$theme, $styles, $cellStyles);
564 $dxfs = $styleReader->dxfs($this->readDataOnly);
565 $styles = $styleReader->styles();
566
567 //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
568 $xmlWorkbook = simplexml_load_string(
569 $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")),
570 'SimpleXMLElement',
572 );
573
574 // Set base date
575 if ($xmlWorkbook->workbookPr) {
577 if (isset($xmlWorkbook->workbookPr['date1904'])) {
578 if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) {
580 }
581 }
582 }
583
584 // Set protection
585 $this->readProtection($excel, $xmlWorkbook);
586
587 $sheetId = 0; // keep track of new sheet id in final workbook
588 $oldSheetId = -1; // keep track of old sheet id in final workbook
589 $countSkippedSheets = 0; // keep track of number of skipped sheets
590 $mapSheetId = []; // mapping of sheet ids from old to new
591
592 $charts = $chartDetails = [];
593
594 if ($xmlWorkbook->sheets) {
596 foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
597 ++$oldSheetId;
598
599 // Check if sheet should be skipped
600 if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) {
601 ++$countSkippedSheets;
602 $mapSheetId[$oldSheetId] = null;
603
604 continue;
605 }
606
607 // Map old sheet id in original workbook to new sheet id.
608 // They will differ if loadSheetsOnly() is being used
609 $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets;
610
611 // Load sheet
612 $docSheet = $excel->createSheet();
613 // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet
614 // references in formula cells... during the load, all formulae should be correct,
615 // and we're simply bringing the worksheet name in line with the formula, not the
616 // reverse
617 $docSheet->setTitle((string) $eleSheet['name'], false, false);
618 $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
619 //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
620 $xmlSheet = simplexml_load_string(
621 $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")),
622 'SimpleXMLElement',
624 );
625
626 $sharedFormulas = [];
627
628 if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') {
629 $docSheet->setSheetState((string) $eleSheet['state']);
630 }
631
632 if ($xmlSheet) {
633 // Setting Conditional Styles adjusts selected cells, so we need to execute this
634 // before reading the sheet view data to get the actual selected cells
635 if (!$this->readDataOnly && $xmlSheet->conditionalFormatting) {
636 (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load();
637 }
638
639 if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) {
640 $sheetViews = new SheetViews($xmlSheet->sheetViews->sheetView, $docSheet);
641 $sheetViews->load();
642 }
643
644 $sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheet);
645 $sheetViewOptions->load($this->getReadDataOnly());
646
647 (new ColumnAndRowAttributes($docSheet, $xmlSheet))
648 ->load($this->getReadFilter(), $this->getReadDataOnly());
649 }
650
651 if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
652 $cIndex = 1; // Cell Start from 1
653 foreach ($xmlSheet->sheetData->row as $row) {
654 $rowIndex = 1;
655 foreach ($row->c as $c) {
656 $r = (string) $c['r'];
657 if ($r == '') {
658 $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
659 }
660 $cellDataType = (string) $c['t'];
661 $value = null;
662 $calculatedValue = null;
663
664 // Read cell?
665 if ($this->getReadFilter() !== null) {
666 $coordinates = Coordinate::coordinateFromString($r);
667
668 if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) {
669 if (isset($c->f)) {
670 $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
671 }
672 ++$rowIndex;
673
674 continue;
675 }
676 }
677
678 // Read cell!
679 switch ($cellDataType) {
680 case 's':
681 if ((string) $c->v != '') {
682 $value = $sharedStrings[(int) ($c->v)];
683
684 if ($value instanceof RichText) {
685 $value = clone $value;
686 }
687 } else {
688 $value = '';
689 }
690
691 break;
692 case 'b':
693 if (!isset($c->f)) {
694 $value = self::castToBoolean($c);
695 } else {
696 // Formula
697 $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean');
698 if (isset($c->f['t'])) {
699 $att = $c->f;
700 $docSheet->getCell($r)->setFormulaAttributes($att);
701 }
702 }
703
704 break;
705 case 'inlineStr':
706 if (isset($c->f)) {
707 $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
708 } else {
709 $value = $this->parseRichText($c->is);
710 }
711
712 break;
713 case 'e':
714 if (!isset($c->f)) {
715 $value = self::castToError($c);
716 } else {
717 // Formula
718 $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
719 }
720
721 break;
722 default:
723 if (!isset($c->f)) {
724 $value = self::castToString($c);
725 } else {
726 // Formula
727 $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
728 if (isset($c->f['t'])) {
729 $attributes = $c->f['t'];
730 $docSheet->getCell($r)->setFormulaAttributes(['t' => (string) $attributes]);
731 }
732 }
733
734 break;
735 }
736
737 // read empty cells or the cells are not empty
738 if ($this->readEmptyCells || ($value !== null && $value !== '')) {
739 // Rich text?
740 if ($value instanceof RichText && $this->readDataOnly) {
741 $value = $value->getPlainText();
742 }
743
744 $cell = $docSheet->getCell($r);
745 // Assign value
746 if ($cellDataType != '') {
747 // it is possible, that datatype is numeric but with an empty string, which result in an error
748 if ($cellDataType === DataType::TYPE_NUMERIC && $value === '') {
749 $cellDataType = DataType::TYPE_STRING;
750 }
751 $cell->setValueExplicit($value, $cellDataType);
752 } else {
753 $cell->setValue($value);
754 }
755 if ($calculatedValue !== null) {
756 $cell->setCalculatedValue($calculatedValue);
757 }
758
759 // Style information?
760 if ($c['s'] && !$this->readDataOnly) {
761 // no style index means 0, it seems
762 $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
763 (int) ($c['s']) : 0);
764 }
765 }
766 ++$rowIndex;
767 }
768 ++$cIndex;
769 }
770 }
771
772 $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
773 if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
774 foreach ($aKeys as $key) {
775 $method = 'set' . ucfirst($key);
776 $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
777 }
778 }
779
780 if ($xmlSheet) {
781 $this->readSheetProtection($docSheet, $xmlSheet);
782 }
783
784 if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
785 (new AutoFilter($docSheet, $xmlSheet))->load();
786 }
787
788 if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
789 foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
790 $mergeRef = (string) $mergeCell['ref'];
791 if (strpos($mergeRef, ':') !== false) {
792 $docSheet->mergeCells((string) $mergeCell['ref']);
793 }
794 }
795 }
796
797 if ($xmlSheet && !$this->readDataOnly) {
798 $unparsedLoadedData = (new PageSetup($docSheet, $xmlSheet))->load($unparsedLoadedData);
799 }
800
801 if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
802 (new DataValidations($docSheet, $xmlSheet))->load();
803 }
804
805 // unparsed sheet AlternateContent
806 if ($xmlSheet && !$this->readDataOnly) {
807 $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
808 if ($mc->AlternateContent) {
809 foreach ($mc->AlternateContent as $alternateContent) {
810 $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
811 }
812 }
813 }
814
815 // Add hyperlinks
816 if (!$this->readDataOnly) {
817 $hyperlinkReader = new Hyperlinks($docSheet);
818 // Locate hyperlink relations
819 $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
820 if ($zip->locateName($relationsFileName)) {
821 //~ http://schemas.openxmlformats.org/package/2006/relationships"
822 $relsWorksheet = simplexml_load_string(
823 $this->securityScanner->scan(
824 $this->getFromZipArchive($zip, $relationsFileName)
825 ),
826 'SimpleXMLElement',
828 );
829 $hyperlinkReader->readHyperlinks($relsWorksheet);
830 }
831
832 // Loop through hyperlinks
833 if ($xmlSheet && $xmlSheet->hyperlinks) {
834 $hyperlinkReader->setHyperlinks($xmlSheet->hyperlinks);
835 }
836 }
837
838 // Add comments
839 $comments = [];
840 $vmlComments = [];
841 if (!$this->readDataOnly) {
842 // Locate comment relations
843 if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
844 //~ http://schemas.openxmlformats.org/package/2006/relationships"
845 $relsWorksheet = simplexml_load_string(
846 $this->securityScanner->scan(
847 $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
848 ),
849 'SimpleXMLElement',
851 );
852 foreach ($relsWorksheet->Relationship as $ele) {
853 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
854 $comments[(string) $ele['Id']] = (string) $ele['Target'];
855 }
856 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
857 $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
858 }
859 }
860 }
861
862 // Loop through comments
863 foreach ($comments as $relName => $relPath) {
864 // Load comments file
865 $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
866 $commentsFile = simplexml_load_string(
867 $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)),
868 'SimpleXMLElement',
870 );
871
872 // Utility variables
873 $authors = [];
874
875 // Loop through authors
876 foreach ($commentsFile->authors->author as $author) {
877 $authors[] = (string) $author;
878 }
879
880 // Loop through contents
881 foreach ($commentsFile->commentList->comment as $comment) {
882 $commentModel = $docSheet->getComment((string) $comment['ref']);
883 if (!empty($comment['authorId'])) {
884 $commentModel->setAuthor($authors[$comment['authorId']]);
885 }
886 $commentModel->setText($this->parseRichText($comment->text));
887 }
888 }
889
890 // later we will remove from it real vmlComments
891 $unparsedVmlDrawings = $vmlComments;
892
893 // Loop through VML comments
894 foreach ($vmlComments as $relName => $relPath) {
895 // Load VML comments file
896 $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
897
898 try {
899 $vmlCommentsFile = simplexml_load_string(
900 $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)),
901 'SimpleXMLElement',
903 );
904 $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
905 } catch (Throwable $ex) {
906 //Ignore unparsable vmlDrawings. Later they will be moved from $unparsedVmlDrawings to $unparsedLoadedData
907 continue;
908 }
909
910 $shapes = $vmlCommentsFile->xpath('//v:shape');
911 foreach ($shapes as $shape) {
912 $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
913
914 if (isset($shape['style'])) {
915 $style = (string) $shape['style'];
916 $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
917 $column = null;
918 $row = null;
919
920 $clientData = $shape->xpath('.//x:ClientData');
921 if (is_array($clientData) && !empty($clientData)) {
922 $clientData = $clientData[0];
923
924 if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
925 $temp = $clientData->xpath('.//x:Row');
926 if (is_array($temp)) {
927 $row = $temp[0];
928 }
929
930 $temp = $clientData->xpath('.//x:Column');
931 if (is_array($temp)) {
932 $column = $temp[0];
933 }
934 }
935 }
936
937 if (($column !== null) && ($row !== null)) {
938 // Set comment properties
939 $comment = $docSheet->getCommentByColumnAndRow($column + 1, $row + 1);
940 $comment->getFillColor()->setRGB($fillColor);
941
942 // Parse style
943 $styleArray = explode(';', str_replace(' ', '', $style));
944 foreach ($styleArray as $stylePair) {
945 $stylePair = explode(':', $stylePair);
946
947 if ($stylePair[0] == 'margin-left') {
948 $comment->setMarginLeft($stylePair[1]);
949 }
950 if ($stylePair[0] == 'margin-top') {
951 $comment->setMarginTop($stylePair[1]);
952 }
953 if ($stylePair[0] == 'width') {
954 $comment->setWidth($stylePair[1]);
955 }
956 if ($stylePair[0] == 'height') {
957 $comment->setHeight($stylePair[1]);
958 }
959 if ($stylePair[0] == 'visibility') {
960 $comment->setVisible($stylePair[1] == 'visible');
961 }
962 }
963
964 unset($unparsedVmlDrawings[$relName]);
965 }
966 }
967 }
968 }
969
970 // unparsed vmlDrawing
971 if ($unparsedVmlDrawings) {
972 foreach ($unparsedVmlDrawings as $rId => $relPath) {
973 $rId = substr($rId, 3); // rIdXXX
974 $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
975 $unparsedVmlDrawing[$rId] = [];
976 $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
977 $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
978 $unparsedVmlDrawing[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
979 unset($unparsedVmlDrawing);
980 }
981 }
982
983 // Header/footer images
984 if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
985 if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
986 //~ http://schemas.openxmlformats.org/package/2006/relationships"
987 $relsWorksheet = simplexml_load_string(
988 $this->securityScanner->scan(
989 $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
990 ),
991 'SimpleXMLElement',
993 );
994 $vmlRelationship = '';
995
996 foreach ($relsWorksheet->Relationship as $ele) {
997 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
998 $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
999 }
1000 }
1001
1002 if ($vmlRelationship != '') {
1003 // Fetch linked images
1004 //~ http://schemas.openxmlformats.org/package/2006/relationships"
1005 $relsVML = simplexml_load_string(
1006 $this->securityScanner->scan(
1007 $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
1008 ),
1009 'SimpleXMLElement',
1011 );
1012 $drawings = [];
1013 if (isset($relsVML->Relationship)) {
1014 foreach ($relsVML->Relationship as $ele) {
1015 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1016 $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
1017 }
1018 }
1019 }
1020 // Fetch VML document
1021 $vmlDrawing = simplexml_load_string(
1022 $this->securityScanner->scan($this->getFromZipArchive($zip, $vmlRelationship)),
1023 'SimpleXMLElement',
1025 );
1026 $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1027
1028 $hfImages = [];
1029
1030 $shapes = $vmlDrawing->xpath('//v:shape');
1031 foreach ($shapes as $idx => $shape) {
1032 $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
1033 $imageData = $shape->xpath('//v:imagedata');
1034
1035 if (!$imageData) {
1036 continue;
1037 }
1038
1039 $imageData = $imageData[$idx];
1040
1041 $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
1042 $style = self::toCSSArray((string) $shape['style']);
1043
1044 $hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
1045 if (isset($imageData['title'])) {
1046 $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
1047 }
1048
1049 $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
1050 $hfImages[(string) $shape['id']]->setResizeProportional(false);
1051 $hfImages[(string) $shape['id']]->setWidth($style['width']);
1052 $hfImages[(string) $shape['id']]->setHeight($style['height']);
1053 if (isset($style['margin-left'])) {
1054 $hfImages[(string) $shape['id']]->setOffsetX($style['margin-left']);
1055 }
1056 $hfImages[(string) $shape['id']]->setOffsetY($style['margin-top']);
1057 $hfImages[(string) $shape['id']]->setResizeProportional(true);
1058 }
1059
1060 $docSheet->getHeaderFooter()->setImages($hfImages);
1061 }
1062 }
1063 }
1064 }
1065
1066 // TODO: Autoshapes from twoCellAnchors!
1067 if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1068 //~ http://schemas.openxmlformats.org/package/2006/relationships"
1069 $relsWorksheet = simplexml_load_string(
1070 $this->securityScanner->scan(
1071 $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1072 ),
1073 'SimpleXMLElement',
1075 );
1076 $drawings = [];
1077 foreach ($relsWorksheet->Relationship as $ele) {
1078 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1079 $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
1080 }
1081 }
1082 if ($xmlSheet->drawing && !$this->readDataOnly) {
1083 $unparsedDrawings = [];
1084 $fileDrawing = null;
1085 foreach ($xmlSheet->drawing as $drawing) {
1086 $drawingRelId = (string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id');
1087 $fileDrawing = $drawings[$drawingRelId];
1088 //~ http://schemas.openxmlformats.org/package/2006/relationships"
1089 $relsDrawing = simplexml_load_string(
1090 $this->securityScanner->scan(
1091 $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
1092 ),
1093 'SimpleXMLElement',
1095 );
1096 $images = [];
1097 $hyperlinks = [];
1098 if ($relsDrawing && $relsDrawing->Relationship) {
1099 foreach ($relsDrawing->Relationship as $ele) {
1100 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
1101 $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
1102 }
1103 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1104 $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
1105 } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
1106 if ($this->includeCharts) {
1107 $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
1108 'id' => (string) $ele['Id'],
1109 'sheet' => $docSheet->getTitle(),
1110 ];
1111 }
1112 }
1113 }
1114 }
1115 $xmlDrawing = simplexml_load_string(
1116 $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)),
1117 'SimpleXMLElement',
1119 );
1120 $xmlDrawingChildren = $xmlDrawing->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
1121
1122 if ($xmlDrawingChildren->oneCellAnchor) {
1123 foreach ($xmlDrawingChildren->oneCellAnchor as $oneCellAnchor) {
1124 if ($oneCellAnchor->pic->blipFill) {
1126 $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1128 $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1130 $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1132 $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
1133
1134 $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1135 $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1136 $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1137 $imageKey = (string) self::getArrayItem(
1138 $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1139 'embed'
1140 );
1141
1142 if (isset($images[$imageKey])) {
1143 $objDrawing->setPath(
1144 'zip://' . File::realpath($pFilename) . '#' .
1145 $images[$imageKey],
1146 false
1147 );
1148 }
1149 $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
1150
1151 $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
1152 $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
1153 $objDrawing->setResizeProportional(false);
1154 $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
1155 $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
1156 if ($xfrm) {
1157 $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
1158 }
1159 if ($outerShdw) {
1160 $shadow = $objDrawing->getShadow();
1161 $shadow->setVisible(true);
1162 $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
1163 $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
1164 $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
1165 $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
1166 $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr;
1167 $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val'));
1168 $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000);
1169 }
1170
1171 $this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks);
1172
1173 $objDrawing->setWorksheet($docSheet);
1174 } elseif ($this->includeCharts && $oneCellAnchor->graphicFrame) {
1175 // Exported XLSX from Google Sheets positions charts with a oneCellAnchor
1176 $coordinates = Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1);
1177 $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff);
1178 $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
1179 $width = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx'));
1180 $height = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy'));
1181
1182 $graphic = $oneCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic;
1184 $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart;
1185 $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1186
1187 $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1188 'fromCoordinate' => $coordinates,
1189 'fromOffsetX' => $offsetX,
1190 'fromOffsetY' => $offsetY,
1191 'width' => $width,
1192 'height' => $height,
1193 'worksheetTitle' => $docSheet->getTitle(),
1194 ];
1195 }
1196 }
1197 }
1198 if ($xmlDrawingChildren->twoCellAnchor) {
1199 foreach ($xmlDrawingChildren->twoCellAnchor as $twoCellAnchor) {
1200 if ($twoCellAnchor->pic->blipFill) {
1201 $blip = $twoCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
1202 $xfrm = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
1203 $outerShdw = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
1204 $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
1205 $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
1206 $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
1207 $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
1208 $imageKey = (string) self::getArrayItem(
1209 $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
1210 'embed'
1211 );
1212 if (isset($images[$imageKey])) {
1213 $objDrawing->setPath(
1214 'zip://' . File::realpath($pFilename) . '#' .
1215 $images[$imageKey],
1216 false
1217 );
1218 }
1219 $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1));
1220
1221 $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff));
1222 $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
1223 $objDrawing->setResizeProportional(false);
1224
1225 if ($xfrm) {
1226 $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cx')));
1227 $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cy')));
1228 $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
1229 }
1230 if ($outerShdw) {
1231 $shadow = $objDrawing->getShadow();
1232 $shadow->setVisible(true);
1233 $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
1234 $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
1235 $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
1236 $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
1237 $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr;
1238 $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val'));
1239 $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000);
1240 }
1241
1242 $this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks);
1243
1244 $objDrawing->setWorksheet($docSheet);
1245 } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
1246 $fromCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
1247 $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff);
1248 $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
1249 $toCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
1250 $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff);
1251 $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
1252 $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic;
1254 $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart;
1255 $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
1256
1257 $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
1258 'fromCoordinate' => $fromCoordinate,
1259 'fromOffsetX' => $fromOffsetX,
1260 'fromOffsetY' => $fromOffsetY,
1261 'toCoordinate' => $toCoordinate,
1262 'toOffsetX' => $toOffsetX,
1263 'toOffsetY' => $toOffsetY,
1264 'worksheetTitle' => $docSheet->getTitle(),
1265 ];
1266 }
1267 }
1268 }
1269 if ($relsDrawing === false && $xmlDrawing->count() == 0) {
1270 // Save Drawing without rels and children as unparsed
1271 $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML();
1272 }
1273 }
1274
1275 // store original rId of drawing files
1276 $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = [];
1277 foreach ($relsWorksheet->Relationship as $ele) {
1278 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
1279 $drawingRelId = (string) $ele['Id'];
1280 $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = $drawingRelId;
1281 if (isset($unparsedDrawings[$drawingRelId])) {
1282 $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['Drawings'][$drawingRelId] = $unparsedDrawings[$drawingRelId];
1283 }
1284 }
1285 }
1286
1287 // unparsed drawing AlternateContent
1288 $xmlAltDrawing = simplexml_load_string(
1289 $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)),
1290 'SimpleXMLElement',
1292 )->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
1293
1294 if ($xmlAltDrawing->AlternateContent) {
1295 foreach ($xmlAltDrawing->AlternateContent as $alternateContent) {
1296 $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML();
1297 }
1298 }
1299 }
1300 }
1301
1302 $this->readFormControlProperties($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1303 $this->readPrinterSettings($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
1304
1305 // Loop through definedNames
1306 if ($xmlWorkbook->definedNames) {
1307 foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1308 // Extract range
1309 $extractedRange = (string) $definedName;
1310 if (($spos = strpos($extractedRange, '!')) !== false) {
1311 $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
1312 } else {
1313 $extractedRange = str_replace('$', '', $extractedRange);
1314 }
1315
1316 // Valid range?
1317 if ($extractedRange == '') {
1318 continue;
1319 }
1320
1321 // Some definedNames are only applicable if we are on the same sheet...
1322 if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) {
1323 // Switch on type
1324 switch ((string) $definedName['name']) {
1325 case '_xlnm._FilterDatabase':
1326 if ((string) $definedName['hidden'] !== '1') {
1327 $extractedRange = explode(',', $extractedRange);
1328 foreach ($extractedRange as $range) {
1329 $autoFilterRange = $range;
1330 if (strpos($autoFilterRange, ':') !== false) {
1331 $docSheet->getAutoFilter()->setRange($autoFilterRange);
1332 }
1333 }
1334 }
1335
1336 break;
1337 case '_xlnm.Print_Titles':
1338 // Split $extractedRange
1339 $extractedRange = explode(',', $extractedRange);
1340
1341 // Set print titles
1342 foreach ($extractedRange as $range) {
1343 $matches = [];
1344 $range = str_replace('$', '', $range);
1345
1346 // check for repeating columns, e g. 'A:A' or 'A:D'
1347 if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
1348 $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]);
1349 } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
1350 // check for repeating rows, e.g. '1:1' or '1:5'
1351 $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]);
1352 }
1353 }
1354
1355 break;
1356 case '_xlnm.Print_Area':
1357 $rangeSets = preg_split("/('?(?:.*?)'?(?:![A-Z0-9]+:[A-Z0-9]+)),?/", $extractedRange, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
1358 $newRangeSets = [];
1359 foreach ($rangeSets as $rangeSet) {
1360 [$sheetName, $rangeSet] = Worksheet::extractSheetTitle($rangeSet, true);
1361 if (strpos($rangeSet, ':') === false) {
1362 $rangeSet = $rangeSet . ':' . $rangeSet;
1363 }
1364 $newRangeSets[] = str_replace('$', '', $rangeSet);
1365 }
1366 $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
1367
1368 break;
1369 default:
1370 break;
1371 }
1372 }
1373 }
1374 }
1375
1376 // Next sheet id
1377 ++$sheetId;
1378 }
1379
1380 // Loop through definedNames
1381 if ($xmlWorkbook->definedNames) {
1382 foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
1383 // Extract range
1384 $extractedRange = (string) $definedName;
1385
1386 // Valid range?
1387 if ($extractedRange == '') {
1388 continue;
1389 }
1390
1391 // Some definedNames are only applicable if we are on the same sheet...
1392 if ((string) $definedName['localSheetId'] != '') {
1393 // Local defined name
1394 // Switch on type
1395 switch ((string) $definedName['name']) {
1396 case '_xlnm._FilterDatabase':
1397 case '_xlnm.Print_Titles':
1398 case '_xlnm.Print_Area':
1399 break;
1400 default:
1401 if ($mapSheetId[(int) $definedName['localSheetId']] !== null) {
1402 $range = Worksheet::extractSheetTitle((string) $definedName, true);
1403 $scope = $excel->getSheet($mapSheetId[(int) $definedName['localSheetId']]);
1404 if (strpos((string) $definedName, '!') !== false) {
1405 $range[0] = str_replace("''", "'", $range[0]);
1406 $range[0] = str_replace("'", '', $range[0]);
1407 if ($worksheet = $excel->getSheetByName($range[0])) {
1408 $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $worksheet, $extractedRange, true, $scope));
1409 } else {
1410 $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true, $scope));
1411 }
1412 } else {
1413 $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true));
1414 }
1415 }
1416
1417 break;
1418 }
1419 } elseif (!isset($definedName['localSheetId'])) {
1420 $definedRange = (string) $definedName;
1421 // "Global" definedNames
1422 $locatedSheet = null;
1423 if (strpos((string) $definedName, '!') !== false) {
1424 // Modify range, and extract the first worksheet reference
1425 // Need to split on a comma or a space if not in quotes, and extract the first part.
1426 $definedNameValueParts = preg_split("/[ ,](?=([^']*'[^']*')*[^']*$)/miuU", $definedRange);
1427 // Extract sheet name
1428 [$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true);
1429 $extractedSheetName = trim($extractedSheetName, "'");
1430
1431 // Locate sheet
1432 $locatedSheet = $excel->getSheetByName($extractedSheetName);
1433 }
1434
1435 if ($locatedSheet === null && !DefinedName::testIfFormula($definedRange)) {
1436 $definedRange = '#REF!';
1437 }
1438 $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $locatedSheet, $definedRange, false));
1439 }
1440 }
1441 }
1442 }
1443
1444 if ((!$this->readDataOnly || !empty($this->loadSheetsOnly)) && isset($xmlWorkbook->bookViews->workbookView)) {
1445 $workbookView = $xmlWorkbook->bookViews->workbookView;
1446
1447 // active sheet index
1448 $activeTab = (int) ($workbookView['activeTab']); // refers to old sheet index
1449
1450 // keep active sheet index if sheet is still loaded, else first sheet is set as the active
1451 if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
1452 $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
1453 } else {
1454 if ($excel->getSheetCount() == 0) {
1455 $excel->createSheet();
1456 }
1457 $excel->setActiveSheetIndex(0);
1458 }
1459
1460 if (isset($workbookView['showHorizontalScroll'])) {
1461 $showHorizontalScroll = (string) $workbookView['showHorizontalScroll'];
1462 $excel->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll));
1463 }
1464
1465 if (isset($workbookView['showVerticalScroll'])) {
1466 $showVerticalScroll = (string) $workbookView['showVerticalScroll'];
1467 $excel->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll));
1468 }
1469
1470 if (isset($workbookView['showSheetTabs'])) {
1471 $showSheetTabs = (string) $workbookView['showSheetTabs'];
1472 $excel->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs));
1473 }
1474
1475 if (isset($workbookView['minimized'])) {
1476 $minimized = (string) $workbookView['minimized'];
1477 $excel->setMinimized($this->castXsdBooleanToBool($minimized));
1478 }
1479
1480 if (isset($workbookView['autoFilterDateGrouping'])) {
1481 $autoFilterDateGrouping = (string) $workbookView['autoFilterDateGrouping'];
1482 $excel->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping));
1483 }
1484
1485 if (isset($workbookView['firstSheet'])) {
1486 $firstSheet = (string) $workbookView['firstSheet'];
1487 $excel->setFirstSheetIndex((int) $firstSheet);
1488 }
1489
1490 if (isset($workbookView['visibility'])) {
1491 $visibility = (string) $workbookView['visibility'];
1492 $excel->setVisibility($visibility);
1493 }
1494
1495 if (isset($workbookView['tabRatio'])) {
1496 $tabRatio = (string) $workbookView['tabRatio'];
1497 $excel->setTabRatio((int) $tabRatio);
1498 }
1499 }
1500
1501 break;
1502 }
1503 }
1504
1505 if (!$this->readDataOnly) {
1506 $contentTypes = simplexml_load_string(
1507 $this->securityScanner->scan(
1508 $this->getFromZipArchive($zip, '[Content_Types].xml')
1509 ),
1510 'SimpleXMLElement',
1512 );
1513
1514 // Default content types
1515 foreach ($contentTypes->Default as $contentType) {
1516 switch ($contentType['ContentType']) {
1517 case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings':
1518 $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType'];
1519
1520 break;
1521 }
1522 }
1523
1524 // Override content types
1525 foreach ($contentTypes->Override as $contentType) {
1526 switch ($contentType['ContentType']) {
1527 case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
1528 if ($this->includeCharts) {
1529 $chartEntryRef = ltrim($contentType['PartName'], '/');
1530 $chartElements = simplexml_load_string(
1531 $this->securityScanner->scan(
1532 $this->getFromZipArchive($zip, $chartEntryRef)
1533 ),
1534 'SimpleXMLElement',
1536 );
1537 $objChart = Chart::readChart($chartElements, basename($chartEntryRef, '.xml'));
1538
1539 if (isset($charts[$chartEntryRef])) {
1540 $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
1541 if (isset($chartDetails[$chartPositionRef])) {
1542 $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
1543 $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
1544 $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
1545 if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) {
1546 // For oneCellAnchor positioned charts, toCoordinate is not in the data. Does it need to be calculated?
1547 $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
1548 }
1549 }
1550 }
1551 }
1552
1553 break;
1554
1555 // unparsed
1556 case 'application/vnd.ms-excel.controlproperties+xml':
1557 $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
1558
1559 break;
1560 }
1561 }
1562 }
1563
1564 $excel->setUnparsedLoadedData($unparsedLoadedData);
1565
1566 $zip->close();
1567
1568 return $excel;
1569 }
1570
1574 private static function readStyle(Style $docStyle, $style): void
1575 {
1576 $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
1577
1578 // font
1579 if (isset($style->font)) {
1580 Styles::readFontStyle($docStyle->getFont(), $style->font);
1581 }
1582
1583 // fill
1584 if (isset($style->fill)) {
1585 Styles::readFillStyle($docStyle->getFill(), $style->fill);
1586 }
1587
1588 // border
1589 if (isset($style->border)) {
1590 Styles::readBorderStyle($docStyle->getBorders(), $style->border);
1591 }
1592
1593 // alignment
1594 if (isset($style->alignment)) {
1595 Styles::readAlignmentStyle($docStyle->getAlignment(), $style->alignment);
1596 }
1597
1598 // protection
1599 if (isset($style->protection)) {
1600 Styles::readProtectionLocked($docStyle, $style->protection);
1601 Styles::readProtectionHidden($docStyle, $style->protection);
1602 }
1603
1604 // top-level style settings
1605 if (isset($style->quotePrefix)) {
1606 $docStyle->setQuotePrefix((bool) $style->quotePrefix);
1607 }
1608 }
1609
1615 private function parseRichText(?SimpleXMLElement $is)
1616 {
1617 $value = new RichText();
1618
1619 if (isset($is->t)) {
1620 $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
1621 } else {
1622 if (is_object($is->r)) {
1623
1625 foreach ($is->r as $run) {
1626 if (!isset($run->rPr)) {
1627 $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
1628 } else {
1629 $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
1630
1631 if (isset($run->rPr->rFont['val'])) {
1632 $objText->getFont()->setName((string) $run->rPr->rFont['val']);
1633 }
1634 if (isset($run->rPr->sz['val'])) {
1635 $objText->getFont()->setSize((float) $run->rPr->sz['val']);
1636 }
1637 if (isset($run->rPr->color)) {
1638 $objText->getFont()->setColor(new Color(Styles::readColor($run->rPr->color)));
1639 }
1640 if (
1641 (isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
1642 (isset($run->rPr->b) && !isset($run->rPr->b['val']))
1643 ) {
1644 $objText->getFont()->setBold(true);
1645 }
1646 if (
1647 (isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
1648 (isset($run->rPr->i) && !isset($run->rPr->i['val']))
1649 ) {
1650 $objText->getFont()->setItalic(true);
1651 }
1652 if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
1653 $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
1654 if ($vertAlign == 'superscript') {
1655 $objText->getFont()->setSuperscript(true);
1656 }
1657 if ($vertAlign == 'subscript') {
1658 $objText->getFont()->setSubscript(true);
1659 }
1660 }
1661 if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
1662 $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
1663 } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
1664 $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
1665 }
1666 if (
1667 (isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
1668 (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))
1669 ) {
1670 $objText->getFont()->setStrikethrough(true);
1671 }
1672 }
1673 }
1674 }
1675 }
1676
1677 return $value;
1678 }
1679
1684 private function readRibbon(Spreadsheet $excel, $customUITarget, $zip): void
1685 {
1686 $baseDir = dirname($customUITarget);
1687 $nameCustomUI = basename($customUITarget);
1688 // get the xml file (ribbon)
1689 $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
1690 $customUIImagesNames = [];
1691 $customUIImagesBinaries = [];
1692 // something like customUI/_rels/customUI.xml.rels
1693 $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
1694 $dataRels = $this->getFromZipArchive($zip, $pathRels);
1695 if ($dataRels) {
1696 // exists and not empty if the ribbon have some pictures (other than internal MSO)
1697 $UIRels = simplexml_load_string(
1698 $this->securityScanner->scan($dataRels),
1699 'SimpleXMLElement',
1701 );
1702 if (false !== $UIRels) {
1703 // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
1704 foreach ($UIRels->Relationship as $ele) {
1705 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
1706 // an image ?
1707 $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
1708 $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
1709 }
1710 }
1711 }
1712 }
1713 if ($localRibbon) {
1714 $excel->setRibbonXMLData($customUITarget, $localRibbon);
1715 if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
1716 $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
1717 } else {
1718 $excel->setRibbonBinObjects(null, null);
1719 }
1720 } else {
1721 $excel->setRibbonXMLData(null, null);
1722 $excel->setRibbonBinObjects(null, null);
1723 }
1724 }
1725
1726 private static function getArrayItem($array, $key = 0)
1727 {
1728 return $array[$key] ?? null;
1729 }
1730
1731 private static function dirAdd($base, $add)
1732 {
1733 return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
1734 }
1735
1736 private static function toCSSArray($style)
1737 {
1739
1740 $temp = explode(';', $style);
1741 $style = [];
1742 foreach ($temp as $item) {
1743 $item = explode(':', $item);
1744
1745 if (strpos($item[1], 'px') !== false) {
1746 $item[1] = str_replace('px', '', $item[1]);
1747 }
1748 if (strpos($item[1], 'pt') !== false) {
1749 $item[1] = str_replace('pt', '', $item[1]);
1750 $item[1] = Font::fontSizeToPixels($item[1]);
1751 }
1752 if (strpos($item[1], 'in') !== false) {
1753 $item[1] = str_replace('in', '', $item[1]);
1754 $item[1] = Font::inchSizeToPixels($item[1]);
1755 }
1756 if (strpos($item[1], 'cm') !== false) {
1757 $item[1] = str_replace('cm', '', $item[1]);
1758 $item[1] = Font::centimeterSizeToPixels($item[1]);
1759 }
1760
1761 $style[$item[0]] = $item[1];
1762 }
1763
1764 return $style;
1765 }
1766
1767 public static function stripWhiteSpaceFromStyleString($string)
1768 {
1769 return trim(str_replace(["\r", "\n", ' '], '', $string), ';');
1770 }
1771
1772 private static function boolean($value)
1773 {
1774 if (is_object($value)) {
1775 $value = (string) $value;
1776 }
1777 if (is_numeric($value)) {
1778 return (bool) $value;
1779 }
1780
1781 return $value === 'true' || $value === 'TRUE';
1782 }
1783
1789 private function readHyperLinkDrawing($objDrawing, $cellAnchor, $hyperlinks): void
1790 {
1791 $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
1792
1793 if ($hlinkClick->count() === 0) {
1794 return;
1795 }
1796
1797 $hlinkId = (string) $hlinkClick->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id'];
1798 $hyperlink = new Hyperlink(
1799 $hyperlinks[$hlinkId],
1800 (string) self::getArrayItem($cellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')
1801 );
1802 $objDrawing->setHyperlink($hyperlink);
1803 }
1804
1805 private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook): void
1806 {
1807 if (!$xmlWorkbook->workbookProtection) {
1808 return;
1809 }
1810
1811 $excel->getSecurity()->setLockRevision(self::getLockValue($xmlWorkbook->workbookProtection, 'lockRevision'));
1812 $excel->getSecurity()->setLockStructure(self::getLockValue($xmlWorkbook->workbookProtection, 'lockStructure'));
1813 $excel->getSecurity()->setLockWindows(self::getLockValue($xmlWorkbook->workbookProtection, 'lockWindows'));
1814
1815 if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
1816 $excel->getSecurity()->setRevisionsPassword(
1817 (string) $xmlWorkbook->workbookProtection['revisionsPassword'],
1818 true
1819 );
1820 }
1821
1822 if ($xmlWorkbook->workbookProtection['workbookPassword']) {
1823 $excel->getSecurity()->setWorkbookPassword(
1824 (string) $xmlWorkbook->workbookProtection['workbookPassword'],
1825 true
1826 );
1827 }
1828 }
1829
1830 private static function getLockValue(SimpleXmlElement $protection, string $key): ?bool
1831 {
1832 $returnValue = null;
1833 $protectKey = $protection[$key];
1834 if (!empty($protectKey)) {
1835 $protectKey = (string) $protectKey;
1836 $returnValue = $protectKey !== 'false' && (bool) $protectKey;
1837 }
1838
1839 return $returnValue;
1840 }
1841
1842 private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void
1843 {
1844 if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1845 return;
1846 }
1847
1848 //~ http://schemas.openxmlformats.org/package/2006/relationships"
1849 $relsWorksheet = simplexml_load_string(
1850 $this->securityScanner->scan(
1851 $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1852 ),
1853 'SimpleXMLElement',
1855 );
1856 $ctrlProps = [];
1857 foreach ($relsWorksheet->Relationship as $ele) {
1858 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') {
1859 $ctrlProps[(string) $ele['Id']] = $ele;
1860 }
1861 }
1862
1863 $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
1864 foreach ($ctrlProps as $rId => $ctrlProp) {
1865 $rId = substr($rId, 3); // rIdXXX
1866 $unparsedCtrlProps[$rId] = [];
1867 $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
1868 $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
1869 $unparsedCtrlProps[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
1870 }
1871 unset($unparsedCtrlProps);
1872 }
1873
1874 private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void
1875 {
1876 if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
1877 return;
1878 }
1879
1880 //~ http://schemas.openxmlformats.org/package/2006/relationships"
1881 $relsWorksheet = simplexml_load_string(
1882 $this->securityScanner->scan(
1883 $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
1884 ),
1885 'SimpleXMLElement',
1887 );
1888 $sheetPrinterSettings = [];
1889 foreach ($relsWorksheet->Relationship as $ele) {
1890 if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') {
1891 $sheetPrinterSettings[(string) $ele['Id']] = $ele;
1892 }
1893 }
1894
1895 $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
1896 foreach ($sheetPrinterSettings as $rId => $printerSettings) {
1897 $rId = substr($rId, 3) . 'ps'; // rIdXXX, add 'ps' suffix to avoid identical resource identifier collision with unparsed vmlDrawing
1898 $unparsedPrinterSettings[$rId] = [];
1899 $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']);
1900 $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target'];
1901 $unparsedPrinterSettings[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
1902 }
1903 unset($unparsedPrinterSettings);
1904 }
1905
1920 private function castXsdBooleanToBool($xsdBoolean)
1921 {
1922 if ($xsdBoolean === 'false') {
1923 return false;
1924 }
1925
1926 return (bool) $xsdBoolean;
1927 }
1928
1934 private function getWorkbookBaseName(ZipArchive $zip)
1935 {
1936 $workbookBasename = '';
1937
1938 // check if it is an OOXML archive
1939 $rels = simplexml_load_string(
1940 $this->securityScanner->scan(
1941 $this->getFromZipArchive($zip, '_rels/.rels')
1942 ),
1943 'SimpleXMLElement',
1945 );
1946 if ($rels !== false) {
1947 foreach ($rels->Relationship as $rel) {
1948 switch ($rel['Type']) {
1949 case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
1950 $basename = basename($rel['Target']);
1951 if (preg_match('/workbook.*\.xml/', $basename)) {
1952 $workbookBasename = $basename;
1953 }
1954
1955 break;
1956 }
1957 }
1958 }
1959
1960 return $workbookBasename;
1961 }
1962
1963 private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void
1964 {
1965 if ($this->readDataOnly || !$xmlSheet->sheetProtection) {
1966 return;
1967 }
1968
1969 $algorithmName = (string) $xmlSheet->sheetProtection['algorithmName'];
1970 $protection = $docSheet->getProtection();
1971 $protection->setAlgorithm($algorithmName);
1972
1973 if ($algorithmName) {
1974 $protection->setPassword((string) $xmlSheet->sheetProtection['hashValue'], true);
1975 $protection->setSalt((string) $xmlSheet->sheetProtection['saltValue']);
1976 $protection->setSpinCount((int) $xmlSheet->sheetProtection['spinCount']);
1977 } else {
1978 $protection->setPassword((string) $xmlSheet->sheetProtection['password'], true);
1979 }
1980
1981 if ($xmlSheet->protectedRanges->protectedRange) {
1982 foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
1983 $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
1984 }
1985 }
1986 }
1987}
$result
$comment
Definition: buildRTE.php:83
An exception for terminatinating execution or to throw for unit testing.
Helper class to manipulate cell coordinates.
Definition: Coordinate.php:15
static coordinateFromString($pCoordinateString)
Coordinate from string.
Definition: Coordinate.php:32
static indexesFromString(string $coordinates)
Get indexes from a string coordinates.
Definition: Coordinate.php:52
static stringFromColumnIndex($columnIndex)
String from column index.
Definition: Coordinate.php:313
static testIfFormula(string $value)
static createInstance(string $name, ?Worksheet $worksheet=null, ?string $value=null, bool $localOnly=false, ?Worksheet $scope=null)
Create a new defined name, either a range or a formula.
Definition: DefinedName.php:84
getReadDataOnly()
Read data only? If this is true, then the Reader will only read data values for cells,...
Definition: BaseReader.php:64
static getInstance(Reader\IReader $reader)
Definition: XmlScanner.php:39
static readChart(SimpleXMLElement $chartElements, $chartName)
Definition: Chart.php:57
static readProtectionHidden(Style $docStyle, $style)
Definition: Styles.php:227
static readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml)
Definition: Styles.php:126
static readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml)
Definition: Styles.php:43
static readProtectionLocked(Style $docStyle, $style)
Definition: Styles.php:216
static readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml)
Definition: Styles.php:157
static readColor($color, $background=false)
Definition: Styles.php:238
static getLockValue(SimpleXmlElement $protection, string $key)
Definition: Xlsx.php:1830
readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet)
Definition: Xlsx.php:1963
listWorksheetNames($pFilename)
Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
Definition: Xlsx.php:98
readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook)
Definition: Xlsx.php:1805
readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
Definition: Xlsx.php:1874
static readStyle(Style $docStyle, $style)
Definition: Xlsx.php:1574
canRead($pFilename)
Can the current IReader read the file?
Definition: Xlsx.php:74
castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType)
Definition: Xlsx.php:260
readHyperLinkDrawing($objDrawing, $cellAnchor, $hyperlinks)
Definition: Xlsx.php:1789
static getArrayItem($array, $key=0)
Definition: Xlsx.php:1726
readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
Definition: Xlsx.php:1842
static dirAdd($base, $add)
Definition: Xlsx.php:1731
readRibbon(Spreadsheet $excel, $customUITarget, $zip)
Definition: Xlsx.php:1684
static stripWhiteSpaceFromStyleString($string)
Definition: Xlsx.php:1767
getFromZipArchive(ZipArchive $archive, $fileName='')
Definition: Xlsx.php:290
__construct()
Create a new Xlsx Reader instance.
Definition: Xlsx.php:60
getWorkbookBaseName(ZipArchive $zip)
Definition: Xlsx.php:1934
castXsdBooleanToBool($xsdBoolean)
Convert an 'xsd:boolean' XML value to a PHP boolean value.
Definition: Xlsx.php:1920
static getInstance()
Get an instance of this class.
static getLibXmlLoaderOptions()
Get default options for libxml loader.
Definition: Settings.php:116
static setExcelCalendar($baseDate)
Set the Excel calendar (Windows 1900 or Mac 1904).
Definition: Date.php:73
const CALENDAR_WINDOWS_1900
constants
Definition: Date.php:17
static angleToDegrees($pValue)
Convert angle to degrees.
Definition: Drawing.php:141
static EMUToPixels($pValue)
Convert EMU to pixels.
Definition: Drawing.php:28
static realpath($pFilename)
Returns canonicalized absolute pathname, also for ZIP archives.
Definition: File.php:76
static assertFile($filename)
Assert that given path is an existing file and is readable, otherwise throw exception.
Definition: File.php:143
static controlCharacterOOXML2PHP($value)
Convert from OpenXML escaped control character to PHP control character.
setRibbonXMLData($target, $xmlData)
set ribbon XML data.
setRibbonBinObjects($BinObjectsNames, $BinObjectsData)
store binaries ribbon objects (pictures).
static builtInFormatCode($pIndex)
Get built-in format code.
if(!file_exists(getcwd() . '/ilias.ini.php'))
registration confirmation script for ilias
Definition: confirmReg.php:12
$key
Definition: croninfo.php:18
$style
Definition: example_012.php:70
$r
Definition: example_031.php:79
if(array_key_exists('yes', $_REQUEST)) $attributes
Definition: getconsent.php:85
load($pFilename)
Loads PhpSpreadsheet from file.
$base
Definition: index.php:4
$row
if( $path[strlen( $path) - 1]==='/') if(is_dir($path)) if(!file_exists( $path)) if(preg_match('#\.php$#D', mb_strtolower($path, 'UTF-8'))) $contentType
Definition: module.php:144
echo;exit;}function LogoutNotification($SessionID){ global $ilDB;$q="SELECT session_id, data FROM usr_session WHERE expires > (\w+)\|/" PREG_SPLIT_NO_EMPTY PREG_SPLIT_DELIM_CAPTURE