first commit. dokuwiki.
[h2N7SspZmY.git] / inc / ZipLib.class.php
blob836e9d9e615be5b08caeb76b99b94cf527e62539
1 <?php
3 /**
4 * @author bouchon
5 * @link http://dev.maxg.info
6 * @link http://forum.maxg.info
8 * Modified for Dokuwiki
9 * @author Christopher Smith <chris@jalakai.co.uk>
11 class ZipLib
14 var $datasec, $ctrl_dir = array();
15 var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
16 var $old_offset = 0; var $dirs = Array(".");
18 function get_List($zip_name)
20 $zip = @fopen($zip_name, 'rb');
21 if(!$zip) return(0);
22 $centd = $this->ReadCentralDir($zip,$zip_name);
24 @rewind($zip);
25 @fseek($zip, $centd['offset']);
27 for ($i=0; $i<$centd['entries']; $i++)
29 $header = $this->ReadCentralFileHeaders($zip);
30 $header['index'] = $i;$info['filename'] = $header['filename'];
31 $info['stored_filename'] = $header['stored_filename'];
32 $info['size'] = $header['size'];$info['compressed_size']=$header['compressed_size'];
33 $info['crc'] = strtoupper(dechex( $header['crc'] ));
34 $info['mtime'] = $header['mtime']; $info['comment'] = $header['comment'];
35 $info['folder'] = ($header['external']==0x41FF0010||$header['external']==16)?1:0;
36 $info['index'] = $header['index'];$info['status'] = $header['status'];
37 $ret[]=$info; unset($header);
39 return $ret;
42 function Add($files,$compact)
44 if(!is_array($files[0])) $files=Array($files);
46 for($i=0;$files[$i];$i++){
47 $fn = $files[$i];
48 if(!in_Array(dirname($fn[0]),$this->dirs))
49 $this->add_Dir(dirname($fn[0]));
50 if(basename($fn[0]))
51 $ret[basename($fn[0])]=$this->add_File($fn[1],$fn[0],$compact);
53 return $ret;
56 /**
57 * Zips recursively the $folder directory, from the $basedir directory
59 function Compress($folder, $basedir=null, $parent=null)
61 $full_path = $basedir."/".$parent.$folder;
62 $zip_path = $parent.$folder;
63 if ($zip_path) {
64 $zip_path .= "/";
65 $this->add_dir($zip_path);
67 $dir = new DirectoryIterator($full_path);
68 foreach($dir as $file) {
69 if(!$file->isDot()) {
70 $filename = $file->getFilename();
71 if($file->isDir()) {
72 $this->Compress($filename, $basedir, $zip_path);
73 } else {
74 $content = join('', file($full_path.'/'.$filename));
75 $this->add_File($content, $zip_path.$filename);
81 /**
82 * Returns the Zip file
84 function get_file()
86 $data = implode('', $this -> datasec);
87 $ctrldir = implode('', $this -> ctrl_dir);
89 return $data . $ctrldir . $this -> eof_ctrl_dir .
90 pack('v', sizeof($this -> ctrl_dir)).pack('v', sizeof($this -> ctrl_dir)).
91 pack('V', strlen($ctrldir)) . pack('V', strlen($data)) . "\x00\x00";
94 function add_dir($name)
96 $name = str_replace("\\", "/", $name);
97 $fr = "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
99 $fr .= pack("V",0).pack("V",0).pack("V",0).pack("v", strlen($name) );
100 $fr .= pack("v", 0 ).$name.pack("V", 0).pack("V", 0).pack("V", 0);
101 $this -> datasec[] = $fr;
103 $new_offset = strlen(implode("", $this->datasec));
105 $cdrec = "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
106 $cdrec .= pack("V",0).pack("V",0).pack("V",0).pack("v", strlen($name) );
107 $cdrec .= pack("v", 0 ).pack("v", 0 ).pack("v", 0 ).pack("v", 0 );
108 $ext = "\xff\xff\xff\xff";
109 $cdrec .= pack("V", 16 ).pack("V", $this -> old_offset ).$name;
111 $this -> ctrl_dir[] = $cdrec;
112 $this -> old_offset = $new_offset;
113 $this -> dirs[] = $name;
117 * Add a file named $name from a string $data
119 function add_File($data, $name, $compact = 1)
121 $name = str_replace('\\', '/', $name);
122 $dtime = dechex($this->DosTime());
124 $hexdtime = '\x' . $dtime[6] . $dtime[7].'\x'.$dtime[4] . $dtime[5]
125 . '\x' . $dtime[2] . $dtime[3].'\x'.$dtime[0].$dtime[1];
126 eval('$hexdtime = "' . $hexdtime . '";');
128 if($compact)
129 $fr = "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00".$hexdtime;
130 else $fr = "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00".$hexdtime;
131 $unc_len = strlen($data); $crc = crc32($data);
133 if($compact){
134 $zdata = gzcompress($data); $c_len = strlen($zdata);
135 $zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
136 }else{
137 $zdata = $data;
139 $c_len=strlen($zdata);
140 $fr .= pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);
141 $fr .= pack('v', strlen($name)).pack('v', 0).$name.$zdata;
143 $fr .= pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);
145 $this -> datasec[] = $fr;
146 $new_offset = strlen(implode('', $this->datasec));
147 if($compact)
148 $cdrec = "\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00";
149 else $cdrec = "\x50\x4b\x01\x02\x14\x00\x0a\x00\x00\x00\x00\x00";
150 $cdrec .= $hexdtime.pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);
151 $cdrec .= pack('v', strlen($name) ).pack('v', 0 ).pack('v', 0 );
152 $cdrec .= pack('v', 0 ).pack('v', 0 ).pack('V', 32 );
153 $cdrec .= pack('V', $this -> old_offset );
155 $this -> old_offset = $new_offset;
156 $cdrec .= $name;
157 $this -> ctrl_dir[] = $cdrec;
158 return true;
161 function DosTime() {
162 $timearray = getdate();
163 if ($timearray['year'] < 1980) {
164 $timearray['year'] = 1980; $timearray['mon'] = 1;
165 $timearray['mday'] = 1; $timearray['hours'] = 0;
166 $timearray['minutes'] = 0; $timearray['seconds'] = 0;
168 return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | ($timearray['hours'] << 11) |
169 ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
173 * Extract a zip file $zn to the $to directory
175 function Extract ( $zn, $to, $index = Array(-1) )
177 if(!@is_dir($to)) $this->_mkdir($to);
178 $ok = 0; $zip = @fopen($zn,'rb');
179 if(!$zip) return(-1);
180 $cdir = $this->ReadCentralDir($zip,$zn);
181 $pos_entry = $cdir['offset'];
183 if(!is_array($index)){ $index = array($index); }
184 for($i=0; isset($index[$i]);$i++){
185 if(intval($index[$i])!=$index[$i]||$index[$i]>$cdir['entries'])
186 return(-1);
189 for ($i=0; $i<$cdir['entries']; $i++)
191 @fseek($zip, $pos_entry);
192 $header = $this->ReadCentralFileHeaders($zip);
193 $header['index'] = $i; $pos_entry = ftell($zip);
194 @rewind($zip); fseek($zip, $header['offset']);
195 if(in_array("-1",$index)||in_array($i,$index))
196 $stat[$header['filename']]=$this->ExtractFile($header, $to, $zip);
199 fclose($zip);
200 return $stat;
203 function ReadFileHeader($zip, $header)
205 $binary_data = fread($zip, 30);
206 $data = unpack('vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $binary_data);
208 $header['filename'] = fread($zip, $data['filename_len']);
209 if ($data['extra_len'] != 0) {
210 $header['extra'] = fread($zip, $data['extra_len']);
211 } else { $header['extra'] = ''; }
213 $header['compression'] = $data['compression'];
214 foreach (array('size','compressed_size','crc') as $hd) { // On ODT files, these headers are 0. Keep the previous value.
215 if ($data[$hd] != 0) $header[$hd] = $data[$hd];
217 $header['flag'] = $data['flag'];
218 $header['mdate'] = $data['mdate'];$header['mtime'] = $data['mtime'];
220 if ($header['mdate'] && $header['mtime']){
221 $hour=($header['mtime']&0xF800)>>11;$minute=($header['mtime']&0x07E0)>>5;
222 $seconde=($header['mtime']&0x001F)*2;$year=(($header['mdate']&0xFE00)>>9)+1980;
223 $month=($header['mdate']&0x01E0)>>5;$day=$header['mdate']&0x001F;
224 $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
225 }else{$header['mtime'] = time();}
227 $header['stored_filename'] = $header['filename'];
228 $header['status'] = "ok";
229 return $header;
232 function ReadCentralFileHeaders($zip){
233 $binary_data = fread($zip, 46);
234 $header = unpack('vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $binary_data);
236 if ($header['filename_len'] != 0)
237 $header['filename'] = fread($zip,$header['filename_len']);
238 else $header['filename'] = '';
240 if ($header['extra_len'] != 0)
241 $header['extra'] = fread($zip, $header['extra_len']);
242 else $header['extra'] = '';
244 if ($header['comment_len'] != 0)
245 $header['comment'] = fread($zip, $header['comment_len']);
246 else $header['comment'] = '';
248 if ($header['mdate'] && $header['mtime'])
250 $hour = ($header['mtime'] & 0xF800) >> 11;
251 $minute = ($header['mtime'] & 0x07E0) >> 5;
252 $seconde = ($header['mtime'] & 0x001F)*2;
253 $year = (($header['mdate'] & 0xFE00) >> 9) + 1980;
254 $month = ($header['mdate'] & 0x01E0) >> 5;
255 $day = $header['mdate'] & 0x001F;
256 $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
257 } else {
258 $header['mtime'] = time();
260 $header['stored_filename'] = $header['filename'];
261 $header['status'] = 'ok';
262 if (substr($header['filename'], -1) == '/')
263 $header['external'] = 0x41FF0010;
264 return $header;
267 function ReadCentralDir($zip,$zip_name)
269 $size = filesize($zip_name);
270 if ($size < 277) $maximum_size = $size;
271 else $maximum_size=277;
273 @fseek($zip, $size-$maximum_size);
274 $pos = ftell($zip); $bytes = 0x00000000;
276 while ($pos < $size)
278 $byte = @fread($zip, 1);
279 $bytes=(($bytes << 8) & 0xFFFFFFFF) | Ord($byte);
280 if ($bytes == 0x504b0506){ $pos++; break; } $pos++;
283 $data=unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
284 fread($zip, 18));
286 if ($data['comment_size'] != 0)
287 $centd['comment'] = fread($zip, $data['comment_size']);
288 else $centd['comment'] = ''; $centd['entries'] = $data['entries'];
289 $centd['disk_entries'] = $data['disk_entries'];
290 $centd['offset'] = $data['offset'];$centd['disk_start'] = $data['disk_start'];
291 $centd['size'] = $data['size']; $centd['disk'] = $data['disk'];
292 return $centd;
295 function ExtractFile($header,$to,$zip)
297 $header = $this->readfileheader($zip, $header);
299 if(substr($to,-1)!="/") $to.="/";
300 if(substr($header['filename'],-1)=="/")
302 // @mkdir($to.$header['filename']); --CS
303 $this->_mkdir($to.$header['filename']); //-- CS
304 return +2;
307 // $pth = explode("/",dirname($header['filename']));
308 // for($i=0,$tmp="";isset($pth[$i]);$i++){
309 // if(!$pth[$i]) continue;
310 // if(!is_dir($to.$tmp.$pth[$i])) @mkdir($to.$pth[$i],0777);
311 // $tmp.=$pth[$i]."/";
312 // }
313 if (!$this->_mkdir($to.dirname($header['filename']))) return (-1); //--CS
315 if (!array_key_exists("external", $header) || (!($header['external']==0x41FF0010)&&!($header['external']==16)))
317 if ($header['compression']==0)
319 $fp = @fopen($to.$header['filename'], 'wb');
320 if(!$fp) return(-1);
321 $size = $header['compressed_size'];
323 while ($size != 0)
325 $read_size = ($size < 2048 ? $size : 2048);
326 $buffer = fread($zip, $read_size);
327 $binary_data = pack('a'.$read_size, $buffer);
328 @fwrite($fp, $binary_data, $read_size);
329 $size -= $read_size;
331 fclose($fp);
332 touch($to.$header['filename'], $header['mtime']);
334 }else{
335 if (!is_dir(dirname($to.$header['filename']))) $this->_mkdir(dirname($to.$header['filename'])); //-CS
336 $fp = fopen($to.$header['filename'].'.gz','wb');
337 if(!$fp) return(-1);
338 $binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($header['compression']),
339 Chr(0x00), time(), Chr(0x00), Chr(3));
341 fwrite($fp, $binary_data, 10);
342 $size = $header['compressed_size'];
344 while ($size != 0)
346 $read_size = ($size < 1024 ? $size : 1024);
347 $buffer = fread($zip, $read_size);
348 $binary_data = pack('a'.$read_size, $buffer);
349 @fwrite($fp, $binary_data, $read_size);
350 $size -= $read_size;
353 $binary_data = pack('VV', $header['crc'], $header['size']);
354 fwrite($fp, $binary_data,8); fclose($fp);
356 $gzp = @gzopen($to.$header['filename'].'.gz','rb');
357 if(!$gzp){
358 @gzclose($gzp); @unlink($to.$header['filename']);
359 die("Archive is compressed whereas ZLIB is not enabled.");
361 $fp = @fopen($to.$header['filename'],'wb');
362 if(!$fp) return(-1);
363 $size = $header['size'];
365 while ($size != 0)
367 $read_size = ($size < 2048 ? $size : 2048);
368 $buffer = gzread($gzp, $read_size);
369 $binary_data = pack('a'.$read_size, $buffer);
370 @fwrite($fp, $binary_data, $read_size);
371 $size -= $read_size;
373 fclose($fp); gzclose($gzp);
375 touch($to.$header['filename'], $header['mtime']);
376 @unlink($to.$header['filename'].'.gz');
379 return true;
382 //--CS start
383 // centralize mkdir calls and use dokuwiki io functions
384 function _mkdir($d) {
385 return io_mkdir_p($d);
387 //--CS end
390 function ExtractStr($zn, $name) {
391 $ok = 0;
392 $zip = @fopen($zn,'rb');
393 if(!$zip) return(NULL);
394 $cdir = $this->ReadCentralDir($zip,$zn);
395 $pos_entry = $cdir['offset'];
397 for ($i=0; $i<$cdir['entries']; $i++)
399 @fseek($zip, $pos_entry);
400 $header = $this->ReadCentralFileHeaders($zip);
401 $header['index'] = $i;
402 $pos_entry = ftell($zip);
403 @rewind($zip);
404 fseek($zip, $header['offset']);
405 if ($name == $header['stored_filename'] || $name == $header['filename']) {
406 $str = $this->ExtractStrFile($header, $zip);
407 fclose($zip);
408 return $str;
412 fclose($zip);
413 return null;
416 function ExtractStrFile($header,$zip) {
417 $hdr = $this->readfileheader($zip);
418 $binary_data = '';
419 if (!($header['external']==0x41FF0010) && !($header['external']==16))
421 if ($header['compression']==0)
423 while ($size != 0)
425 $read_size = ($size < 2048 ? $size : 2048);
426 $buffer = fread($zip, $read_size);
427 $binary_data .= pack('a'.$read_size, $buffer);
428 $size -= $read_size;
430 return $binary_data;
431 } else {
432 $size = $header['compressed_size'];
433 if ($size == 0) {
434 return '';
436 //Just in case
437 if ($size > ($this->_ret_bytes(ini_get('memory_limit'))/2)) {
438 die("Compressed file is to huge to be uncompress in memory.");
440 while ($size != 0)
442 $read_size = ($size < 2048 ? $size : 2048);
443 $buffer = fread($zip, $read_size);
444 $binary_data .= pack('a'.$read_size, $buffer);
445 $size -= $read_size;
447 $str = gzinflate($binary_data, $header['size']);
448 if ($header['crc'] == crc32($str)) {
449 return $str;
450 } else {
451 die("Crc Error");
455 return NULL;
458 function _ret_bytes($val) {
459 $val = trim($val);
460 $last = $val{strlen($val)-1};
461 switch($last) {
462 case 'k':
463 case 'K':
464 return (int) $val * 1024;
465 break;
466 case 'm':
467 case 'M':
468 return (int) $val * 1048576;
469 break;
470 default:
471 return $val;