Calibre OPDS (and HTML) PHP Server : web-based light alternative to Calibre content server / Calibre2OPDS to serve ebooks (epub, mobi, pdf, ...) http://blog.slucas.fr/en/oss/calibre-opds-php-server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1007 lines
31KB

  1. <?php
  2. /*
  3. TbsZip version 2.15
  4. Date : 2013-10-16
  5. Author : Skrol29 (email: http://www.tinybutstrong.com/onlyyou.html)
  6. Licence : LGPL
  7. This class is independent from any other classes and has been originally created for the OpenTbs plug-in
  8. for TinyButStrong Template Engine (TBS). OpenTbs makes TBS able to merge OpenOffice and Ms Office documents.
  9. Visit http://www.tinybutstrong.com
  10. */
  11. define('TBSZIP_DOWNLOAD',1); // download (default)
  12. define('TBSZIP_NOHEADER',4); // option to use with DOWNLOAD: no header is sent
  13. define('TBSZIP_FILE',8); // output to file , or add from file
  14. define('TBSZIP_STRING',32); // output to string, or add from string
  15. class clsTbsZip {
  16. function __construct() {
  17. $this->Meth8Ok = extension_loaded('zlib'); // check if Zlib extension is available. This is need for compress and uncompress with method 8.
  18. $this->DisplayError = true;
  19. $this->ArchFile = '';
  20. $this->Error = false;
  21. }
  22. function CreateNew($ArchName='new.zip') {
  23. // Create a new virtual empty archive, the name will be the default name when the archive is flushed.
  24. if (!isset($this->Meth8Ok)) $this->__construct(); // for PHP 4 compatibility
  25. $this->Close(); // note that $this->ArchHnd is set to false here
  26. $this->Error = false;
  27. $this->ArchFile = $ArchName;
  28. $this->ArchIsNew = true;
  29. $bin = 'PK'.chr(05).chr(06).str_repeat(chr(0), 18);
  30. $this->CdEndPos = strlen($bin) - 4;
  31. $this->CdInfo = array('disk_num_curr'=>0, 'disk_num_cd'=>0, 'file_nbr_curr'=>0, 'file_nbr_tot'=>0, 'l_cd'=>0, 'p_cd'=>0, 'l_comm'=>0, 'v_comm'=>'', 'bin'=>$bin);
  32. $this->CdPos = $this->CdInfo['p_cd'];
  33. }
  34. function Open($ArchFile, $UseIncludePath=false) {
  35. // Open the zip archive
  36. if (!isset($this->Meth8Ok)) $this->__construct(); // for PHP 4 compatibility
  37. $this->Close(); // close handle and init info
  38. $this->Error = false;
  39. $this->ArchIsNew = false;
  40. $this->ArchIsStream = (is_resource($ArchFile) && (get_resource_type($ArchFile)=='stream'));
  41. if ($this->ArchIsStream) {
  42. $this->ArchFile = 'from_stream.zip';
  43. $this->ArchHnd = $ArchFile;
  44. } else {
  45. // open the file
  46. $this->ArchFile = $ArchFile;
  47. $this->ArchHnd = fopen($ArchFile, 'rb', $UseIncludePath);
  48. }
  49. $ok = !($this->ArchHnd===false);
  50. if ($ok) $ok = $this->CentralDirRead();
  51. return $ok;
  52. }
  53. function Close() {
  54. if (isset($this->ArchHnd) and ($this->ArchHnd!==false)) fclose($this->ArchHnd);
  55. $this->ArchFile = '';
  56. $this->ArchHnd = false;
  57. $this->CdInfo = array();
  58. $this->CdFileLst = array();
  59. $this->CdFileNbr = 0;
  60. $this->CdFileByName = array();
  61. $this->VisFileLst = array();
  62. $this->ArchCancelModif();
  63. }
  64. function ArchCancelModif() {
  65. $this->LastReadComp = false; // compression of the last read file (1=compressed, 0=stored not compressed, -1= stored compressed but read uncompressed)
  66. $this->LastReadIdx = false; // index of the last file read
  67. $this->ReplInfo = array();
  68. $this->ReplByPos = array();
  69. $this->AddInfo = array();
  70. }
  71. function FileAdd($Name, $Data, $DataType=TBSZIP_STRING, $Compress=true) {
  72. if ($Data===false) return $this->FileCancelModif($Name, false); // Cancel a previously added file
  73. // Save information for adding a new file into the archive
  74. $Diff = 30 + 46 + 2*strlen($Name); // size of the header + cd info
  75. $Ref = $this->_DataCreateNewRef($Data, $DataType, $Compress, $Diff, $Name);
  76. if ($Ref===false) return false;
  77. $Ref['name'] = $Name;
  78. $this->AddInfo[] = $Ref;
  79. return $Ref['res'];
  80. }
  81. function CentralDirRead() {
  82. $cd_info = 'PK'.chr(05).chr(06); // signature of the Central Directory
  83. $cd_pos = -22;
  84. $this->_MoveTo($cd_pos, SEEK_END);
  85. $b = $this->_ReadData(4);
  86. if ($b===$cd_info) {
  87. $this->CdEndPos = ftell($this->ArchHnd) - 4;
  88. } else {
  89. $p = $this->_FindCDEnd($cd_info);
  90. //echo 'p='.var_export($p,true); exit;
  91. if ($p===false) {
  92. return $this->RaiseError('The End of Central Directory Record is not found.');
  93. } else {
  94. $this->CdEndPos = $p;
  95. $this->_MoveTo($p+4);
  96. }
  97. }
  98. $this->CdInfo = $this->CentralDirRead_End($cd_info);
  99. $this->CdFileLst = array();
  100. $this->CdFileNbr = $this->CdInfo['file_nbr_curr'];
  101. $this->CdPos = $this->CdInfo['p_cd'];
  102. if ($this->CdFileNbr<=0) return $this->RaiseError('No header found in the Central Directory.');
  103. if ($this->CdPos<=0) return $this->RaiseError('No position found for the Central Directory.');
  104. $this->_MoveTo($this->CdPos);
  105. for ($i=0;$i<$this->CdFileNbr;$i++) {
  106. $x = $this->CentralDirRead_File($i);
  107. if ($x!==false) {
  108. $this->CdFileLst[$i] = $x;
  109. $this->CdFileByName[$x['v_name']] = $i;
  110. }
  111. }
  112. return true;
  113. }
  114. function CentralDirRead_End($cd_info) {
  115. $b = $cd_info.$this->_ReadData(18);
  116. $x = array();
  117. $x['disk_num_curr'] = $this->_GetDec($b,4,2); // number of this disk
  118. $x['disk_num_cd'] = $this->_GetDec($b,6,2); // number of the disk with the start of the central directory
  119. $x['file_nbr_curr'] = $this->_GetDec($b,8,2); // total number of entries in the central directory on this disk
  120. $x['file_nbr_tot'] = $this->_GetDec($b,10,2); // total number of entries in the central directory
  121. $x['l_cd'] = $this->_GetDec($b,12,4); // size of the central directory
  122. $x['p_cd'] = $this->_GetDec($b,16,4); // position of start of central directory with respect to the starting disk number
  123. $x['l_comm'] = $this->_GetDec($b,20,2); // .ZIP file comment length
  124. $x['v_comm'] = $this->_ReadData($x['l_comm']); // .ZIP file comment
  125. $x['bin'] = $b.$x['v_comm'];
  126. return $x;
  127. }
  128. function CentralDirRead_File($idx) {
  129. $b = $this->_ReadData(46);
  130. $x = $this->_GetHex($b,0,4);
  131. if ($x!=='h:02014b50') return $this->RaiseError("Signature of Central Directory Header #".$idx." (file information) expected but not found at position ".$this->_TxtPos(ftell($this->ArchHnd) - 46).".");
  132. $x = array();
  133. $x['vers_used'] = $this->_GetDec($b,4,2);
  134. $x['vers_necess'] = $this->_GetDec($b,6,2);
  135. $x['purp'] = $this->_GetBin($b,8,2);
  136. $x['meth'] = $this->_GetDec($b,10,2);
  137. $x['time'] = $this->_GetDec($b,12,2);
  138. $x['date'] = $this->_GetDec($b,14,2);
  139. $x['crc32'] = $this->_GetDec($b,16,4);
  140. $x['l_data_c'] = $this->_GetDec($b,20,4);
  141. $x['l_data_u'] = $this->_GetDec($b,24,4);
  142. $x['l_name'] = $this->_GetDec($b,28,2);
  143. $x['l_fields'] = $this->_GetDec($b,30,2);
  144. $x['l_comm'] = $this->_GetDec($b,32,2);
  145. $x['disk_num'] = $this->_GetDec($b,34,2);
  146. $x['int_file_att'] = $this->_GetDec($b,36,2);
  147. $x['ext_file_att'] = $this->_GetDec($b,38,4);
  148. $x['p_loc'] = $this->_GetDec($b,42,4);
  149. $x['v_name'] = $this->_ReadData($x['l_name']);
  150. $x['v_fields'] = $this->_ReadData($x['l_fields']);
  151. $x['v_comm'] = $this->_ReadData($x['l_comm']);
  152. $x['bin'] = $b.$x['v_name'].$x['v_fields'].$x['v_comm'];
  153. return $x;
  154. }
  155. function RaiseError($Msg) {
  156. if ($this->DisplayError) {
  157. if (PHP_SAPI==='cli') {
  158. echo get_class($this).' ERROR with the zip archive: '.$Msg."\r\n";
  159. } else {
  160. echo '<strong>'.get_class($this).' ERROR with the zip archive:</strong> '.$Msg.'<br>'."\r\n";
  161. }
  162. }
  163. $this->Error = $Msg;
  164. return false;
  165. }
  166. function Debug($FileHeaders=false) {
  167. $this->DisplayError = true;
  168. if ($FileHeaders) {
  169. // Calculations first in order to have error messages before other information
  170. $idx = 0;
  171. $pos = 0;
  172. $pos_stop = $this->CdInfo['p_cd'];
  173. $this->_MoveTo($pos);
  174. while ( ($pos<$pos_stop) && ($ok = $this->_ReadFile($idx,false)) ) {
  175. $this->VisFileLst[$idx]['p_this_header (debug_mode only)'] = $pos;
  176. $pos = ftell($this->ArchHnd);
  177. $idx++;
  178. }
  179. }
  180. $nl = "\r\n";
  181. echo "<pre>";
  182. echo "-------------------------------".$nl;
  183. echo "End of Central Directory record".$nl;
  184. echo "-------------------------------".$nl;
  185. print_r($this->DebugArray($this->CdInfo));
  186. echo $nl;
  187. echo "-------------------------".$nl;
  188. echo "Central Directory headers".$nl;
  189. echo "-------------------------".$nl;
  190. print_r($this->DebugArray($this->CdFileLst));
  191. if ($FileHeaders) {
  192. echo $nl;
  193. echo "------------------".$nl;
  194. echo "Local File headers".$nl;
  195. echo "------------------".$nl;
  196. print_r($this->DebugArray($this->VisFileLst));
  197. }
  198. echo "</pre>";
  199. }
  200. function DebugArray($arr) {
  201. foreach ($arr as $k=>$v) {
  202. if (is_array($v)) {
  203. $arr[$k] = $this->DebugArray($v);
  204. } elseif (substr($k,0,2)=='p_') {
  205. $arr[$k] = $this->_TxtPos($v);
  206. }
  207. }
  208. return $arr;
  209. }
  210. function FileExists($NameOrIdx) {
  211. return ($this->FileGetIdx($NameOrIdx)!==false);
  212. }
  213. function FileGetIdx($NameOrIdx) {
  214. // Check if a file name, or a file index exists in the Central Directory, and return its index
  215. if (is_string($NameOrIdx)) {
  216. if (isset($this->CdFileByName[$NameOrIdx])) {
  217. return $this->CdFileByName[$NameOrIdx];
  218. } else {
  219. return false;
  220. }
  221. } else {
  222. if (isset($this->CdFileLst[$NameOrIdx])) {
  223. return $NameOrIdx;
  224. } else {
  225. return false;
  226. }
  227. }
  228. }
  229. function FileGetIdxAdd($Name) {
  230. // Check if a file name exists in the list of file to add, and return its index
  231. if (!is_string($Name)) return false;
  232. $idx_lst = array_keys($this->AddInfo);
  233. foreach ($idx_lst as $idx) {
  234. if ($this->AddInfo[$idx]['name']===$Name) return $idx;
  235. }
  236. return false;
  237. }
  238. function FileRead($NameOrIdx, $Uncompress=true) {
  239. $this->LastReadComp = false; // means the file is not found
  240. $this->LastReadIdx = false;
  241. $idx = $this->FileGetIdx($NameOrIdx);
  242. if ($idx===false) return $this->RaiseError('File "'.$NameOrIdx.'" is not found in the Central Directory.');
  243. $pos = $this->CdFileLst[$idx]['p_loc'];
  244. $this->_MoveTo($pos);
  245. $this->LastReadIdx = $idx; // Can be usefull to get the idx
  246. $Data = $this->_ReadFile($idx, true);
  247. // Manage uncompression
  248. $Comp = 1; // means the contents stays compressed
  249. $meth = $this->CdFileLst[$idx]['meth'];
  250. if ($meth==8) {
  251. if ($Uncompress) {
  252. if ($this->Meth8Ok) {
  253. $Data = gzinflate($Data);
  254. $Comp = -1; // means uncompressed
  255. } else {
  256. $this->RaiseError('Unable to uncompress file "'.$NameOrIdx.'" because extension Zlib is not installed.');
  257. }
  258. }
  259. } elseif($meth==0) {
  260. $Comp = 0; // means stored without compression
  261. } else {
  262. if ($Uncompress) $this->RaiseError('Unable to uncompress file "'.$NameOrIdx.'" because it is compressed with method '.$meth.'.');
  263. }
  264. $this->LastReadComp = $Comp;
  265. return $Data;
  266. }
  267. function _ReadFile($idx, $ReadData) {
  268. // read the file header (and maybe the data ) in the archive, assuming the cursor in at a new file position
  269. $b = $this->_ReadData(30);
  270. $x = $this->_GetHex($b,0,4);
  271. if ($x!=='h:04034b50') return $this->RaiseError("Signature of Local File Header #".$idx." (data section) expected but not found at position ".$this->_TxtPos(ftell($this->ArchHnd)-30).".");
  272. $x = array();
  273. $x['vers'] = $this->_GetDec($b,4,2);
  274. $x['purp'] = $this->_GetBin($b,6,2);
  275. $x['meth'] = $this->_GetDec($b,8,2);
  276. $x['time'] = $this->_GetDec($b,10,2);
  277. $x['date'] = $this->_GetDec($b,12,2);
  278. $x['crc32'] = $this->_GetDec($b,14,4);
  279. $x['l_data_c'] = $this->_GetDec($b,18,4);
  280. $x['l_data_u'] = $this->_GetDec($b,22,4);
  281. $x['l_name'] = $this->_GetDec($b,26,2);
  282. $x['l_fields'] = $this->_GetDec($b,28,2);
  283. $x['v_name'] = $this->_ReadData($x['l_name']);
  284. $x['v_fields'] = $this->_ReadData($x['l_fields']);
  285. $x['bin'] = $b.$x['v_name'].$x['v_fields'];
  286. // Read Data
  287. if (isset($this->CdFileLst[$idx])) {
  288. $len_cd = $this->CdFileLst[$idx]['l_data_c'];
  289. if ($x['l_data_c']==0) {
  290. // Sometimes, the size is not specified in the local information.
  291. $len = $len_cd;
  292. } else {
  293. $len = $x['l_data_c'];
  294. if ($len!=$len_cd) {
  295. //echo "TbsZip Warning: Local information for file #".$idx." says len=".$len.", while Central Directory says len=".$len_cd.".";
  296. }
  297. }
  298. } else {
  299. $len = $x['l_data_c'];
  300. if ($len==0) $this->RaiseError("File Data #".$idx." cannt be read because no length is specified in the Local File Header and its Central Directory information has not been found.");
  301. }
  302. if ($ReadData) {
  303. $Data = $this->_ReadData($len);
  304. } else {
  305. $this->_MoveTo($len, SEEK_CUR);
  306. }
  307. // Description information
  308. $desc_ok = ($x['purp'][2+3]=='1');
  309. if ($desc_ok) {
  310. $b = $this->_ReadData(12);
  311. $s = $this->_GetHex($b,0,4);
  312. $d = 0;
  313. // the specification says the signature may or may not be present
  314. if ($s=='h:08074b50') {
  315. $b .= $this->_ReadData(4);
  316. $d = 4;
  317. $x['desc_bin'] = $b;
  318. $x['desc_sign'] = $s;
  319. } else {
  320. $x['desc_bin'] = $b;
  321. }
  322. $x['desc_crc32'] = $this->_GetDec($b,0+$d,4);
  323. $x['desc_l_data_c'] = $this->_GetDec($b,4+$d,4);
  324. $x['desc_l_data_u'] = $this->_GetDec($b,8+$d,4);
  325. }
  326. // Save file info without the data
  327. $this->VisFileLst[$idx] = $x;
  328. // Return the info
  329. if ($ReadData) {
  330. return $Data;
  331. } else {
  332. return true;
  333. }
  334. }
  335. function FileReplace($NameOrIdx, $Data, $DataType=TBSZIP_STRING, $Compress=true) {
  336. // Store replacement information.
  337. $idx = $this->FileGetIdx($NameOrIdx);
  338. if ($idx===false) return $this->RaiseError('File "'.$NameOrIdx.'" is not found in the Central Directory.');
  339. $pos = $this->CdFileLst[$idx]['p_loc'];
  340. if ($Data===false) {
  341. // file to delete
  342. $this->ReplInfo[$idx] = false;
  343. $Result = true;
  344. } else {
  345. // file to replace
  346. $Diff = - $this->CdFileLst[$idx]['l_data_c'];
  347. $Ref = $this->_DataCreateNewRef($Data, $DataType, $Compress, $Diff, $NameOrIdx);
  348. if ($Ref===false) return false;
  349. $this->ReplInfo[$idx] = $Ref;
  350. $Result = $Ref['res'];
  351. }
  352. $this->ReplByPos[$pos] = $idx;
  353. return $Result;
  354. }
  355. /**
  356. * Return the state of the file.
  357. * @return {string} 'u'=unchanged, 'm'=modified, 'd'=deleted, 'a'=added, false=unknown
  358. */
  359. function FileGetState($NameOrIdx) {
  360. $idx = $this->FileGetIdx($NameOrIdx);
  361. if ($idx===false) {
  362. $idx = $this->FileGetIdxAdd($NameOrIdx);
  363. if ($idx===false) {
  364. return false;
  365. } else {
  366. return 'a';
  367. }
  368. } elseif (isset($this->ReplInfo[$idx])) {
  369. if ($this->ReplInfo[$idx]===false) {
  370. return 'd';
  371. } else {
  372. return 'm';
  373. }
  374. } else {
  375. return 'u';
  376. }
  377. }
  378. function FileCancelModif($NameOrIdx, $ReplacedAndDeleted=true) {
  379. // cancel added, modified or deleted modifications on a file in the archive
  380. // return the number of cancels
  381. $nbr = 0;
  382. if ($ReplacedAndDeleted) {
  383. // replaced or deleted files
  384. $idx = $this->FileGetIdx($NameOrIdx);
  385. if ($idx!==false) {
  386. if (isset($this->ReplInfo[$idx])) {
  387. $pos = $this->CdFileLst[$idx]['p_loc'];
  388. unset($this->ReplByPos[$pos]);
  389. unset($this->ReplInfo[$idx]);
  390. $nbr++;
  391. }
  392. }
  393. }
  394. // added files
  395. $idx = $this->FileGetIdxAdd($NameOrIdx);
  396. if ($idx!==false) {
  397. unset($this->AddInfo[$idx]);
  398. $nbr++;
  399. }
  400. return $nbr;
  401. }
  402. function Flush($Render=TBSZIP_DOWNLOAD, $File='', $ContentType='') {
  403. if ( ($File!=='') && ($this->ArchFile===$File)) {
  404. $this->RaiseError('Method Flush() cannot overwrite the current opened archive: \''.$File.'\''); // this makes corrupted zip archives without PHP error.
  405. return false;
  406. }
  407. $ArchPos = 0;
  408. $Delta = 0;
  409. $FicNewPos = array();
  410. $DelLst = array(); // idx of deleted files
  411. $DeltaCdLen = 0; // delta of the CD's size
  412. $now = time();
  413. $date = $this->_MsDos_Date($now);
  414. $time = $this->_MsDos_Time($now);
  415. if (!$this->OutputOpen($Render, $File, $ContentType)) return false;
  416. // output modified zipped files and unmodified zipped files that are beetween them
  417. ksort($this->ReplByPos);
  418. foreach ($this->ReplByPos as $ReplPos => $ReplIdx) {
  419. // output data from the zip archive which is before the data to replace
  420. $this->OutputFromArch($ArchPos, $ReplPos);
  421. // get current file information
  422. if (!isset($this->VisFileLst[$ReplIdx])) $this->_ReadFile($ReplIdx, false);
  423. $FileInfo =& $this->VisFileLst[$ReplIdx];
  424. $b1 = $FileInfo['bin'];
  425. if (isset($FileInfo['desc_bin'])) {
  426. $b2 = $FileInfo['desc_bin'];
  427. } else {
  428. $b2 = '';
  429. }
  430. $info_old_len = strlen($b1) + $this->CdFileLst[$ReplIdx]['l_data_c'] + strlen($b2); // $FileInfo['l_data_c'] may have a 0 value in some archives
  431. // get replacement information
  432. $ReplInfo =& $this->ReplInfo[$ReplIdx];
  433. if ($ReplInfo===false) {
  434. // The file is to be deleted
  435. $Delta = $Delta - $info_old_len; // headers and footers are also deleted
  436. $DelLst[$ReplIdx] = true;
  437. } else {
  438. // prepare the header of the current file
  439. $this->_DataPrepare($ReplInfo); // get data from external file if necessary
  440. $this->_PutDec($b1, $time, 10, 2); // time
  441. $this->_PutDec($b1, $date, 12, 2); // date
  442. $this->_PutDec($b1, $ReplInfo['crc32'], 14, 4); // crc32
  443. $this->_PutDec($b1, $ReplInfo['len_c'], 18, 4); // l_data_c
  444. $this->_PutDec($b1, $ReplInfo['len_u'], 22, 4); // l_data_u
  445. if ($ReplInfo['meth']!==false) $this->_PutDec($b1, $ReplInfo['meth'], 8, 2); // meth
  446. // prepare the bottom description if the zipped file, if any
  447. if ($b2!=='') {
  448. $d = (strlen($b2)==16) ? 4 : 0; // offset because of the signature if any
  449. $this->_PutDec($b2, $ReplInfo['crc32'], $d+0, 4); // crc32
  450. $this->_PutDec($b2, $ReplInfo['len_c'], $d+4, 4); // l_data_c
  451. $this->_PutDec($b2, $ReplInfo['len_u'], $d+8, 4); // l_data_u
  452. }
  453. // output data
  454. $this->OutputFromString($b1.$ReplInfo['data'].$b2);
  455. unset($ReplInfo['data']); // save PHP memory
  456. $Delta = $Delta + $ReplInfo['diff'] + $ReplInfo['len_c'];
  457. }
  458. // Update the delta of positions for zipped files which are physically after the currently replaced one
  459. for ($i=0;$i<$this->CdFileNbr;$i++) {
  460. if ($this->CdFileLst[$i]['p_loc']>$ReplPos) {
  461. $FicNewPos[$i] = $this->CdFileLst[$i]['p_loc'] + $Delta;
  462. }
  463. }
  464. // Update the current pos in the archive
  465. $ArchPos = $ReplPos + $info_old_len;
  466. }
  467. // Ouput all the zipped files that remain before the Central Directory listing
  468. if ($this->ArchHnd!==false) $this->OutputFromArch($ArchPos, $this->CdPos); // ArchHnd is false if CreateNew() has been called
  469. $ArchPos = $this->CdPos;
  470. // Output file to add
  471. $AddNbr = count($this->AddInfo);
  472. $AddDataLen = 0; // total len of added data (inlcuding file headers)
  473. if ($AddNbr>0) {
  474. $AddPos = $ArchPos + $Delta; // position of the start
  475. $AddLst = array_keys($this->AddInfo);
  476. foreach ($AddLst as $idx) {
  477. $n = $this->_DataOuputAddedFile($idx, $AddPos);
  478. $AddPos += $n;
  479. $AddDataLen += $n;
  480. }
  481. }
  482. // Modifiy file information in the Central Directory for replaced files
  483. $b2 = '';
  484. $old_cd_len = 0;
  485. for ($i=0;$i<$this->CdFileNbr;$i++) {
  486. $b1 = $this->CdFileLst[$i]['bin'];
  487. $old_cd_len += strlen($b1);
  488. if (!isset($DelLst[$i])) {
  489. if (isset($FicNewPos[$i])) $this->_PutDec($b1, $FicNewPos[$i], 42, 4); // p_loc
  490. if (isset($this->ReplInfo[$i])) {
  491. $ReplInfo =& $this->ReplInfo[$i];
  492. $this->_PutDec($b1, $time, 12, 2); // time
  493. $this->_PutDec($b1, $date, 14, 2); // date
  494. $this->_PutDec($b1, $ReplInfo['crc32'], 16, 4); // crc32
  495. $this->_PutDec($b1, $ReplInfo['len_c'], 20, 4); // l_data_c
  496. $this->_PutDec($b1, $ReplInfo['len_u'], 24, 4); // l_data_u
  497. if ($ReplInfo['meth']!==false) $this->_PutDec($b1, $ReplInfo['meth'], 10, 2); // meth
  498. }
  499. $b2 .= $b1;
  500. }
  501. }
  502. $this->OutputFromString($b2);
  503. $ArchPos += $old_cd_len;
  504. $DeltaCdLen = $DeltaCdLen + strlen($b2) - $old_cd_len;
  505. // Output until "end of central directory record"
  506. if ($this->ArchHnd!==false) $this->OutputFromArch($ArchPos, $this->CdEndPos); // ArchHnd is false if CreateNew() has been called
  507. // Output file information of the Central Directory for added files
  508. if ($AddNbr>0) {
  509. $b2 = '';
  510. foreach ($AddLst as $idx) {
  511. $b2 .= $this->AddInfo[$idx]['bin'];
  512. }
  513. $this->OutputFromString($b2);
  514. $DeltaCdLen += strlen($b2);
  515. }
  516. // Output "end of central directory record"
  517. $b2 = $this->CdInfo['bin'];
  518. $DelNbr = count($DelLst);
  519. if ( ($AddNbr>0) or ($DelNbr>0) ) {
  520. // total number of entries in the central directory on this disk
  521. $n = $this->_GetDec($b2, 8, 2);
  522. $this->_PutDec($b2, $n + $AddNbr - $DelNbr, 8, 2);
  523. // total number of entries in the central directory
  524. $n = $this->_GetDec($b2, 10, 2);
  525. $this->_PutDec($b2, $n + $AddNbr - $DelNbr, 10, 2);
  526. // size of the central directory
  527. $n = $this->_GetDec($b2, 12, 4);
  528. $this->_PutDec($b2, $n + $DeltaCdLen, 12, 4);
  529. $Delta = $Delta + $AddDataLen;
  530. }
  531. $this->_PutDec($b2, $this->CdPos+$Delta , 16, 4); // p_cd (offset of start of central directory with respect to the starting disk number)
  532. $this->OutputFromString($b2);
  533. $this->OutputClose();
  534. return true;
  535. }
  536. // ----------------
  537. // output functions
  538. // ----------------
  539. function OutputOpen($Render, $File, $ContentType) {
  540. if (($Render & TBSZIP_FILE)==TBSZIP_FILE) {
  541. $this->OutputMode = TBSZIP_FILE;
  542. if (''.$File=='') $File = basename($this->ArchFile).'.zip';
  543. $this->OutputHandle = @fopen($File, 'w');
  544. if ($this->OutputHandle===false) {
  545. return $this->RaiseError('Method Flush() cannot overwrite the target file \''.$File.'\'. This may not be a valid file path or the file may be locked by another process or because of a denied permission.');
  546. }
  547. } elseif (($Render & TBSZIP_STRING)==TBSZIP_STRING) {
  548. $this->OutputMode = TBSZIP_STRING;
  549. $this->OutputSrc = '';
  550. } elseif (($Render & TBSZIP_DOWNLOAD)==TBSZIP_DOWNLOAD) {
  551. $this->OutputMode = TBSZIP_DOWNLOAD;
  552. // Output the file
  553. if (''.$File=='') $File = basename($this->ArchFile);
  554. if (($Render & TBSZIP_NOHEADER)==TBSZIP_NOHEADER) {
  555. } else {
  556. header ('Pragma: no-cache');
  557. if ($ContentType!='') header ('Content-Type: '.$ContentType);
  558. if (strlen($File) != strlen(utf8_decode($File))) {
  559. header('Content-Disposition: attachment; filename="book.epub"; filename*=utf-8\'\'' . rawurlencode($File));
  560. } else {
  561. header('Content-Disposition: attachment; filename="'.$File.'"');
  562. }
  563. header('Expires: 0');
  564. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  565. header('Cache-Control: public');
  566. header('Content-Description: File Transfer');
  567. header('Content-Transfer-Encoding: binary');
  568. $Len = $this->_EstimateNewArchSize();
  569. if ($Len!==false) header('Content-Length: '.$Len);
  570. }
  571. } else {
  572. return $this->RaiseError('Method Flush is called with a unsupported render option.');
  573. }
  574. return true;
  575. }
  576. function OutputFromArch($pos, $pos_stop) {
  577. $len = $pos_stop - $pos;
  578. if ($len<0) return;
  579. $this->_MoveTo($pos);
  580. $block = 1024;
  581. while ($len>0) {
  582. $l = min($len, $block);
  583. $x = $this->_ReadData($l);
  584. $this->OutputFromString($x);
  585. $len = $len - $l;
  586. }
  587. unset($x);
  588. }
  589. function OutputFromString($data) {
  590. if ($this->OutputMode===TBSZIP_DOWNLOAD) {
  591. echo $data; // donwload
  592. } elseif ($this->OutputMode===TBSZIP_STRING) {
  593. $this->OutputSrc .= $data; // to string
  594. } elseif (TBSZIP_FILE) {
  595. fwrite($this->OutputHandle, $data); // to file
  596. }
  597. }
  598. function OutputClose() {
  599. if ( ($this->OutputMode===TBSZIP_FILE) && ($this->OutputHandle!==false) ) {
  600. fclose($this->OutputHandle);
  601. $this->OutputHandle = false;
  602. }
  603. }
  604. // ----------------
  605. // Reading functions
  606. // ----------------
  607. function _MoveTo($pos, $relative = SEEK_SET) {
  608. fseek($this->ArchHnd, $pos, $relative);
  609. }
  610. function _ReadData($len) {
  611. if ($len>0) {
  612. $x = fread($this->ArchHnd, $len);
  613. return $x;
  614. } else {
  615. return '';
  616. }
  617. }
  618. // ----------------
  619. // Take info from binary data
  620. // ----------------
  621. function _GetDec($txt, $pos, $len) {
  622. $x = substr($txt, $pos, $len);
  623. $z = 0;
  624. for ($i=0;$i<$len;$i++) {
  625. $asc = ord($x[$i]);
  626. if ($asc>0) $z = $z + $asc*pow(256,$i);
  627. }
  628. return $z;
  629. }
  630. function _GetHex($txt, $pos, $len) {
  631. $x = substr($txt, $pos, $len);
  632. return 'h:'.bin2hex(strrev($x));
  633. }
  634. function _GetBin($txt, $pos, $len) {
  635. $x = substr($txt, $pos, $len);
  636. $z = '';
  637. for ($i=0;$i<$len;$i++) {
  638. $asc = ord($x[$i]);
  639. if (isset($x[$i])) {
  640. for ($j=0;$j<8;$j++) {
  641. $z .= ($asc & pow(2,$j)) ? '1' : '0';
  642. }
  643. } else {
  644. $z .= '00000000';
  645. }
  646. }
  647. return 'b:'.$z;
  648. }
  649. // ----------------
  650. // Put info into binary data
  651. // ----------------
  652. function _PutDec(&$txt, $val, $pos, $len) {
  653. $x = '';
  654. for ($i=0;$i<$len;$i++) {
  655. if ($val==0) {
  656. $z = 0;
  657. } else {
  658. $z = intval($val % 256);
  659. if (($val<0) && ($z!=0)) { // ($z!=0) is very important, example: val=-420085702
  660. // special opration for negative value. If the number id too big, PHP stores it into a signed integer. For example: crc32('coucou') => -256185401 instead of 4038781895. NegVal = BigVal - (MaxVal+1) = BigVal - 256^4
  661. $val = ($val - $z)/256 -1;
  662. $z = 256 + $z;
  663. } else {
  664. $val = ($val - $z)/256;
  665. }
  666. }
  667. $x .= chr($z);
  668. }
  669. $txt = substr_replace($txt, $x, $pos, $len);
  670. }
  671. function _MsDos_Date($Timestamp = false) {
  672. // convert a date-time timstamp into the MS-Dos format
  673. $d = ($Timestamp===false) ? getdate() : getdate($Timestamp);
  674. return (($d['year']-1980)*512) + ($d['mon']*32) + $d['mday'];
  675. }
  676. function _MsDos_Time($Timestamp = false) {
  677. // convert a date-time timstamp into the MS-Dos format
  678. $d = ($Timestamp===false) ? getdate() : getdate($Timestamp);
  679. return ($d['hours']*2048) + ($d['minutes']*32) + intval($d['seconds']/2); // seconds are rounded to an even number in order to save 1 bit
  680. }
  681. function _MsDos_Debug($date, $time) {
  682. // Display the formated date and time. Just for debug purpose.
  683. // date end time are encoded on 16 bits (2 bytes) : date = yyyyyyymmmmddddd , time = hhhhhnnnnnssssss
  684. $y = ($date & 65024)/512 + 1980;
  685. $m = ($date & 480)/32;
  686. $d = ($date & 31);
  687. $h = ($time & 63488)/2048;
  688. $i = ($time & 1984)/32;
  689. $s = ($time & 31) * 2; // seconds have been rounded to an even number in order to save 1 bit
  690. return $y.'-'.str_pad($m,2,'0',STR_PAD_LEFT).'-'.str_pad($d,2,'0',STR_PAD_LEFT).' '.str_pad($h,2,'0',STR_PAD_LEFT).':'.str_pad($i,2,'0',STR_PAD_LEFT).':'.str_pad($s,2,'0',STR_PAD_LEFT);
  691. }
  692. function _TxtPos($pos) {
  693. // Return the human readable position in both decimal and hexa
  694. return $pos." (h:".dechex($pos).")";
  695. }
  696. /**
  697. * Search the record of end of the Central Directory.
  698. * Return the position of the record in the file.
  699. * Return false if the record is not found. The comment cannot exceed 65335 bytes (=FFFF).
  700. * The method is read backwards a block of 256 bytes and search the key in this block.
  701. */
  702. function _FindCDEnd($cd_info) {
  703. $nbr = 1;
  704. $p = false;
  705. $pos = ftell($this->ArchHnd) - 4 - 256;
  706. while ( ($p===false) && ($nbr<256) ) {
  707. if ($pos<=0) {
  708. $pos = 0;
  709. $nbr = 256; // in order to make this a last check
  710. }
  711. $this->_MoveTo($pos);
  712. $x = $this->_ReadData(256);
  713. $p = strpos($x, $cd_info);
  714. if ($p===false) {
  715. $nbr++;
  716. $pos = $pos - 256 - 256;
  717. } else {
  718. return $pos + $p;
  719. }
  720. }
  721. return false;
  722. }
  723. function _DataOuputAddedFile($Idx, $PosLoc) {
  724. $Ref =& $this->AddInfo[$Idx];
  725. $this->_DataPrepare($Ref); // get data from external file if necessary
  726. // Other info
  727. $now = time();
  728. $date = $this->_MsDos_Date($now);
  729. $time = $this->_MsDos_Time($now);
  730. $len_n = strlen($Ref['name']);
  731. $purp = 2048 ; // purpose // +8 to indicates that there is an extended local header
  732. // Header for file in the data section
  733. $b = 'PK'.chr(03).chr(04).str_repeat(' ',26); // signature
  734. $this->_PutDec($b,20,4,2); //vers = 20
  735. $this->_PutDec($b,$purp,6,2); // purp
  736. $this->_PutDec($b,$Ref['meth'],8,2); // meth
  737. $this->_PutDec($b,$time,10,2); // time
  738. $this->_PutDec($b,$date,12,2); // date
  739. $this->_PutDec($b,$Ref['crc32'],14,4); // crc32
  740. $this->_PutDec($b,$Ref['len_c'],18,4); // l_data_c
  741. $this->_PutDec($b,$Ref['len_u'],22,4); // l_data_u
  742. $this->_PutDec($b,$len_n,26,2); // l_name
  743. $this->_PutDec($b,0,28,2); // l_fields
  744. $b .= $Ref['name']; // name
  745. $b .= ''; // fields
  746. // Output the data
  747. $this->OutputFromString($b.$Ref['data']);
  748. $OutputLen = strlen($b) + $Ref['len_c']; // new position of the cursor
  749. unset($Ref['data']); // save PHP memory
  750. // Information for file in the Central Directory
  751. $b = 'PK'.chr(01).chr(02).str_repeat(' ',42); // signature
  752. $this->_PutDec($b,20,4,2); // vers_used = 20
  753. $this->_PutDec($b,20,6,2); // vers_necess = 20
  754. $this->_PutDec($b,$purp,8,2); // purp
  755. $this->_PutDec($b,$Ref['meth'],10,2); // meth
  756. $this->_PutDec($b,$time,12,2); // time
  757. $this->_PutDec($b,$date,14,2); // date
  758. $this->_PutDec($b,$Ref['crc32'],16,4); // crc32
  759. $this->_PutDec($b,$Ref['len_c'],20,4); // l_data_c
  760. $this->_PutDec($b,$Ref['len_u'],24,4); // l_data_u
  761. $this->_PutDec($b,$len_n,28,2); // l_name
  762. $this->_PutDec($b,0,30,2); // l_fields
  763. $this->_PutDec($b,0,32,2); // l_comm
  764. $this->_PutDec($b,0,34,2); // disk_num
  765. $this->_PutDec($b,0,36,2); // int_file_att
  766. $this->_PutDec($b,0,38,4); // ext_file_att
  767. $this->_PutDec($b,$PosLoc,42,4); // p_loc
  768. $b .= $Ref['name']; // v_name
  769. $b .= ''; // v_fields
  770. $b .= ''; // v_comm
  771. $Ref['bin'] = $b;
  772. return $OutputLen;
  773. }
  774. function _DataCreateNewRef($Data, $DataType, $Compress, $Diff, $NameOrIdx) {
  775. if (is_array($Compress)) {
  776. $result = 2;
  777. $meth = $Compress['meth'];
  778. $len_u = $Compress['len_u'];
  779. $crc32 = $Compress['crc32'];
  780. $Compress = false;
  781. } elseif ($Compress and ($this->Meth8Ok)) {
  782. $result = 1;
  783. $meth = 8;
  784. $len_u = false; // means unknown
  785. $crc32 = false;
  786. } else {
  787. $result = ($Compress) ? -1 : 0;
  788. $meth = 0;
  789. $len_u = false;
  790. $crc32 = false;
  791. $Compress = false;
  792. }
  793. if ($DataType==TBSZIP_STRING) {
  794. $path = false;
  795. if ($Compress) {
  796. // we compress now in order to save PHP memory
  797. $len_u = strlen($Data);
  798. $crc32 = crc32($Data);
  799. $Data = gzdeflate($Data);
  800. $len_c = strlen($Data);
  801. } else {
  802. $len_c = strlen($Data);
  803. if ($len_u===false) {
  804. $len_u = $len_c;
  805. $crc32 = crc32($Data);
  806. }
  807. }
  808. } else {
  809. $path = $Data;
  810. $Data = false;
  811. if (file_exists($path)) {
  812. $fz = filesize($path);
  813. if ($len_u===false) $len_u = $fz;
  814. $len_c = ($Compress) ? false : $fz;
  815. } else {
  816. return $this->RaiseError("Cannot add the file '".$path."' because it is not found.");
  817. }
  818. }
  819. // at this step $Data and $crc32 can be false only in case of external file, and $len_c is false only in case of external file to compress
  820. return array('data'=>$Data, 'path'=>$path, 'meth'=>$meth, 'len_u'=>$len_u, 'len_c'=>$len_c, 'crc32'=>$crc32, 'diff'=>$Diff, 'res'=>$result);
  821. }
  822. function _DataPrepare(&$Ref) {
  823. // returns the real size of data
  824. if ($Ref['path']!==false) {
  825. $Ref['data'] = file_get_contents($Ref['path']);
  826. if ($Ref['crc32']===false) $Ref['crc32'] = crc32($Ref['data']);
  827. if ($Ref['len_c']===false) {
  828. // means the data must be compressed
  829. $Ref['data'] = gzdeflate($Ref['data']);
  830. $Ref['len_c'] = strlen($Ref['data']);
  831. }
  832. }
  833. }
  834. function _EstimateNewArchSize($Optim=true) {
  835. // Return the size of the new archive, or false if it cannot be calculated (because of external file that must be compressed before to be insered)
  836. if ($this->ArchIsNew) {
  837. $Len = strlen($this->CdInfo['bin']);
  838. } elseif ($this->ArchIsStream) {
  839. $x = fstat($this->ArchHnd);
  840. $Len = $x['size'];
  841. } else {
  842. $Len = filesize($this->ArchFile);
  843. }
  844. // files to replace or delete
  845. foreach ($this->ReplByPos as $i) {
  846. $Ref =& $this->ReplInfo[$i];
  847. if ($Ref===false) {
  848. // file to delete
  849. $Info =& $this->CdFileLst[$i];
  850. if (!isset($this->VisFileLst[$i])) {
  851. if ($Optim) return false; // if $Optimization is set to true, then we d'ont rewind to read information
  852. $this->_MoveTo($Info['p_loc']);
  853. $this->_ReadFile($i, false);
  854. }
  855. $Vis =& $this->VisFileLst[$i];
  856. $Len += -strlen($Vis['bin']) -strlen($Info['bin']) - $Info['l_data_c'];
  857. if (isset($Vis['desc_bin'])) $Len += -strlen($Vis['desc_bin']);
  858. } elseif ($Ref['len_c']===false) {
  859. return false; // information not yet known
  860. } else {
  861. // file to replace
  862. $Len += $Ref['len_c'] + $Ref['diff'];
  863. }
  864. }
  865. // files to add
  866. $i_lst = array_keys($this->AddInfo);
  867. foreach ($i_lst as $i) {
  868. $Ref =& $this->AddInfo[$i];
  869. if ($Ref['len_c']===false) {
  870. return false; // information not yet known
  871. } else {
  872. $Len += $Ref['len_c'] + $Ref['diff'];
  873. }
  874. }
  875. return $Len;
  876. }
  877. }