PageRenderTime 60ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/app/libraries/Tbszip/tbszip.php

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