Xlsx.php 151 KB

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