Xlsx.php 115 KB

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