Xlsx.php 113 KB

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