Excel2007.php 134 KB

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