7f8683e3b655ad4dcfc075af96f57545c8cdd493.svn-base 96 KB

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