6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
20 * Class for handling archives (compression/decompression)
30 function add_file($src, $src_rm_prefix = '', $src_add_prefix = '', $skip_files = '')
32 global $phpbb_root_path;
34 $skip_files = explode(',', $skip_files);
36 // Remove rm prefix from src path
37 $src_path = ($src_rm_prefix) ? preg_replace('#^(' . preg_quote($src_rm_prefix, '#') . ')#', '', $src) : $src;
39 $src_path = ($src_add_prefix) ? ($src_add_prefix . ((substr($src_add_prefix, -1) != '/') ? '/' : '') . $src_path) : $src_path;
40 // Remove initial "/" if present
41 $src_path = (substr($src_path, 0, 1) == '/') ? substr($src_path, 1) : $src_path;
43 if (is_file($phpbb_root_path . $src))
45 $this->data($src_path, file_get_contents("$phpbb_root_path$src"), false, stat("$phpbb_root_path$src"));
47 else if (is_dir($phpbb_root_path . $src))
49 // Clean up path, add closing / if not present
50 $src_path = ($src_path && substr($src_path, -1) != '/') ? $src_path . '/' : $src_path;
53 $filelist = filelist("$phpbb_root_path$src", '', '*');
57 * Commented out, as adding the folders produces corrupted archives
60 $this->data($src_path, '', true, stat("$phpbb_root_path$src"));
64 foreach ($filelist as $path => $file_ary)
67 * Commented out, as adding the folders produces corrupted archives
70 // Same as for src_path
71 $path = (substr($path, 0, 1) == '/') ? substr($path, 1) : $path;
72 $path = ($path && substr($path, -1) != '/') ? $path . '/' : $path;
74 $this->data("$src_path$path", '', true, stat("$phpbb_root_path$src$path"));
78 foreach ($file_ary as $file)
80 if (in_array($path . $file, $skip_files))
85 $this->data("$src_path$path$file", file_get_contents("$phpbb_root_path$src$path$file"), false, stat("$phpbb_root_path$src$path$file"));
91 // $src does not exist
99 * Add custom file (the filepath will not be adjusted)
101 function add_custom_file($src, $filename)
103 if (!file_exists($src))
108 $this->data($filename, file_get_contents($src), false, stat($src));
115 function add_data($src, $name)
118 $stat[2] = 436; //384
119 $stat[4] = $stat[5] = 0;
120 $stat[7] = strlen($src);
122 $this->data($name, $src, false, $stat);
127 * Return available methods
131 $methods = array('.tar');
132 $available_methods = array('.tar.gz' => 'zlib', '.tar.bz2' => 'bz2', '.zip' => 'zlib');
134 foreach ($available_methods as $type => $module)
136 if (!@extension_loaded($module))
148 * Zip creation class from phpMyAdmin 2.3.0 (c) Tobias Ratschiller, Olivier Müller, Loïc Chapeaux,
149 * Marc Delisle, http://www.phpmyadmin.net/
151 * Zip extraction function by Alexandre Tedeschi, alexandrebr at gmail dot com
153 * Modified extensively by psoTFX and DavidMJ, (c) phpBB Group, 2003
155 * Based on work by Eric Mueller and Denis125
156 * Official ZIP file format: http://www.pkware.com/appnote.txt
160 class compress_zip extends compress
162 var $datasec = array();
163 var $ctrl_dir = array();
164 var $eof_cdh = "\x50\x4b\x05\x06\x00\x00\x00\x00";
167 var $datasec_len = 0;
172 function compress_zip($mode, $file)
174 $this->fp = @fopen($file, $mode . 'b');
178 trigger_error('Unable to open file ' . $file . ' [' . $mode . 'b]');
183 * Convert unix to dos time
185 function unix_to_dos_time($time)
187 $timearray = (!$time) ? getdate() : getdate($time);
189 if ($timearray['year'] < 1980)
191 $timearray['year'] = 1980;
192 $timearray['mon'] = $timearray['mday'] = 1;
193 $timearray['hours'] = $timearray['minutes'] = $timearray['seconds'] = 0;
196 return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
202 function extract($dst)
204 // Loop the file, looking for files and folders
208 while (!feof($this->fp))
210 // Check if the signature is valid...
211 $signature = fread($this->fp, 4);
215 // 'Local File Header'
216 case "\x50\x4b\x03\x04":
217 // Lets get everything we need.
218 // We don't store the version needed to extract, the general purpose bit flag or the date and time fields
219 $data = unpack("@4/vc_method/@10/Vcrc/Vc_size/Vuc_size/vname_len/vextra_field", fread($this->fp, 26));
220 $file_name = fread($this->fp, $data['name_len']); // filename
222 if ($data['extra_field'])
224 fread($this->fp, $data['extra_field']); // extra field
227 $target_filename = "$dst$file_name";
229 if (!$data['uc_size'] && !$data['crc'] && substr($file_name, -1, 1) == '/')
231 if (!is_dir($target_filename))
234 $folders = explode('/', $target_filename);
236 // Create and folders and subfolders if they do not exist
237 foreach ($folders as $folder)
239 $folder = trim($folder);
245 $str = (!empty($str)) ? $str . '/' . $folder : $folder;
248 if (!@mkdir($str, 0777))
250 trigger_error("Could not create directory $folder");
252 phpbb_chmod($str, CHMOD_READ | CHMOD_WRITE);
256 // This is a directory, we are not writting files
261 // Some archivers are punks, they don't include folders in their archives!
263 $folders = explode('/', pathinfo($target_filename, PATHINFO_DIRNAME));
265 // Create and folders and subfolders if they do not exist
266 foreach ($folders as $folder)
268 $folder = trim($folder);
274 $str = (!empty($str)) ? $str . '/' . $folder : $folder;
277 if (!@mkdir($str, 0777))
279 trigger_error("Could not create directory $folder");
281 phpbb_chmod($str, CHMOD_READ | CHMOD_WRITE);
286 if (!$data['uc_size'])
292 $content = fread($this->fp, $data['c_size']);
295 $fp = fopen($target_filename, "w");
297 switch ($data['c_method'])
301 fwrite($fp, $content);
306 fwrite($fp, gzinflate($content, $data['uc_size']));
311 fwrite($fp, bzdecompress($content));
318 // We hit the 'Central Directory Header', we can stop because nothing else in here requires our attention
319 // or we hit the end of the central directory record, we can safely end the loop as we are totally finished with looking for files and folders
320 case "\x50\x4b\x01\x02":
321 // This case should simply never happen.. but it does exist..
322 case "\x50\x4b\x05\x06":
325 // 'Packed to Removable Disk', ignore it and look for the next signature...
329 // We have encountered a header that is weird. Lets look for better data...
333 // Unexpected header. Trying to detect wrong placed 'Data Descriptor';
335 fseek($this->fp, 8, SEEK_CUR); // Jump over 'crc-32'(4) 'compressed-size'(4), 'uncompressed-size'(4)
338 trigger_error("Unexpected header, ending loop");
351 // Write out central file directory and footer ... if it exists
352 if (sizeof($this->ctrl_dir))
354 fwrite($this->fp, $this->file());
360 * Create the structures ... note we assume version made by is MSDOS
362 function data($name, $data, $is_dir = false, $stat)
364 $name = str_replace('\\', '/', $name);
366 $hexdtime = pack('V', $this->unix_to_dos_time($stat[9]));
370 $unc_len = $c_len = $crc = 0;
376 $unc_len = strlen($data);
378 $zdata = gzdeflate($data);
379 $c_len = strlen($zdata);
382 // Did we compress? No, then use data as is
383 if ($c_len >= $unc_len)
392 // If we didn't compress set method to store, else deflate
393 $c_method = ($c_len == $unc_len) ? "\x00\x00" : "\x08\x00";
395 // Are we a file or a directory? Set archive for file
396 $attrib = ($is_dir) ? 16 : 32;
398 // File Record Header
399 $fr = "\x50\x4b\x03\x04"; // Local file header 4bytes
400 $fr .= pack('v', $var_ext); // ver needed to extract 2bytes
401 $fr .= "\x00\x00"; // gen purpose bit flag 2bytes
402 $fr .= $c_method; // compression method 2bytes
403 $fr .= $hexdtime; // last mod time and date 2+2bytes
404 $fr .= pack('V', $crc); // crc32 4bytes
405 $fr .= pack('V', $c_len); // compressed filesize 4bytes
406 $fr .= pack('V', $unc_len); // uncompressed filesize 4bytes
407 $fr .= pack('v', strlen($name));// length of filename 2bytes
409 $fr .= pack('v', 0); // extra field length 2bytes
414 $this->datasec_len += strlen($fr);
416 // Add data to file ... by writing data out incrementally we save some memory
417 fwrite($this->fp, $fr);
420 // Central Directory Header
421 $cdrec = "\x50\x4b\x01\x02"; // header 4bytes
422 $cdrec .= "\x00\x00"; // version made by
423 $cdrec .= pack('v', $var_ext); // version needed to extract
424 $cdrec .= "\x00\x00"; // gen purpose bit flag
425 $cdrec .= $c_method; // compression method
426 $cdrec .= $hexdtime; // last mod time & date
427 $cdrec .= pack('V', $crc); // crc32
428 $cdrec .= pack('V', $c_len); // compressed filesize
429 $cdrec .= pack('V', $unc_len); // uncompressed filesize
430 $cdrec .= pack('v', strlen($name)); // length of filename
431 $cdrec .= pack('v', 0); // extra field length
432 $cdrec .= pack('v', 0); // file comment length
433 $cdrec .= pack('v', 0); // disk number start
434 $cdrec .= pack('v', 0); // internal file attributes
435 $cdrec .= pack('V', $attrib); // external file attributes
436 $cdrec .= pack('V', $this->old_offset); // relative offset of local header
439 // Save to central directory
440 $this->ctrl_dir[] = $cdrec;
442 $this->old_offset = $this->datasec_len;
450 $ctrldir = implode('', $this->ctrl_dir);
452 return $ctrldir . $this->eof_cdh .
453 pack('v', sizeof($this->ctrl_dir)) . // total # of entries "on this disk"
454 pack('v', sizeof($this->ctrl_dir)) . // total # of entries overall
455 pack('V', strlen($ctrldir)) . // size of central dir
456 pack('V', $this->datasec_len) . // offset to start of central dir
457 "\x00\x00"; // .zip file comment length
463 function download($filename, $download_name = false)
465 global $phpbb_root_path;
467 if ($download_name === false)
469 $download_name = $filename;
472 $mimetype = 'application/zip';
474 header('Pragma: no-cache');
475 header("Content-Type: $mimetype; name=\"$download_name.zip\"");
476 header("Content-disposition: attachment; filename=$download_name.zip");
478 $fp = @fopen("{$phpbb_root_path}store/$filename.zip", 'rb');
481 while ($buffer = fread($fp, 1024))
491 * Tar/tar.gz compression routine
492 * Header/checksum creation derived from tarfile.pl, (c) Tom Horsley, 1994
496 class compress_tar extends compress
508 function compress_tar($mode, $file, $type = '')
510 $type = (!$type) ? $file : $type;
511 $this->isgz = preg_match('#(\.tar\.gz|\.tgz)$#', $type);
512 $this->isbz = preg_match('#\.tar\.bz2$#', $type);
514 $this->mode = &$mode;
515 $this->file = &$file;
516 $this->type = &$type;
523 function extract($dst)
525 $fzread = ($this->isbz && function_exists('bzread')) ? 'bzread' : (($this->isgz && @extension_loaded('zlib')) ? 'gzread' : 'fread');
527 // Run through the file and grab directory entries
528 while ($buffer = $fzread($this->fp, 512))
530 $tmp = unpack('A6magic', substr($buffer, 257, 6));
532 if (trim($tmp['magic']) == 'ustar')
534 $tmp = unpack('A100name', $buffer);
535 $filename = trim($tmp['name']);
537 $tmp = unpack('Atype', substr($buffer, 156, 1));
538 $filetype = (int) trim($tmp['type']);
540 $tmp = unpack('A12size', substr($buffer, 124, 12));
541 $filesize = octdec((int) trim($tmp['size']));
543 $target_filename = "$dst$filename";
547 if (!is_dir($target_filename))
550 $folders = explode('/', $target_filename);
552 // Create and folders and subfolders if they do not exist
553 foreach ($folders as $folder)
555 $folder = trim($folder);
561 $str = (!empty($str)) ? $str . '/' . $folder : $folder;
564 if (!@mkdir($str, 0777))
566 trigger_error("Could not create directory $folder");
568 phpbb_chmod($str, CHMOD_READ | CHMOD_WRITE);
573 else if ($filesize >= 0 && ($filetype == 0 || $filetype == "\0"))
575 // Some archivers are punks, they don't properly order the folders in their archives!
577 $folders = explode('/', pathinfo($target_filename, PATHINFO_DIRNAME));
579 // Create and folders and subfolders if they do not exist
580 foreach ($folders as $folder)
582 $folder = trim($folder);
588 $str = (!empty($str)) ? $str . '/' . $folder : $folder;
591 if (!@mkdir($str, 0777))
593 trigger_error("Could not create directory $folder");
595 phpbb_chmod($str, CHMOD_READ | CHMOD_WRITE);
599 // Write out the files
600 if (!($fp = fopen($target_filename, 'wb')))
602 trigger_error("Couldn't create file $filename");
604 phpbb_chmod($target_filename, CHMOD_READ);
606 // Grab the file contents
607 fwrite($fp, ($filesize) ? $fzread($this->fp, ($filesize + 511) &~ 511) : '', $filesize);
619 $fzclose = ($this->isbz && function_exists('bzclose')) ? 'bzclose' : (($this->isgz && @extension_loaded('zlib')) ? 'gzclose' : 'fclose');
623 $fzwrite = ($this->isbz && function_exists('bzwrite')) ? 'bzwrite' : (($this->isgz && @extension_loaded('zlib')) ? 'gzwrite' : 'fwrite');
625 // The end of a tar archive ends in two records of all NULLs (1024 bytes of \0)
626 $fzwrite($this->fp, str_repeat("\0", 1024));
633 * Create the structures
635 function data($name, $data, $is_dir = false, $stat)
638 $fzwrite = ($this->isbz && function_exists('bzwrite')) ? 'bzwrite' : (($this->isgz && @extension_loaded('zlib')) ? 'gzwrite' : 'fwrite');
640 $typeflag = ($is_dir) ? '5' : '';
642 // This is the header data, it contains all the info we know about the file or folder that we are about to archive
644 $header .= pack('a100', $name); // file name
645 $header .= pack('a8', sprintf("%07o", $stat[2])); // file mode
646 $header .= pack('a8', sprintf("%07o", $stat[4])); // owner id
647 $header .= pack('a8', sprintf("%07o", $stat[5])); // group id
648 $header .= pack('a12', sprintf("%011o", $stat[7])); // file size
649 $header .= pack('a12', sprintf("%011o", $stat[9])); // last mod time
653 for ($i = 0; $i < 148; $i++)
655 $checksum += ord($header[$i]);
658 // We precompute the rest of the hash, this saves us time in the loop and allows us to insert our hash without resorting to string functions
659 $checksum += 2415 + (($is_dir) ? 53 : 0);
661 $header .= pack('a8', sprintf("%07o", $checksum)); // checksum
662 $header .= pack('a1', $typeflag); // link indicator
663 $header .= pack('a100', ''); // name of linked file
664 $header .= pack('a6', 'ustar'); // ustar indicator
665 $header .= pack('a2', '00'); // ustar version
666 $header .= pack('a32', 'Unknown'); // owner name
667 $header .= pack('a32', 'Unknown'); // group name
668 $header .= pack('a8', ''); // device major number
669 $header .= pack('a8', ''); // device minor number
670 $header .= pack('a155', ''); // filename prefix
671 $header .= pack('a12', ''); // end
673 // This writes the entire file in one shot. Header, followed by data and then null padded to a multiple of 512
674 $fzwrite($this->fp, $header . (($stat[7] !== 0 && !$is_dir) ? $data . str_repeat("\0", (($stat[7] + 511) &~ 511) - $stat[7]) : ''));
683 $fzopen = ($this->isbz && function_exists('bzopen')) ? 'bzopen' : (($this->isgz && @extension_loaded('zlib')) ? 'gzopen' : 'fopen');
684 $this->fp = @$fzopen($this->file, $this->mode . (($fzopen == 'bzopen') ? '' : 'b') . (($fzopen == 'gzopen') ? '9' : ''));
688 trigger_error('Unable to open file ' . $this->file . ' [' . $fzopen . ' - ' . $this->mode . 'b]');
695 function download($filename, $download_name = false)
697 global $phpbb_root_path;
699 if ($download_name === false)
701 $download_name = $filename;
707 $mimetype = 'application/x-tar';
711 $mimetype = 'application/x-gzip';
715 $mimetype = 'application/x-bzip2';
719 $mimetype = 'application/octet-stream';
723 header('Pragma: no-cache');
724 header("Content-Type: $mimetype; name=\"$download_name$this->type\"");
725 header("Content-disposition: attachment; filename=$download_name$this->type");
727 $fp = @fopen("{$phpbb_root_path}store/$filename$this->type", 'rb');
730 while ($buffer = fread($fp, 1024))