OLE.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2002 The PHP Group |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available at through the world-wide-web at |
  11. // | http://www.php.net/license/2_02.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | license@php.net so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Author: Xavier Noguer <xnoguer@php.net> |
  17. // | Based on OLE::Storage_Lite by Kawai, Takanori |
  18. // +----------------------------------------------------------------------+
  19. //
  20. // $Id: OLE.php,v 1.13 2007/03/07 14:38:25 schmidt Exp $
  21. /**
  22. * Array for storing OLE instances that are accessed from
  23. * OLE_ChainedBlockStream::stream_open().
  24. * @var array
  25. */
  26. $GLOBALS['_OLE_INSTANCES'] = array();
  27. /**
  28. * OLE package base class.
  29. *
  30. * @author Xavier Noguer <xnoguer@php.net>
  31. * @author Christian Schmidt <schmidt@php.net>
  32. * @category PHPExcel
  33. * @package PHPExcel_Shared_OLE
  34. */
  35. class PHPExcel_Shared_OLE
  36. {
  37. const OLE_PPS_TYPE_ROOT = 5;
  38. const OLE_PPS_TYPE_DIR = 1;
  39. const OLE_PPS_TYPE_FILE = 2;
  40. const OLE_DATA_SIZE_SMALL = 0x1000;
  41. const OLE_LONG_INT_SIZE = 4;
  42. const OLE_PPS_SIZE = 0x80;
  43. /**
  44. * The file handle for reading an OLE container
  45. * @var resource
  46. */
  47. public $_file_handle;
  48. /**
  49. * Array of PPS's found on the OLE container
  50. * @var array
  51. */
  52. public $_list = array();
  53. /**
  54. * Root directory of OLE container
  55. * @var OLE_PPS_Root
  56. */
  57. public $root;
  58. /**
  59. * Big Block Allocation Table
  60. * @var array (blockId => nextBlockId)
  61. */
  62. public $bbat;
  63. /**
  64. * Short Block Allocation Table
  65. * @var array (blockId => nextBlockId)
  66. */
  67. public $sbat;
  68. /**
  69. * Size of big blocks. This is usually 512.
  70. * @var int number of octets per block.
  71. */
  72. public $bigBlockSize;
  73. /**
  74. * Size of small blocks. This is usually 64.
  75. * @var int number of octets per block
  76. */
  77. public $smallBlockSize;
  78. /**
  79. * Reads an OLE container from the contents of the file given.
  80. *
  81. * @acces public
  82. * @param string $file
  83. * @return mixed true on success, PEAR_Error on failure
  84. */
  85. public function read($file)
  86. {
  87. $fh = fopen($file, "r");
  88. if (!$fh) {
  89. throw new PHPExcel_Reader_Exception("Can't open file $file");
  90. }
  91. $this->_file_handle = $fh;
  92. $signature = fread($fh, 8);
  93. if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) {
  94. throw new PHPExcel_Reader_Exception("File doesn't seem to be an OLE container.");
  95. }
  96. fseek($fh, 28);
  97. if (fread($fh, 2) != "\xFE\xFF") {
  98. // This shouldn't be a problem in practice
  99. throw new PHPExcel_Reader_Exception("Only Little-Endian encoding is supported.");
  100. }
  101. // Size of blocks and short blocks in bytes
  102. $this->bigBlockSize = pow(2, self::_readInt2($fh));
  103. $this->smallBlockSize = pow(2, self::_readInt2($fh));
  104. // Skip UID, revision number and version number
  105. fseek($fh, 44);
  106. // Number of blocks in Big Block Allocation Table
  107. $bbatBlockCount = self::_readInt4($fh);
  108. // Root chain 1st block
  109. $directoryFirstBlockId = self::_readInt4($fh);
  110. // Skip unused bytes
  111. fseek($fh, 56);
  112. // Streams shorter than this are stored using small blocks
  113. $this->bigBlockThreshold = self::_readInt4($fh);
  114. // Block id of first sector in Short Block Allocation Table
  115. $sbatFirstBlockId = self::_readInt4($fh);
  116. // Number of blocks in Short Block Allocation Table
  117. $sbbatBlockCount = self::_readInt4($fh);
  118. // Block id of first sector in Master Block Allocation Table
  119. $mbatFirstBlockId = self::_readInt4($fh);
  120. // Number of blocks in Master Block Allocation Table
  121. $mbbatBlockCount = self::_readInt4($fh);
  122. $this->bbat = array();
  123. // Remaining 4 * 109 bytes of current block is beginning of Master
  124. // Block Allocation Table
  125. $mbatBlocks = array();
  126. for ($i = 0; $i < 109; ++$i) {
  127. $mbatBlocks[] = self::_readInt4($fh);
  128. }
  129. // Read rest of Master Block Allocation Table (if any is left)
  130. $pos = $this->_getBlockOffset($mbatFirstBlockId);
  131. for ($i = 0; $i < $mbbatBlockCount; ++$i) {
  132. fseek($fh, $pos);
  133. for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) {
  134. $mbatBlocks[] = self::_readInt4($fh);
  135. }
  136. // Last block id in each block points to next block
  137. $pos = $this->_getBlockOffset(self::_readInt4($fh));
  138. }
  139. // Read Big Block Allocation Table according to chain specified by
  140. // $mbatBlocks
  141. for ($i = 0; $i < $bbatBlockCount; ++$i) {
  142. $pos = $this->_getBlockOffset($mbatBlocks[$i]);
  143. fseek($fh, $pos);
  144. for ($j = 0 ; $j < $this->bigBlockSize / 4; ++$j) {
  145. $this->bbat[] = self::_readInt4($fh);
  146. }
  147. }
  148. // Read short block allocation table (SBAT)
  149. $this->sbat = array();
  150. $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4;
  151. $sbatFh = $this->getStream($sbatFirstBlockId);
  152. for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) {
  153. $this->sbat[$blockId] = self::_readInt4($sbatFh);
  154. }
  155. fclose($sbatFh);
  156. $this->_readPpsWks($directoryFirstBlockId);
  157. return true;
  158. }
  159. /**
  160. * @param int block id
  161. * @param int byte offset from beginning of file
  162. * @access public
  163. */
  164. public function _getBlockOffset($blockId)
  165. {
  166. return 512 + $blockId * $this->bigBlockSize;
  167. }
  168. /**
  169. * Returns a stream for use with fread() etc. External callers should
  170. * use PHPExcel_Shared_OLE_PPS_File::getStream().
  171. * @param int|PPS block id or PPS
  172. * @return resource read-only stream
  173. */
  174. public function getStream($blockIdOrPps)
  175. {
  176. static $isRegistered = false;
  177. if (!$isRegistered) {
  178. stream_wrapper_register('ole-chainedblockstream',
  179. 'PHPExcel_Shared_OLE_ChainedBlockStream');
  180. $isRegistered = true;
  181. }
  182. // Store current instance in global array, so that it can be accessed
  183. // in OLE_ChainedBlockStream::stream_open().
  184. // Object is removed from self::$instances in OLE_Stream::close().
  185. $GLOBALS['_OLE_INSTANCES'][] = $this;
  186. $instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES']));
  187. $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId;
  188. if ($blockIdOrPps instanceof PHPExcel_Shared_OLE_PPS) {
  189. $path .= '&blockId=' . $blockIdOrPps->_StartBlock;
  190. $path .= '&size=' . $blockIdOrPps->Size;
  191. } else {
  192. $path .= '&blockId=' . $blockIdOrPps;
  193. }
  194. return fopen($path, 'r');
  195. }
  196. /**
  197. * Reads a signed char.
  198. * @param resource file handle
  199. * @return int
  200. * @access public
  201. */
  202. private static function _readInt1($fh)
  203. {
  204. list(, $tmp) = unpack("c", fread($fh, 1));
  205. return $tmp;
  206. }
  207. /**
  208. * Reads an unsigned short (2 octets).
  209. * @param resource file handle
  210. * @return int
  211. * @access public
  212. */
  213. private static function _readInt2($fh)
  214. {
  215. list(, $tmp) = unpack("v", fread($fh, 2));
  216. return $tmp;
  217. }
  218. /**
  219. * Reads an unsigned long (4 octets).
  220. * @param resource file handle
  221. * @return int
  222. * @access public
  223. */
  224. private static function _readInt4($fh)
  225. {
  226. list(, $tmp) = unpack("V", fread($fh, 4));
  227. return $tmp;
  228. }
  229. /**
  230. * Gets information about all PPS's on the OLE container from the PPS WK's
  231. * creates an OLE_PPS object for each one.
  232. *
  233. * @access public
  234. * @param integer the block id of the first block
  235. * @return mixed true on success, PEAR_Error on failure
  236. */
  237. public function _readPpsWks($blockId)
  238. {
  239. $fh = $this->getStream($blockId);
  240. for ($pos = 0; ; $pos += 128) {
  241. fseek($fh, $pos, SEEK_SET);
  242. $nameUtf16 = fread($fh, 64);
  243. $nameLength = self::_readInt2($fh);
  244. $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2);
  245. // Simple conversion from UTF-16LE to ISO-8859-1
  246. $name = str_replace("\x00", "", $nameUtf16);
  247. $type = self::_readInt1($fh);
  248. switch ($type) {
  249. case self::OLE_PPS_TYPE_ROOT:
  250. $pps = new PHPExcel_Shared_OLE_PPS_Root(null, null, array());
  251. $this->root = $pps;
  252. break;
  253. case self::OLE_PPS_TYPE_DIR:
  254. $pps = new PHPExcel_Shared_OLE_PPS(null, null, null, null, null,
  255. null, null, null, null, array());
  256. break;
  257. case self::OLE_PPS_TYPE_FILE:
  258. $pps = new PHPExcel_Shared_OLE_PPS_File($name);
  259. break;
  260. default:
  261. continue;
  262. }
  263. fseek($fh, 1, SEEK_CUR);
  264. $pps->Type = $type;
  265. $pps->Name = $name;
  266. $pps->PrevPps = self::_readInt4($fh);
  267. $pps->NextPps = self::_readInt4($fh);
  268. $pps->DirPps = self::_readInt4($fh);
  269. fseek($fh, 20, SEEK_CUR);
  270. $pps->Time1st = self::OLE2LocalDate(fread($fh, 8));
  271. $pps->Time2nd = self::OLE2LocalDate(fread($fh, 8));
  272. $pps->_StartBlock = self::_readInt4($fh);
  273. $pps->Size = self::_readInt4($fh);
  274. $pps->No = count($this->_list);
  275. $this->_list[] = $pps;
  276. // check if the PPS tree (starting from root) is complete
  277. if (isset($this->root) &&
  278. $this->_ppsTreeComplete($this->root->No)) {
  279. break;
  280. }
  281. }
  282. fclose($fh);
  283. // Initialize $pps->children on directories
  284. foreach ($this->_list as $pps) {
  285. if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) {
  286. $nos = array($pps->DirPps);
  287. $pps->children = array();
  288. while ($nos) {
  289. $no = array_pop($nos);
  290. if ($no != -1) {
  291. $childPps = $this->_list[$no];
  292. $nos[] = $childPps->PrevPps;
  293. $nos[] = $childPps->NextPps;
  294. $pps->children[] = $childPps;
  295. }
  296. }
  297. }
  298. }
  299. return true;
  300. }
  301. /**
  302. * It checks whether the PPS tree is complete (all PPS's read)
  303. * starting with the given PPS (not necessarily root)
  304. *
  305. * @access public
  306. * @param integer $index The index of the PPS from which we are checking
  307. * @return boolean Whether the PPS tree for the given PPS is complete
  308. */
  309. public function _ppsTreeComplete($index)
  310. {
  311. return isset($this->_list[$index]) &&
  312. ($pps = $this->_list[$index]) &&
  313. ($pps->PrevPps == -1 ||
  314. $this->_ppsTreeComplete($pps->PrevPps)) &&
  315. ($pps->NextPps == -1 ||
  316. $this->_ppsTreeComplete($pps->NextPps)) &&
  317. ($pps->DirPps == -1 ||
  318. $this->_ppsTreeComplete($pps->DirPps));
  319. }
  320. /**
  321. * Checks whether a PPS is a File PPS or not.
  322. * If there is no PPS for the index given, it will return false.
  323. *
  324. * @access public
  325. * @param integer $index The index for the PPS
  326. * @return bool true if it's a File PPS, false otherwise
  327. */
  328. public function isFile($index)
  329. {
  330. if (isset($this->_list[$index])) {
  331. return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE);
  332. }
  333. return false;
  334. }
  335. /**
  336. * Checks whether a PPS is a Root PPS or not.
  337. * If there is no PPS for the index given, it will return false.
  338. *
  339. * @access public
  340. * @param integer $index The index for the PPS.
  341. * @return bool true if it's a Root PPS, false otherwise
  342. */
  343. public function isRoot($index)
  344. {
  345. if (isset($this->_list[$index])) {
  346. return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT);
  347. }
  348. return false;
  349. }
  350. /**
  351. * Gives the total number of PPS's found in the OLE container.
  352. *
  353. * @access public
  354. * @return integer The total number of PPS's found in the OLE container
  355. */
  356. public function ppsTotal()
  357. {
  358. return count($this->_list);
  359. }
  360. /**
  361. * Gets data from a PPS
  362. * If there is no PPS for the index given, it will return an empty string.
  363. *
  364. * @access public
  365. * @param integer $index The index for the PPS
  366. * @param integer $position The position from which to start reading
  367. * (relative to the PPS)
  368. * @param integer $length The amount of bytes to read (at most)
  369. * @return string The binary string containing the data requested
  370. * @see OLE_PPS_File::getStream()
  371. */
  372. public function getData($index, $position, $length)
  373. {
  374. // if position is not valid return empty string
  375. if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) {
  376. return '';
  377. }
  378. $fh = $this->getStream($this->_list[$index]);
  379. $data = stream_get_contents($fh, $length, $position);
  380. fclose($fh);
  381. return $data;
  382. }
  383. /**
  384. * Gets the data length from a PPS
  385. * If there is no PPS for the index given, it will return 0.
  386. *
  387. * @access public
  388. * @param integer $index The index for the PPS
  389. * @return integer The amount of bytes in data the PPS has
  390. */
  391. public function getDataLength($index)
  392. {
  393. if (isset($this->_list[$index])) {
  394. return $this->_list[$index]->Size;
  395. }
  396. return 0;
  397. }
  398. /**
  399. * Utility function to transform ASCII text to Unicode
  400. *
  401. * @access public
  402. * @static
  403. * @param string $ascii The ASCII string to transform
  404. * @return string The string in Unicode
  405. */
  406. public static function Asc2Ucs($ascii)
  407. {
  408. $rawname = '';
  409. for ($i = 0; $i < strlen($ascii); ++$i) {
  410. $rawname .= $ascii{$i} . "\x00";
  411. }
  412. return $rawname;
  413. }
  414. /**
  415. * Utility function
  416. * Returns a string for the OLE container with the date given
  417. *
  418. * @access public
  419. * @static
  420. * @param integer $date A timestamp
  421. * @return string The string for the OLE container
  422. */
  423. public static function LocalDate2OLE($date = null)
  424. {
  425. if (!isset($date)) {
  426. return "\x00\x00\x00\x00\x00\x00\x00\x00";
  427. }
  428. // factor used for separating numbers into 4 bytes parts
  429. $factor = pow(2, 32);
  430. // days from 1-1-1601 until the beggining of UNIX era
  431. $days = 134774;
  432. // calculate seconds
  433. $big_date = $days*24*3600 + gmmktime(date("H",$date),date("i",$date),date("s",$date),
  434. date("m",$date),date("d",$date),date("Y",$date));
  435. // multiply just to make MS happy
  436. $big_date *= 10000000;
  437. $high_part = floor($big_date / $factor);
  438. // lower 4 bytes
  439. $low_part = floor((($big_date / $factor) - $high_part) * $factor);
  440. // Make HEX string
  441. $res = '';
  442. for ($i = 0; $i < 4; ++$i) {
  443. $hex = $low_part % 0x100;
  444. $res .= pack('c', $hex);
  445. $low_part /= 0x100;
  446. }
  447. for ($i = 0; $i < 4; ++$i) {
  448. $hex = $high_part % 0x100;
  449. $res .= pack('c', $hex);
  450. $high_part /= 0x100;
  451. }
  452. return $res;
  453. }
  454. /**
  455. * Returns a timestamp from an OLE container's date
  456. *
  457. * @access public
  458. * @static
  459. * @param integer $string A binary string with the encoded date
  460. * @return string The timestamp corresponding to the string
  461. */
  462. public static function OLE2LocalDate($string)
  463. {
  464. if (strlen($string) != 8) {
  465. return new PEAR_Error("Expecting 8 byte string");
  466. }
  467. // factor used for separating numbers into 4 bytes parts
  468. $factor = pow(2,32);
  469. list(, $high_part) = unpack('V', substr($string, 4, 4));
  470. list(, $low_part) = unpack('V', substr($string, 0, 4));
  471. $big_date = ($high_part * $factor) + $low_part;
  472. // translate to seconds
  473. $big_date /= 10000000;
  474. // days from 1-1-1601 until the beggining of UNIX era
  475. $days = 134774;
  476. // translate to seconds from beggining of UNIX era
  477. $big_date -= $days * 24 * 3600;
  478. return floor($big_date);
  479. }
  480. }