Xlsx.php 132 KB

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