Xlsx.php 151 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604
  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. // Check for numeric values
  865. if (is_numeric($value) && $cellDataType != 's') {
  866. if ($value == (int) $value) {
  867. $value = (int) $value;
  868. } elseif ($value == (float) $value) {
  869. $value = (float) $value;
  870. } elseif ($value == (float) $value) {
  871. $value = (float) $value;
  872. }
  873. }
  874. // Rich text?
  875. if ($value instanceof RichText && $this->readDataOnly) {
  876. $value = $value->getPlainText();
  877. }
  878. $cell = $docSheet->getCell($r);
  879. // Assign value
  880. if ($cellDataType != '') {
  881. $cell->setValueExplicit($value, $cellDataType);
  882. } else {
  883. $cell->setValue($value);
  884. }
  885. if ($calculatedValue !== null) {
  886. $cell->setCalculatedValue($calculatedValue);
  887. }
  888. // Style information?
  889. if ($c['s'] && !$this->readDataOnly) {
  890. // no style index means 0, it seems
  891. $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
  892. (int) ($c['s']) : 0);
  893. }
  894. $rowIndex += 1;
  895. }
  896. $cIndex += 1;
  897. }
  898. }
  899. $conditionals = [];
  900. if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
  901. foreach ($xmlSheet->conditionalFormatting as $conditional) {
  902. foreach ($conditional->cfRule as $cfRule) {
  903. 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'])])) {
  904. $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
  905. }
  906. }
  907. }
  908. foreach ($conditionals as $ref => $cfRules) {
  909. ksort($cfRules);
  910. $conditionalStyles = [];
  911. foreach ($cfRules as $cfRule) {
  912. $objConditional = new Conditional();
  913. $objConditional->setConditionType((string) $cfRule['type']);
  914. $objConditional->setOperatorType((string) $cfRule['operator']);
  915. if ((string) $cfRule['text'] != '') {
  916. $objConditional->setText((string) $cfRule['text']);
  917. }
  918. if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
  919. $objConditional->setStopIfTrue(true);
  920. }
  921. if (count($cfRule->formula) > 1) {
  922. foreach ($cfRule->formula as $formula) {
  923. $objConditional->addCondition((string) $formula);
  924. }
  925. } else {
  926. $objConditional->addCondition((string) $cfRule->formula);
  927. }
  928. $objConditional->setStyle(clone $dxfs[(int) ($cfRule['dxfId'])]);
  929. $conditionalStyles[] = $objConditional;
  930. }
  931. // Extract all cell references in $ref
  932. $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
  933. foreach ($cellBlocks as $cellBlock) {
  934. $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles);
  935. }
  936. }
  937. }
  938. $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
  939. if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  940. foreach ($aKeys as $key) {
  941. $method = 'set' . ucfirst($key);
  942. $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key]));
  943. }
  944. }
  945. if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
  946. $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true);
  947. if ($xmlSheet->protectedRanges->protectedRange) {
  948. foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) {
  949. $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true);
  950. }
  951. }
  952. }
  953. if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
  954. $autoFilterRange = (string) $xmlSheet->autoFilter['ref'];
  955. if (strpos($autoFilterRange, ':') !== false) {
  956. $autoFilter = $docSheet->getAutoFilter();
  957. $autoFilter->setRange($autoFilterRange);
  958. foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) {
  959. $column = $autoFilter->getColumnByOffset((int) $filterColumn['colId']);
  960. // Check for standard filters
  961. if ($filterColumn->filters) {
  962. $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
  963. $filters = $filterColumn->filters;
  964. if ((isset($filters['blank'])) && ($filters['blank'] == 1)) {
  965. // Operator is undefined, but always treated as EQUAL
  966. $column->createRule()->setRule(null, '')->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
  967. }
  968. // Standard filters are always an OR join, so no join rule needs to be set
  969. // Entries can be either filter elements
  970. foreach ($filters->filter as $filterRule) {
  971. // Operator is undefined, but always treated as EQUAL
  972. $column->createRule()->setRule(null, (string) $filterRule['val'])->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_FILTER);
  973. }
  974. // Or Date Group elements
  975. foreach ($filters->dateGroupItem as $dateGroupItem) {
  976. // Operator is undefined, but always treated as EQUAL
  977. $column->createRule()->setRule(
  978. null,
  979. [
  980. 'year' => (string) $dateGroupItem['year'],
  981. 'month' => (string) $dateGroupItem['month'],
  982. 'day' => (string) $dateGroupItem['day'],
  983. 'hour' => (string) $dateGroupItem['hour'],
  984. 'minute' => (string) $dateGroupItem['minute'],
  985. 'second' => (string) $dateGroupItem['second'],
  986. ],
  987. (string) $dateGroupItem['dateTimeGrouping']
  988. )
  989. ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP);
  990. }
  991. }
  992. // Check for custom filters
  993. if ($filterColumn->customFilters) {
  994. $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
  995. $customFilters = $filterColumn->customFilters;
  996. // Custom filters can an AND or an OR join;
  997. // and there should only ever be one or two entries
  998. if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
  999. $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
  1000. }
  1001. foreach ($customFilters->customFilter as $filterRule) {
  1002. $column->createRule()->setRule(
  1003. (string) $filterRule['operator'],
  1004. (string) $filterRule['val']
  1005. )
  1006. ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
  1007. }
  1008. }
  1009. // Check for dynamic filters
  1010. if ($filterColumn->dynamicFilter) {
  1011. $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
  1012. // We should only ever have one dynamic filter
  1013. foreach ($filterColumn->dynamicFilter as $filterRule) {
  1014. // Operator is undefined, but always treated as EQUAL
  1015. $column->createRule()->setRule(
  1016. null,
  1017. (string) $filterRule['val'],
  1018. (string) $filterRule['type']
  1019. )
  1020. ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
  1021. if (isset($filterRule['val'])) {
  1022. $column->setAttribute('val', (string) $filterRule['val']);
  1023. }
  1024. if (isset($filterRule['maxVal'])) {
  1025. $column->setAttribute('maxVal', (string) $filterRule['maxVal']);
  1026. }
  1027. }
  1028. }
  1029. // Check for dynamic filters
  1030. if ($filterColumn->top10) {
  1031. $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
  1032. // We should only ever have one top10 filter
  1033. foreach ($filterColumn->top10 as $filterRule) {
  1034. $column->createRule()->setRule(
  1035. (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
  1036. ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
  1037. : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
  1038. ),
  1039. (string) $filterRule['val'],
  1040. (((isset($filterRule['top'])) && ($filterRule['top'] == 1))
  1041. ? Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
  1042. : Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
  1043. )
  1044. )
  1045. ->setRuleType(Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
  1046. }
  1047. }
  1048. }
  1049. }
  1050. }
  1051. if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
  1052. foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) {
  1053. $mergeRef = (string) $mergeCell['ref'];
  1054. if (strpos($mergeRef, ':') !== false) {
  1055. $docSheet->mergeCells((string) $mergeCell['ref']);
  1056. }
  1057. }
  1058. }
  1059. if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) {
  1060. $docPageMargins = $docSheet->getPageMargins();
  1061. $docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
  1062. $docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
  1063. $docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
  1064. $docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
  1065. $docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
  1066. $docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
  1067. }
  1068. if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) {
  1069. $docPageSetup = $docSheet->getPageSetup();
  1070. if (isset($xmlSheet->pageSetup['orientation'])) {
  1071. $docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
  1072. }
  1073. if (isset($xmlSheet->pageSetup['paperSize'])) {
  1074. $docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
  1075. }
  1076. if (isset($xmlSheet->pageSetup['scale'])) {
  1077. $docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
  1078. }
  1079. if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
  1080. $docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
  1081. }
  1082. if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
  1083. $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
  1084. }
  1085. if (isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) &&
  1086. self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) {
  1087. $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
  1088. }
  1089. $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
  1090. if (isset($relAttributes['id'])) {
  1091. $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id'];
  1092. }
  1093. }
  1094. if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) {
  1095. $docHeaderFooter = $docSheet->getHeaderFooter();
  1096. if (isset($xmlSheet->headerFooter['differentOddEven']) &&
  1097. self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) {
  1098. $docHeaderFooter->setDifferentOddEven(true);
  1099. } else {
  1100. $docHeaderFooter->setDifferentOddEven(false);
  1101. }
  1102. if (isset($xmlSheet->headerFooter['differentFirst']) &&
  1103. self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) {
  1104. $docHeaderFooter->setDifferentFirst(true);
  1105. } else {
  1106. $docHeaderFooter->setDifferentFirst(false);
  1107. }
  1108. if (isset($xmlSheet->headerFooter['scaleWithDoc']) &&
  1109. !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) {
  1110. $docHeaderFooter->setScaleWithDocument(false);
  1111. } else {
  1112. $docHeaderFooter->setScaleWithDocument(true);
  1113. }
  1114. if (isset($xmlSheet->headerFooter['alignWithMargins']) &&
  1115. !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) {
  1116. $docHeaderFooter->setAlignWithMargins(false);
  1117. } else {
  1118. $docHeaderFooter->setAlignWithMargins(true);
  1119. }
  1120. $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
  1121. $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
  1122. $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
  1123. $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
  1124. $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
  1125. $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
  1126. }
  1127. if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) {
  1128. foreach ($xmlSheet->rowBreaks->brk as $brk) {
  1129. if ($brk['man']) {
  1130. $docSheet->setBreak("A$brk[id]", Worksheet::BREAK_ROW);
  1131. }
  1132. }
  1133. }
  1134. if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) {
  1135. foreach ($xmlSheet->colBreaks->brk as $brk) {
  1136. if ($brk['man']) {
  1137. $docSheet->setBreak(Coordinate::stringFromColumnIndex((string) $brk['id'] + 1) . '1', Worksheet::BREAK_COLUMN);
  1138. }
  1139. }
  1140. }
  1141. if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
  1142. foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) {
  1143. // Uppercase coordinate
  1144. $range = strtoupper($dataValidation['sqref']);
  1145. $rangeSet = explode(' ', $range);
  1146. foreach ($rangeSet as $range) {
  1147. $stRange = $docSheet->shrinkRangeToFit($range);
  1148. // Extract all cell references in $range
  1149. foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $reference) {
  1150. // Create validation
  1151. $docValidation = $docSheet->getCell($reference)->getDataValidation();
  1152. $docValidation->setType((string) $dataValidation['type']);
  1153. $docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
  1154. $docValidation->setOperator((string) $dataValidation['operator']);
  1155. $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
  1156. $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
  1157. $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
  1158. $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
  1159. $docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
  1160. $docValidation->setError((string) $dataValidation['error']);
  1161. $docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
  1162. $docValidation->setPrompt((string) $dataValidation['prompt']);
  1163. $docValidation->setFormula1((string) $dataValidation->formula1);
  1164. $docValidation->setFormula2((string) $dataValidation->formula2);
  1165. }
  1166. }
  1167. }
  1168. }
  1169. // unparsed sheet AlternateContent
  1170. if ($xmlSheet && !$this->readDataOnly) {
  1171. $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
  1172. if ($mc->AlternateContent) {
  1173. foreach ($mc->AlternateContent as $alternateContent) {
  1174. $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
  1175. }
  1176. }
  1177. }
  1178. // Add hyperlinks
  1179. $hyperlinks = [];
  1180. if (!$this->readDataOnly) {
  1181. // Locate hyperlink relations
  1182. if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
  1183. //~ http://schemas.openxmlformats.org/package/2006/relationships"
  1184. $relsWorksheet = simplexml_load_string(
  1185. $this->securityScanner->scan(
  1186. $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
  1187. ),
  1188. 'SimpleXMLElement',
  1189. Settings::getLibXmlLoaderOptions()
  1190. );
  1191. foreach ($relsWorksheet->Relationship as $ele) {
  1192. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
  1193. $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
  1194. }
  1195. }
  1196. }
  1197. // Loop through hyperlinks
  1198. if ($xmlSheet && $xmlSheet->hyperlinks) {
  1199. /** @var SimpleXMLElement $hyperlink */
  1200. foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) {
  1201. // Link url
  1202. $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
  1203. foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
  1204. $cell = $docSheet->getCell($cellReference);
  1205. if (isset($linkRel['id'])) {
  1206. $hyperlinkUrl = $hyperlinks[(string) $linkRel['id']];
  1207. if (isset($hyperlink['location'])) {
  1208. $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
  1209. }
  1210. $cell->getHyperlink()->setUrl($hyperlinkUrl);
  1211. } elseif (isset($hyperlink['location'])) {
  1212. $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
  1213. }
  1214. // Tooltip
  1215. if (isset($hyperlink['tooltip'])) {
  1216. $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. // Add comments
  1223. $comments = [];
  1224. $vmlComments = [];
  1225. if (!$this->readDataOnly) {
  1226. // Locate comment relations
  1227. if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
  1228. //~ http://schemas.openxmlformats.org/package/2006/relationships"
  1229. $relsWorksheet = simplexml_load_string(
  1230. $this->securityScanner->scan(
  1231. $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
  1232. ),
  1233. 'SimpleXMLElement',
  1234. Settings::getLibXmlLoaderOptions()
  1235. );
  1236. foreach ($relsWorksheet->Relationship as $ele) {
  1237. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
  1238. $comments[(string) $ele['Id']] = (string) $ele['Target'];
  1239. }
  1240. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
  1241. $vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
  1242. }
  1243. }
  1244. }
  1245. // Loop through comments
  1246. foreach ($comments as $relName => $relPath) {
  1247. // Load comments file
  1248. $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
  1249. $commentsFile = simplexml_load_string(
  1250. $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)),
  1251. 'SimpleXMLElement',
  1252. Settings::getLibXmlLoaderOptions()
  1253. );
  1254. // Utility variables
  1255. $authors = [];
  1256. // Loop through authors
  1257. foreach ($commentsFile->authors->author as $author) {
  1258. $authors[] = (string) $author;
  1259. }
  1260. // Loop through contents
  1261. foreach ($commentsFile->commentList->comment as $comment) {
  1262. if (!empty($comment['authorId'])) {
  1263. $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]);
  1264. }
  1265. $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text));
  1266. }
  1267. }
  1268. // later we will remove from it real vmlComments
  1269. $unparsedVmlDrawings = $vmlComments;
  1270. // Loop through VML comments
  1271. foreach ($vmlComments as $relName => $relPath) {
  1272. // Load VML comments file
  1273. $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
  1274. $vmlCommentsFile = simplexml_load_string(
  1275. $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)),
  1276. 'SimpleXMLElement',
  1277. Settings::getLibXmlLoaderOptions()
  1278. );
  1279. $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1280. $shapes = $vmlCommentsFile->xpath('//v:shape');
  1281. foreach ($shapes as $shape) {
  1282. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1283. if (isset($shape['style'])) {
  1284. $style = (string) $shape['style'];
  1285. $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
  1286. $column = null;
  1287. $row = null;
  1288. $clientData = $shape->xpath('.//x:ClientData');
  1289. if (is_array($clientData) && !empty($clientData)) {
  1290. $clientData = $clientData[0];
  1291. if (isset($clientData['ObjectType']) && (string) $clientData['ObjectType'] == 'Note') {
  1292. $temp = $clientData->xpath('.//x:Row');
  1293. if (is_array($temp)) {
  1294. $row = $temp[0];
  1295. }
  1296. $temp = $clientData->xpath('.//x:Column');
  1297. if (is_array($temp)) {
  1298. $column = $temp[0];
  1299. }
  1300. }
  1301. }
  1302. if (($column !== null) && ($row !== null)) {
  1303. // Set comment properties
  1304. $comment = $docSheet->getCommentByColumnAndRow($column + 1, $row + 1);
  1305. $comment->getFillColor()->setRGB($fillColor);
  1306. // Parse style
  1307. $styleArray = explode(';', str_replace(' ', '', $style));
  1308. foreach ($styleArray as $stylePair) {
  1309. $stylePair = explode(':', $stylePair);
  1310. if ($stylePair[0] == 'margin-left') {
  1311. $comment->setMarginLeft($stylePair[1]);
  1312. }
  1313. if ($stylePair[0] == 'margin-top') {
  1314. $comment->setMarginTop($stylePair[1]);
  1315. }
  1316. if ($stylePair[0] == 'width') {
  1317. $comment->setWidth($stylePair[1]);
  1318. }
  1319. if ($stylePair[0] == 'height') {
  1320. $comment->setHeight($stylePair[1]);
  1321. }
  1322. if ($stylePair[0] == 'visibility') {
  1323. $comment->setVisible($stylePair[1] == 'visible');
  1324. }
  1325. }
  1326. unset($unparsedVmlDrawings[$relName]);
  1327. }
  1328. }
  1329. }
  1330. }
  1331. // unparsed vmlDrawing
  1332. if ($unparsedVmlDrawings) {
  1333. foreach ($unparsedVmlDrawings as $rId => $relPath) {
  1334. $rId = substr($rId, 3); // rIdXXX
  1335. $unparsedVmlDrawing = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['vmlDrawings'];
  1336. $unparsedVmlDrawing[$rId] = [];
  1337. $unparsedVmlDrawing[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $relPath);
  1338. $unparsedVmlDrawing[$rId]['relFilePath'] = $relPath;
  1339. $unparsedVmlDrawing[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedVmlDrawing[$rId]['filePath']));
  1340. unset($unparsedVmlDrawing);
  1341. }
  1342. }
  1343. // Header/footer images
  1344. if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
  1345. if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
  1346. //~ http://schemas.openxmlformats.org/package/2006/relationships"
  1347. $relsWorksheet = simplexml_load_string(
  1348. $this->securityScanner->scan(
  1349. $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
  1350. ),
  1351. 'SimpleXMLElement',
  1352. Settings::getLibXmlLoaderOptions()
  1353. );
  1354. $vmlRelationship = '';
  1355. foreach ($relsWorksheet->Relationship as $ele) {
  1356. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
  1357. $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
  1358. }
  1359. }
  1360. if ($vmlRelationship != '') {
  1361. // Fetch linked images
  1362. //~ http://schemas.openxmlformats.org/package/2006/relationships"
  1363. $relsVML = simplexml_load_string(
  1364. $this->securityScanner->scan(
  1365. $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
  1366. ),
  1367. 'SimpleXMLElement',
  1368. Settings::getLibXmlLoaderOptions()
  1369. );
  1370. $drawings = [];
  1371. foreach ($relsVML->Relationship as $ele) {
  1372. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
  1373. $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
  1374. }
  1375. }
  1376. // Fetch VML document
  1377. $vmlDrawing = simplexml_load_string(
  1378. $this->securityScanner->scan($this->getFromZipArchive($zip, $vmlRelationship)),
  1379. 'SimpleXMLElement',
  1380. Settings::getLibXmlLoaderOptions()
  1381. );
  1382. $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1383. $hfImages = [];
  1384. $shapes = $vmlDrawing->xpath('//v:shape');
  1385. foreach ($shapes as $idx => $shape) {
  1386. $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
  1387. $imageData = $shape->xpath('//v:imagedata');
  1388. if (!$imageData) {
  1389. continue;
  1390. }
  1391. $imageData = $imageData[$idx];
  1392. $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
  1393. $style = self::toCSSArray((string) $shape['style']);
  1394. $hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
  1395. if (isset($imageData['title'])) {
  1396. $hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
  1397. }
  1398. $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
  1399. $hfImages[(string) $shape['id']]->setResizeProportional(false);
  1400. $hfImages[(string) $shape['id']]->setWidth($style['width']);
  1401. $hfImages[(string) $shape['id']]->setHeight($style['height']);
  1402. if (isset($style['margin-left'])) {
  1403. $hfImages[(string) $shape['id']]->setOffsetX($style['margin-left']);
  1404. }
  1405. $hfImages[(string) $shape['id']]->setOffsetY($style['margin-top']);
  1406. $hfImages[(string) $shape['id']]->setResizeProportional(true);
  1407. }
  1408. $docSheet->getHeaderFooter()->setImages($hfImages);
  1409. }
  1410. }
  1411. }
  1412. }
  1413. // TODO: Autoshapes from twoCellAnchors!
  1414. if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
  1415. //~ http://schemas.openxmlformats.org/package/2006/relationships"
  1416. $relsWorksheet = simplexml_load_string(
  1417. $this->securityScanner->scan(
  1418. $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
  1419. ),
  1420. 'SimpleXMLElement',
  1421. Settings::getLibXmlLoaderOptions()
  1422. );
  1423. $drawings = [];
  1424. foreach ($relsWorksheet->Relationship as $ele) {
  1425. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
  1426. $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
  1427. }
  1428. }
  1429. if ($xmlSheet->drawing && !$this->readDataOnly) {
  1430. foreach ($xmlSheet->drawing as $drawing) {
  1431. $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
  1432. //~ http://schemas.openxmlformats.org/package/2006/relationships"
  1433. $relsDrawing = simplexml_load_string(
  1434. $this->securityScanner->scan(
  1435. $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
  1436. ),
  1437. 'SimpleXMLElement',
  1438. Settings::getLibXmlLoaderOptions()
  1439. );
  1440. $images = [];
  1441. $hyperlinks = [];
  1442. if ($relsDrawing && $relsDrawing->Relationship) {
  1443. foreach ($relsDrawing->Relationship as $ele) {
  1444. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
  1445. $hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
  1446. }
  1447. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
  1448. $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
  1449. } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
  1450. if ($this->includeCharts) {
  1451. $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
  1452. 'id' => (string) $ele['Id'],
  1453. 'sheet' => $docSheet->getTitle(),
  1454. ];
  1455. }
  1456. }
  1457. }
  1458. }
  1459. $xmlDrawing = simplexml_load_string(
  1460. $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)),
  1461. 'SimpleXMLElement',
  1462. Settings::getLibXmlLoaderOptions()
  1463. )->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
  1464. if ($xmlDrawing->oneCellAnchor) {
  1465. foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) {
  1466. if ($oneCellAnchor->pic->blipFill) {
  1467. /** @var SimpleXMLElement $blip */
  1468. $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
  1469. /** @var SimpleXMLElement $xfrm */
  1470. $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
  1471. /** @var SimpleXMLElement $outerShdw */
  1472. $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
  1473. /** @var \SimpleXMLElement $hlinkClick */
  1474. $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
  1475. $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  1476. $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
  1477. $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
  1478. $objDrawing->setPath(
  1479. 'zip://' . File::realpath($pFilename) . '#' .
  1480. $images[(string) self::getArrayItem(
  1481. $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
  1482. 'embed'
  1483. )],
  1484. false
  1485. );
  1486. $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
  1487. $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
  1488. $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
  1489. $objDrawing->setResizeProportional(false);
  1490. $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
  1491. $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
  1492. if ($xfrm) {
  1493. $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
  1494. }
  1495. if ($outerShdw) {
  1496. $shadow = $objDrawing->getShadow();
  1497. $shadow->setVisible(true);
  1498. $shadow->setBlurRadius(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
  1499. $shadow->setDistance(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
  1500. $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
  1501. $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
  1502. $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), 'val'));
  1503. $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), 'val') / 1000);
  1504. }
  1505. $this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks);
  1506. $objDrawing->setWorksheet($docSheet);
  1507. } else {
  1508. // ? Can charts be positioned with a oneCellAnchor ?
  1509. $coordinates = Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1);
  1510. $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff);
  1511. $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
  1512. $width = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx'));
  1513. $height = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy'));
  1514. }
  1515. }
  1516. }
  1517. if ($xmlDrawing->twoCellAnchor) {
  1518. foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) {
  1519. if ($twoCellAnchor->pic->blipFill) {
  1520. $blip = $twoCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
  1521. $xfrm = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
  1522. $outerShdw = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
  1523. $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
  1524. $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  1525. $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
  1526. $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
  1527. $objDrawing->setPath(
  1528. 'zip://' . File::realpath($pFilename) . '#' .
  1529. $images[(string) self::getArrayItem(
  1530. $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
  1531. 'embed'
  1532. )],
  1533. false
  1534. );
  1535. $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1));
  1536. $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff));
  1537. $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
  1538. $objDrawing->setResizeProportional(false);
  1539. if ($xfrm) {
  1540. $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cx')));
  1541. $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cy')));
  1542. $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
  1543. }
  1544. if ($outerShdw) {
  1545. $shadow = $objDrawing->getShadow();
  1546. $shadow->setVisible(true);
  1547. $shadow->setBlurRadius(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
  1548. $shadow->setDistance(Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
  1549. $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
  1550. $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
  1551. $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), 'val'));
  1552. $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), 'val') / 1000);
  1553. }
  1554. $this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks);
  1555. $objDrawing->setWorksheet($docSheet);
  1556. } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
  1557. $fromCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
  1558. $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff);
  1559. $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
  1560. $toCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
  1561. $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff);
  1562. $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
  1563. $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic;
  1564. /** @var SimpleXMLElement $chartRef */
  1565. $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart;
  1566. $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
  1567. $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
  1568. 'fromCoordinate' => $fromCoordinate,
  1569. 'fromOffsetX' => $fromOffsetX,
  1570. 'fromOffsetY' => $fromOffsetY,
  1571. 'toCoordinate' => $toCoordinate,
  1572. 'toOffsetX' => $toOffsetX,
  1573. 'toOffsetY' => $toOffsetY,
  1574. 'worksheetTitle' => $docSheet->getTitle(),
  1575. ];
  1576. }
  1577. }
  1578. }
  1579. }
  1580. // store original rId of drawing files
  1581. $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = [];
  1582. foreach ($relsWorksheet->Relationship as $ele) {
  1583. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
  1584. $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = (string) $ele['Id'];
  1585. }
  1586. }
  1587. // unparsed drawing AlternateContent
  1588. $xmlAltDrawing = simplexml_load_string(
  1589. $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)),
  1590. 'SimpleXMLElement',
  1591. Settings::getLibXmlLoaderOptions()
  1592. )->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
  1593. if ($xmlAltDrawing->AlternateContent) {
  1594. foreach ($xmlAltDrawing->AlternateContent as $alternateContent) {
  1595. $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML();
  1596. }
  1597. }
  1598. }
  1599. }
  1600. $this->readFormControlProperties($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
  1601. $this->readPrinterSettings($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
  1602. // Loop through definedNames
  1603. if ($xmlWorkbook->definedNames) {
  1604. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1605. // Extract range
  1606. $extractedRange = (string) $definedName;
  1607. if (($spos = strpos($extractedRange, '!')) !== false) {
  1608. $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
  1609. } else {
  1610. $extractedRange = str_replace('$', '', $extractedRange);
  1611. }
  1612. // Valid range?
  1613. if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') {
  1614. continue;
  1615. }
  1616. // Some definedNames are only applicable if we are on the same sheet...
  1617. if ((string) $definedName['localSheetId'] != '' && (string) $definedName['localSheetId'] == $oldSheetId) {
  1618. // Switch on type
  1619. switch ((string) $definedName['name']) {
  1620. case '_xlnm._FilterDatabase':
  1621. if ((string) $definedName['hidden'] !== '1') {
  1622. $extractedRange = explode(',', $extractedRange);
  1623. foreach ($extractedRange as $range) {
  1624. $autoFilterRange = $range;
  1625. if (strpos($autoFilterRange, ':') !== false) {
  1626. $docSheet->getAutoFilter()->setRange($autoFilterRange);
  1627. }
  1628. }
  1629. }
  1630. break;
  1631. case '_xlnm.Print_Titles':
  1632. // Split $extractedRange
  1633. $extractedRange = explode(',', $extractedRange);
  1634. // Set print titles
  1635. foreach ($extractedRange as $range) {
  1636. $matches = [];
  1637. $range = str_replace('$', '', $range);
  1638. // check for repeating columns, e g. 'A:A' or 'A:D'
  1639. if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) {
  1640. $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$matches[1], $matches[2]]);
  1641. } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) {
  1642. // check for repeating rows, e.g. '1:1' or '1:5'
  1643. $docSheet->getPageSetup()->setRowsToRepeatAtTop([$matches[1], $matches[2]]);
  1644. }
  1645. }
  1646. break;
  1647. case '_xlnm.Print_Area':
  1648. $rangeSets = preg_split("/('?(?:.*?)'?(?:![A-Z0-9]+:[A-Z0-9]+)),?/", $extractedRange, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  1649. $newRangeSets = [];
  1650. foreach ($rangeSets as $rangeSet) {
  1651. list($sheetName, $rangeSet) = Worksheet::extractSheetTitle($rangeSet, true);
  1652. if (strpos($rangeSet, ':') === false) {
  1653. $rangeSet = $rangeSet . ':' . $rangeSet;
  1654. }
  1655. $newRangeSets[] = str_replace('$', '', $rangeSet);
  1656. }
  1657. $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets));
  1658. break;
  1659. default:
  1660. break;
  1661. }
  1662. }
  1663. }
  1664. }
  1665. // Next sheet id
  1666. ++$sheetId;
  1667. }
  1668. // Loop through definedNames
  1669. if ($xmlWorkbook->definedNames) {
  1670. foreach ($xmlWorkbook->definedNames->definedName as $definedName) {
  1671. // Extract range
  1672. $extractedRange = (string) $definedName;
  1673. if (($spos = strpos($extractedRange, '!')) !== false) {
  1674. $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos));
  1675. } else {
  1676. $extractedRange = str_replace('$', '', $extractedRange);
  1677. }
  1678. // Valid range?
  1679. if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') {
  1680. continue;
  1681. }
  1682. // Some definedNames are only applicable if we are on the same sheet...
  1683. if ((string) $definedName['localSheetId'] != '') {
  1684. // Local defined name
  1685. // Switch on type
  1686. switch ((string) $definedName['name']) {
  1687. case '_xlnm._FilterDatabase':
  1688. case '_xlnm.Print_Titles':
  1689. case '_xlnm.Print_Area':
  1690. break;
  1691. default:
  1692. if ($mapSheetId[(int) $definedName['localSheetId']] !== null) {
  1693. if (strpos((string) $definedName, '!') !== false) {
  1694. $range = Worksheet::extractSheetTitle((string) $definedName, true);
  1695. $range[0] = str_replace("''", "'", $range[0]);
  1696. $range[0] = str_replace("'", '', $range[0]);
  1697. if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) {
  1698. $extractedRange = str_replace('$', '', $range[1]);
  1699. $scope = $docSheet->getParent()->getSheet($mapSheetId[(int) $definedName['localSheetId']]);
  1700. $excel->addNamedRange(new NamedRange((string) $definedName['name'], $worksheet, $extractedRange, true, $scope));
  1701. }
  1702. }
  1703. }
  1704. break;
  1705. }
  1706. } elseif (!isset($definedName['localSheetId'])) {
  1707. // "Global" definedNames
  1708. $locatedSheet = null;
  1709. $extractedSheetName = '';
  1710. if (strpos((string) $definedName, '!') !== false) {
  1711. // Extract sheet name
  1712. $extractedSheetName = Worksheet::extractSheetTitle((string) $definedName, true);
  1713. $extractedSheetName = $extractedSheetName[0];
  1714. // Locate sheet
  1715. $locatedSheet = $excel->getSheetByName($extractedSheetName);
  1716. // Modify range
  1717. list($worksheetName, $extractedRange) = Worksheet::extractSheetTitle($extractedRange, true);
  1718. }
  1719. if ($locatedSheet !== null) {
  1720. $excel->addNamedRange(new NamedRange((string) $definedName['name'], $locatedSheet, $extractedRange, false));
  1721. }
  1722. }
  1723. }
  1724. }
  1725. }
  1726. if ((!$this->readDataOnly) || (!empty($this->loadSheetsOnly))) {
  1727. $workbookView = $xmlWorkbook->bookViews->workbookView;
  1728. // active sheet index
  1729. $activeTab = (int) ($workbookView['activeTab']); // refers to old sheet index
  1730. // keep active sheet index if sheet is still loaded, else first sheet is set as the active
  1731. if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
  1732. $excel->setActiveSheetIndex($mapSheetId[$activeTab]);
  1733. } else {
  1734. if ($excel->getSheetCount() == 0) {
  1735. $excel->createSheet();
  1736. }
  1737. $excel->setActiveSheetIndex(0);
  1738. }
  1739. if (isset($workbookView['showHorizontalScroll'])) {
  1740. $showHorizontalScroll = (string) $workbookView['showHorizontalScroll'];
  1741. $excel->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll));
  1742. }
  1743. if (isset($workbookView['showVerticalScroll'])) {
  1744. $showVerticalScroll = (string) $workbookView['showVerticalScroll'];
  1745. $excel->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll));
  1746. }
  1747. if (isset($workbookView['showSheetTabs'])) {
  1748. $showSheetTabs = (string) $workbookView['showSheetTabs'];
  1749. $excel->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs));
  1750. }
  1751. if (isset($workbookView['minimized'])) {
  1752. $minimized = (string) $workbookView['minimized'];
  1753. $excel->setMinimized($this->castXsdBooleanToBool($minimized));
  1754. }
  1755. if (isset($workbookView['autoFilterDateGrouping'])) {
  1756. $autoFilterDateGrouping = (string) $workbookView['autoFilterDateGrouping'];
  1757. $excel->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping));
  1758. }
  1759. if (isset($workbookView['firstSheet'])) {
  1760. $firstSheet = (string) $workbookView['firstSheet'];
  1761. $excel->setFirstSheetIndex((int) $firstSheet);
  1762. }
  1763. if (isset($workbookView['visibility'])) {
  1764. $visibility = (string) $workbookView['visibility'];
  1765. $excel->setVisibility($visibility);
  1766. }
  1767. if (isset($workbookView['tabRatio'])) {
  1768. $tabRatio = (string) $workbookView['tabRatio'];
  1769. $excel->setTabRatio((int) $tabRatio);
  1770. }
  1771. }
  1772. break;
  1773. }
  1774. }
  1775. if (!$this->readDataOnly) {
  1776. $contentTypes = simplexml_load_string(
  1777. $this->securityScanner->scan(
  1778. $this->getFromZipArchive($zip, '[Content_Types].xml')
  1779. ),
  1780. 'SimpleXMLElement',
  1781. Settings::getLibXmlLoaderOptions()
  1782. );
  1783. // Default content types
  1784. foreach ($contentTypes->Default as $contentType) {
  1785. switch ($contentType['ContentType']) {
  1786. case 'application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings':
  1787. $unparsedLoadedData['default_content_types'][(string) $contentType['Extension']] = (string) $contentType['ContentType'];
  1788. break;
  1789. }
  1790. }
  1791. // Override content types
  1792. foreach ($contentTypes->Override as $contentType) {
  1793. switch ($contentType['ContentType']) {
  1794. case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
  1795. if ($this->includeCharts) {
  1796. $chartEntryRef = ltrim($contentType['PartName'], '/');
  1797. $chartElements = simplexml_load_string(
  1798. $this->securityScanner->scan(
  1799. $this->getFromZipArchive($zip, $chartEntryRef)
  1800. ),
  1801. 'SimpleXMLElement',
  1802. Settings::getLibXmlLoaderOptions()
  1803. );
  1804. $objChart = Chart::readChart($chartElements, basename($chartEntryRef, '.xml'));
  1805. if (isset($charts[$chartEntryRef])) {
  1806. $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
  1807. if (isset($chartDetails[$chartPositionRef])) {
  1808. $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
  1809. $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
  1810. $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
  1811. $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
  1812. }
  1813. }
  1814. }
  1815. break;
  1816. // unparsed
  1817. case 'application/vnd.ms-excel.controlproperties+xml':
  1818. $unparsedLoadedData['override_content_types'][(string) $contentType['PartName']] = (string) $contentType['ContentType'];
  1819. break;
  1820. }
  1821. }
  1822. }
  1823. $excel->setUnparsedLoadedData($unparsedLoadedData);
  1824. $zip->close();
  1825. return $excel;
  1826. }
  1827. private static function readColor($color, $background = false)
  1828. {
  1829. if (isset($color['rgb'])) {
  1830. return (string) $color['rgb'];
  1831. } elseif (isset($color['indexed'])) {
  1832. return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
  1833. } elseif (isset($color['theme'])) {
  1834. if (self::$theme !== null) {
  1835. $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
  1836. if (isset($color['tint'])) {
  1837. $tintAdjust = (float) $color['tint'];
  1838. $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
  1839. }
  1840. return 'FF' . $returnColour;
  1841. }
  1842. }
  1843. if ($background) {
  1844. return 'FFFFFFFF';
  1845. }
  1846. return 'FF000000';
  1847. }
  1848. /**
  1849. * @param Style $docStyle
  1850. * @param SimpleXMLElement|\stdClass $style
  1851. */
  1852. private static function readStyle(Style $docStyle, $style)
  1853. {
  1854. $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
  1855. // font
  1856. if (isset($style->font)) {
  1857. $docStyle->getFont()->setName((string) $style->font->name['val']);
  1858. $docStyle->getFont()->setSize((string) $style->font->sz['val']);
  1859. if (isset($style->font->b)) {
  1860. $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val']));
  1861. }
  1862. if (isset($style->font->i)) {
  1863. $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val']));
  1864. }
  1865. if (isset($style->font->strike)) {
  1866. $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val']));
  1867. }
  1868. $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color));
  1869. if (isset($style->font->u) && !isset($style->font->u['val'])) {
  1870. $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
  1871. } elseif (isset($style->font->u, $style->font->u['val'])) {
  1872. $docStyle->getFont()->setUnderline((string) $style->font->u['val']);
  1873. }
  1874. if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) {
  1875. $vertAlign = strtolower((string) $style->font->vertAlign['val']);
  1876. if ($vertAlign == 'superscript') {
  1877. $docStyle->getFont()->setSuperscript(true);
  1878. }
  1879. if ($vertAlign == 'subscript') {
  1880. $docStyle->getFont()->setSubscript(true);
  1881. }
  1882. }
  1883. }
  1884. // fill
  1885. if (isset($style->fill)) {
  1886. if ($style->fill->gradientFill) {
  1887. /** @var SimpleXMLElement $gradientFill */
  1888. $gradientFill = $style->fill->gradientFill[0];
  1889. if (!empty($gradientFill['type'])) {
  1890. $docStyle->getFill()->setFillType((string) $gradientFill['type']);
  1891. }
  1892. $docStyle->getFill()->setRotation((float) ($gradientFill['degree']));
  1893. $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
  1894. $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
  1895. $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
  1896. } elseif ($style->fill->patternFill) {
  1897. $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid';
  1898. $docStyle->getFill()->setFillType($patternType);
  1899. if ($style->fill->patternFill->fgColor) {
  1900. $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true));
  1901. } else {
  1902. $docStyle->getFill()->getStartColor()->setARGB('FF000000');
  1903. }
  1904. if ($style->fill->patternFill->bgColor) {
  1905. $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true));
  1906. }
  1907. }
  1908. }
  1909. // border
  1910. if (isset($style->border)) {
  1911. $diagonalUp = self::boolean((string) $style->border['diagonalUp']);
  1912. $diagonalDown = self::boolean((string) $style->border['diagonalDown']);
  1913. if (!$diagonalUp && !$diagonalDown) {
  1914. $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
  1915. } elseif ($diagonalUp && !$diagonalDown) {
  1916. $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
  1917. } elseif (!$diagonalUp && $diagonalDown) {
  1918. $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
  1919. } else {
  1920. $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
  1921. }
  1922. self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
  1923. self::readBorder($docStyle->getBorders()->getRight(), $style->border->right);
  1924. self::readBorder($docStyle->getBorders()->getTop(), $style->border->top);
  1925. self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
  1926. self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
  1927. }
  1928. // alignment
  1929. if (isset($style->alignment)) {
  1930. $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']);
  1931. $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']);
  1932. $textRotation = 0;
  1933. if ((int) $style->alignment['textRotation'] <= 90) {
  1934. $textRotation = (int) $style->alignment['textRotation'];
  1935. } elseif ((int) $style->alignment['textRotation'] > 90) {
  1936. $textRotation = 90 - (int) $style->alignment['textRotation'];
  1937. }
  1938. $docStyle->getAlignment()->setTextRotation((int) $textRotation);
  1939. $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText']));
  1940. $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit']));
  1941. $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0);
  1942. $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0);
  1943. }
  1944. // protection
  1945. if (isset($style->protection)) {
  1946. if (isset($style->protection['locked'])) {
  1947. if (self::boolean((string) $style->protection['locked'])) {
  1948. $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
  1949. } else {
  1950. $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
  1951. }
  1952. }
  1953. if (isset($style->protection['hidden'])) {
  1954. if (self::boolean((string) $style->protection['hidden'])) {
  1955. $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
  1956. } else {
  1957. $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
  1958. }
  1959. }
  1960. }
  1961. // top-level style settings
  1962. if (isset($style->quotePrefix)) {
  1963. $docStyle->setQuotePrefix($style->quotePrefix);
  1964. }
  1965. }
  1966. /**
  1967. * @param Border $docBorder
  1968. * @param SimpleXMLElement $eleBorder
  1969. */
  1970. private static function readBorder(Border $docBorder, $eleBorder)
  1971. {
  1972. if (isset($eleBorder['style'])) {
  1973. $docBorder->setBorderStyle((string) $eleBorder['style']);
  1974. }
  1975. if (isset($eleBorder->color)) {
  1976. $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
  1977. }
  1978. }
  1979. /**
  1980. * @param SimpleXMLElement | null $is
  1981. *
  1982. * @return RichText
  1983. */
  1984. private function parseRichText($is)
  1985. {
  1986. $value = new RichText();
  1987. if (isset($is->t)) {
  1988. $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
  1989. } else {
  1990. if (is_object($is->r)) {
  1991. foreach ($is->r as $run) {
  1992. if (!isset($run->rPr)) {
  1993. $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
  1994. } else {
  1995. $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
  1996. if (isset($run->rPr->rFont['val'])) {
  1997. $objText->getFont()->setName((string) $run->rPr->rFont['val']);
  1998. }
  1999. if (isset($run->rPr->sz['val'])) {
  2000. $objText->getFont()->setSize((float) $run->rPr->sz['val']);
  2001. }
  2002. if (isset($run->rPr->color)) {
  2003. $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
  2004. }
  2005. if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
  2006. (isset($run->rPr->b) && !isset($run->rPr->b['val']))) {
  2007. $objText->getFont()->setBold(true);
  2008. }
  2009. if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
  2010. (isset($run->rPr->i) && !isset($run->rPr->i['val']))) {
  2011. $objText->getFont()->setItalic(true);
  2012. }
  2013. if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
  2014. $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
  2015. if ($vertAlign == 'superscript') {
  2016. $objText->getFont()->setSuperscript(true);
  2017. }
  2018. if ($vertAlign == 'subscript') {
  2019. $objText->getFont()->setSubscript(true);
  2020. }
  2021. }
  2022. if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
  2023. $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
  2024. } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
  2025. $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
  2026. }
  2027. if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
  2028. (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) {
  2029. $objText->getFont()->setStrikethrough(true);
  2030. }
  2031. }
  2032. }
  2033. }
  2034. }
  2035. return $value;
  2036. }
  2037. /**
  2038. * @param Spreadsheet $excel
  2039. * @param mixed $customUITarget
  2040. * @param mixed $zip
  2041. */
  2042. private function readRibbon(Spreadsheet $excel, $customUITarget, $zip)
  2043. {
  2044. $baseDir = dirname($customUITarget);
  2045. $nameCustomUI = basename($customUITarget);
  2046. // get the xml file (ribbon)
  2047. $localRibbon = $this->getFromZipArchive($zip, $customUITarget);
  2048. $customUIImagesNames = [];
  2049. $customUIImagesBinaries = [];
  2050. // something like customUI/_rels/customUI.xml.rels
  2051. $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels';
  2052. $dataRels = $this->getFromZipArchive($zip, $pathRels);
  2053. if ($dataRels) {
  2054. // exists and not empty if the ribbon have some pictures (other than internal MSO)
  2055. $UIRels = simplexml_load_string(
  2056. $this->securityScanner->scan($dataRels),
  2057. 'SimpleXMLElement',
  2058. Settings::getLibXmlLoaderOptions()
  2059. );
  2060. if (false !== $UIRels) {
  2061. // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
  2062. foreach ($UIRels->Relationship as $ele) {
  2063. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
  2064. // an image ?
  2065. $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
  2066. $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
  2067. }
  2068. }
  2069. }
  2070. }
  2071. if ($localRibbon) {
  2072. $excel->setRibbonXMLData($customUITarget, $localRibbon);
  2073. if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) {
  2074. $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries);
  2075. } else {
  2076. $excel->setRibbonBinObjects(null, null);
  2077. }
  2078. } else {
  2079. $excel->setRibbonXMLData(null, null);
  2080. $excel->setRibbonBinObjects(null, null);
  2081. }
  2082. }
  2083. private static function getArrayItem($array, $key = 0)
  2084. {
  2085. return isset($array[$key]) ? $array[$key] : null;
  2086. }
  2087. private static function dirAdd($base, $add)
  2088. {
  2089. return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add");
  2090. }
  2091. private static function toCSSArray($style)
  2092. {
  2093. $style = trim(str_replace(["\r", "\n"], '', $style), ';');
  2094. $temp = explode(';', $style);
  2095. $style = [];
  2096. foreach ($temp as $item) {
  2097. $item = explode(':', $item);
  2098. if (strpos($item[1], 'px') !== false) {
  2099. $item[1] = str_replace('px', '', $item[1]);
  2100. }
  2101. if (strpos($item[1], 'pt') !== false) {
  2102. $item[1] = str_replace('pt', '', $item[1]);
  2103. $item[1] = Font::fontSizeToPixels($item[1]);
  2104. }
  2105. if (strpos($item[1], 'in') !== false) {
  2106. $item[1] = str_replace('in', '', $item[1]);
  2107. $item[1] = Font::inchSizeToPixels($item[1]);
  2108. }
  2109. if (strpos($item[1], 'cm') !== false) {
  2110. $item[1] = str_replace('cm', '', $item[1]);
  2111. $item[1] = Font::centimeterSizeToPixels($item[1]);
  2112. }
  2113. $style[$item[0]] = $item[1];
  2114. }
  2115. return $style;
  2116. }
  2117. private static function boolean($value)
  2118. {
  2119. if (is_object($value)) {
  2120. $value = (string) $value;
  2121. }
  2122. if (is_numeric($value)) {
  2123. return (bool) $value;
  2124. }
  2125. return $value === 'true' || $value === 'TRUE';
  2126. }
  2127. /**
  2128. * @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing
  2129. * @param \SimpleXMLElement $cellAnchor
  2130. * @param array $hyperlinks
  2131. */
  2132. private function readHyperLinkDrawing($objDrawing, $cellAnchor, $hyperlinks)
  2133. {
  2134. $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
  2135. if ($hlinkClick->count() === 0) {
  2136. return;
  2137. }
  2138. $hlinkId = (string) $hlinkClick->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id'];
  2139. $hyperlink = new Hyperlink(
  2140. $hyperlinks[$hlinkId],
  2141. (string) self::getArrayItem($cellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')
  2142. );
  2143. $objDrawing->setHyperlink($hyperlink);
  2144. }
  2145. private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook)
  2146. {
  2147. if (!$xmlWorkbook->workbookProtection) {
  2148. return;
  2149. }
  2150. if ($xmlWorkbook->workbookProtection['lockRevision']) {
  2151. $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']);
  2152. }
  2153. if ($xmlWorkbook->workbookProtection['lockStructure']) {
  2154. $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']);
  2155. }
  2156. if ($xmlWorkbook->workbookProtection['lockWindows']) {
  2157. $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']);
  2158. }
  2159. if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
  2160. $excel->getSecurity()->setRevisionsPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true);
  2161. }
  2162. if ($xmlWorkbook->workbookProtection['workbookPassword']) {
  2163. $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true);
  2164. }
  2165. }
  2166. private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
  2167. {
  2168. if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
  2169. return;
  2170. }
  2171. //~ http://schemas.openxmlformats.org/package/2006/relationships"
  2172. $relsWorksheet = simplexml_load_string(
  2173. $this->securityScanner->scan(
  2174. $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
  2175. ),
  2176. 'SimpleXMLElement',
  2177. Settings::getLibXmlLoaderOptions()
  2178. );
  2179. $ctrlProps = [];
  2180. foreach ($relsWorksheet->Relationship as $ele) {
  2181. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') {
  2182. $ctrlProps[(string) $ele['Id']] = $ele;
  2183. }
  2184. }
  2185. $unparsedCtrlProps = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['ctrlProps'];
  2186. foreach ($ctrlProps as $rId => $ctrlProp) {
  2187. $rId = substr($rId, 3); // rIdXXX
  2188. $unparsedCtrlProps[$rId] = [];
  2189. $unparsedCtrlProps[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $ctrlProp['Target']);
  2190. $unparsedCtrlProps[$rId]['relFilePath'] = (string) $ctrlProp['Target'];
  2191. $unparsedCtrlProps[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedCtrlProps[$rId]['filePath']));
  2192. }
  2193. unset($unparsedCtrlProps);
  2194. }
  2195. private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData)
  2196. {
  2197. if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
  2198. return;
  2199. }
  2200. //~ http://schemas.openxmlformats.org/package/2006/relationships"
  2201. $relsWorksheet = simplexml_load_string(
  2202. $this->securityScanner->scan(
  2203. $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
  2204. ),
  2205. 'SimpleXMLElement',
  2206. Settings::getLibXmlLoaderOptions()
  2207. );
  2208. $sheetPrinterSettings = [];
  2209. foreach ($relsWorksheet->Relationship as $ele) {
  2210. if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') {
  2211. $sheetPrinterSettings[(string) $ele['Id']] = $ele;
  2212. }
  2213. }
  2214. $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings'];
  2215. foreach ($sheetPrinterSettings as $rId => $printerSettings) {
  2216. $rId = substr($rId, 3); // rIdXXX
  2217. $unparsedPrinterSettings[$rId] = [];
  2218. $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']);
  2219. $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target'];
  2220. $unparsedPrinterSettings[$rId]['content'] = $this->securityScanner->scan($this->getFromZipArchive($zip, $unparsedPrinterSettings[$rId]['filePath']));
  2221. }
  2222. unset($unparsedPrinterSettings);
  2223. }
  2224. /**
  2225. * Convert an 'xsd:boolean' XML value to a PHP boolean value.
  2226. * A valid 'xsd:boolean' XML value can be one of the following
  2227. * four values: 'true', 'false', '1', '0'. It is case sensitive.
  2228. *
  2229. * Note that just doing '(bool) $xsdBoolean' is not safe,
  2230. * since '(bool) "false"' returns true.
  2231. *
  2232. * @see https://www.w3.org/TR/xmlschema11-2/#boolean
  2233. *
  2234. * @param string $xsdBoolean An XML string value of type 'xsd:boolean'
  2235. *
  2236. * @return bool Boolean value
  2237. */
  2238. private function castXsdBooleanToBool($xsdBoolean)
  2239. {
  2240. if ($xsdBoolean === 'false') {
  2241. return false;
  2242. }
  2243. return (bool) $xsdBoolean;
  2244. }
  2245. /**
  2246. * Read columns and rows attributes from XML and set them on the worksheet.
  2247. *
  2248. * @param SimpleXMLElement $xmlSheet
  2249. * @param Worksheet $docSheet
  2250. */
  2251. private function readColumnsAndRowsAttributes(SimpleXMLElement $xmlSheet, Worksheet $docSheet)
  2252. {
  2253. $columnsAttributes = [];
  2254. $rowsAttributes = [];
  2255. if (isset($xmlSheet->cols) && !$this->readDataOnly) {
  2256. foreach ($xmlSheet->cols->col as $col) {
  2257. for ($i = (int) ($col['min']); $i <= (int) ($col['max']); ++$i) {
  2258. if ($col['style'] && !$this->readDataOnly) {
  2259. $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['xfIndex'] = (int) $col['style'];
  2260. }
  2261. if (self::boolean($col['hidden'])) {
  2262. $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['visible'] = false;
  2263. }
  2264. if (self::boolean($col['collapsed'])) {
  2265. $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['collapsed'] = true;
  2266. }
  2267. if ($col['outlineLevel'] > 0) {
  2268. $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['outlineLevel'] = (int) $col['outlineLevel'];
  2269. }
  2270. $columnsAttributes[Coordinate::stringFromColumnIndex($i)]['width'] = (float) $col['width'];
  2271. if ((int) ($col['max']) == 16384) {
  2272. break;
  2273. }
  2274. }
  2275. }
  2276. }
  2277. if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
  2278. foreach ($xmlSheet->sheetData->row as $row) {
  2279. if ($row['ht'] && !$this->readDataOnly) {
  2280. $rowsAttributes[(int) $row['r']]['rowHeight'] = (float) $row['ht'];
  2281. }
  2282. if (self::boolean($row['hidden']) && !$this->readDataOnly) {
  2283. $rowsAttributes[(int) $row['r']]['visible'] = false;
  2284. }
  2285. if (self::boolean($row['collapsed'])) {
  2286. $rowsAttributes[(int) $row['r']]['collapsed'] = true;
  2287. }
  2288. if ($row['outlineLevel'] > 0) {
  2289. $rowsAttributes[(int) $row['r']]['outlineLevel'] = (int) $row['outlineLevel'];
  2290. }
  2291. if ($row['s'] && !$this->readDataOnly) {
  2292. $rowsAttributes[(int) $row['r']]['xfIndex'] = (int) $row['s'];
  2293. }
  2294. }
  2295. }
  2296. $readFilter = (\get_class($this->getReadFilter()) !== DefaultReadFilter::class ? $this->getReadFilter() : null);
  2297. // set columns/rows attributes
  2298. $columnsAttributesSet = [];
  2299. $rowsAttributesSet = [];
  2300. foreach ($columnsAttributes as $coordColumn => $columnAttributes) {
  2301. if ($readFilter !== null) {
  2302. foreach ($rowsAttributes as $coordRow => $rowAttributes) {
  2303. if (!$readFilter->readCell($coordColumn, $coordRow, $docSheet->getTitle())) {
  2304. continue 2;
  2305. }
  2306. }
  2307. }
  2308. if (!isset($columnsAttributesSet[$coordColumn])) {
  2309. $this->setColumnAttributes($docSheet, $coordColumn, $columnAttributes);
  2310. $columnsAttributesSet[$coordColumn] = true;
  2311. }
  2312. }
  2313. foreach ($rowsAttributes as $coordRow => $rowAttributes) {
  2314. if ($readFilter !== null) {
  2315. foreach ($columnsAttributes as $coordColumn => $columnAttributes) {
  2316. if (!$readFilter->readCell($coordColumn, $coordRow, $docSheet->getTitle())) {
  2317. continue 2;
  2318. }
  2319. }
  2320. }
  2321. if (!isset($rowsAttributesSet[$coordRow])) {
  2322. $this->setRowAttributes($docSheet, $coordRow, $rowAttributes);
  2323. $rowsAttributesSet[$coordRow] = true;
  2324. }
  2325. }
  2326. }
  2327. }