source: branches/beta/data/module/Tar.php @ 8

Revision 8, 57.9 KB checked in by root, 17 years ago (diff)

new import

Line 
1<?php
2/* vim: set ts=4 sw=4: */
3// +----------------------------------------------------------------------+
4// | PHP Version 4                                                        |
5// +----------------------------------------------------------------------+
6// | Copyright (c) 1997-2003 The PHP Group                                |
7// +----------------------------------------------------------------------+
8// | This source file is subject to version 3.0 of the PHP license,       |
9// | that is bundled with this package in the file LICENSE, and is        |
10// | available through the world-wide-web at the following url:           |
11// | http://www.php.net/license/3_0.txt.                                  |
12// | If you did not receive a copy of the PHP license and are unable to   |
13// | obtain it through the world-wide-web, please send a note to          |
14// | license@php.net so we can mail you a copy immediately.               |
15// +----------------------------------------------------------------------+
16// | Author: Vincent Blavet <vincent@phpconcept.net>                      |
17// +----------------------------------------------------------------------+
18//
19// $Id: Tar.php 4772 2006-10-12 06:52:48Z naka $
20
21if(!defined('TAR_PHP_DIR')) {
22    $TAR_PHP_DIR = realpath(dirname( __FILE__));
23    define("TAR_PHP_DIR", $TAR_PHP_DIR);   
24}
25
26require_once TAR_PHP_DIR . '/PEAR.php';
27
28
29define ('ARCHIVE_TAR_ATT_SEPARATOR', 90001);
30
31/**
32* Creates a (compressed) Tar archive
33*
34* @author   Vincent Blavet <vincent@phpconcept.net>
35* @version  $Revision: 4772 $
36* @package  Archive
37*/
38class Archive_Tar extends PEAR
39{
40    /**
41    * @var string Name of the Tar
42    */
43    var $_tarname='';
44
45    /**
46    * @var boolean if true, the Tar file will be gzipped
47    */
48    var $_compress=false;
49
50    /**
51    * @var string Type of compression : 'none', 'gz' or 'bz2'
52    */
53    var $_compress_type='none';
54
55    /**
56    * @var string Explode separator
57    */
58    var $_separator=' ';
59
60    /**
61    * @var file descriptor
62    */
63    var $_file=0;
64
65    /**
66    * @var string Local Tar name of a remote Tar (http:// or ftp://)
67    */
68    var $_temp_tarname='';
69
70    // {{{ constructor
71    /**
72    * Archive_Tar Class constructor. This flavour of the constructor only
73    * declare a new Archive_Tar object, identifying it by the name of the
74    * tar file.
75    * If the compress argument is set the tar will be read or created as a
76    * gzip or bz2 compressed TAR file.
77    *
78    * @param    string  $p_tarname  The name of the tar archive to create
79    * @param    string  $p_compress can be null, 'gz' or 'bz2'. This
80    *                   parameter indicates if gzip or bz2 compression
81    *                   is required.  For compatibility reason the
82    *                   boolean value 'true' means 'gz'.
83    * @access public
84    */
85    function Archive_Tar($p_tarname, $p_compress = null)
86    {
87        $this->PEAR();
88        $this->_compress = false;
89        $this->_compress_type = 'none';
90        if (($p_compress === null) || ($p_compress == '')) {
91            if (@file_exists($p_tarname)) {
92                if ($fp = @fopen($p_tarname, "rb")) {
93                    // look for gzip magic cookie
94                    $data = fread($fp, 2);
95                    fclose($fp);
96                    if ($data == "\37\213") {
97                        $this->_compress = true;
98                        $this->_compress_type = 'gz';
99                    // No sure it's enought for a magic code ....
100                    } elseif ($data == "BZ") {
101                        $this->_compress = true;
102                        $this->_compress_type = 'bz2';
103                    }
104                }
105            } else {
106                // probably a remote file or some file accessible
107                // through a stream interface
108                if (substr($p_tarname, -2) == 'gz') {
109                    $this->_compress = true;
110                    $this->_compress_type = 'gz';
111                } elseif ((substr($p_tarname, -3) == 'bz2') ||
112                          (substr($p_tarname, -2) == 'bz')) {
113                    $this->_compress = true;
114                    $this->_compress_type = 'bz2';
115                }
116            }
117        } else {
118            if (($p_compress === true) || ($p_compress == 'gz')) {
119                $this->_compress = true;
120                $this->_compress_type = 'gz';
121            } else if ($p_compress == 'bz2') {
122                $this->_compress = true;
123                $this->_compress_type = 'bz2';
124            } else {
125                die("Unsupported compression type '$p_compress'\n".
126                    "Supported types are 'gz' and 'bz2'.\n");
127                return false;
128            }
129        }
130        $this->_tarname = $p_tarname;
131        if ($this->_compress) { // assert zlib or bz2 extension support
132            if ($this->_compress_type == 'gz')
133                $extname = 'zlib';
134            else if ($this->_compress_type == 'bz2')
135                $extname = 'bz2';
136
137            if (!extension_loaded($extname)) {
138                PEAR::loadExtension($extname);
139            }
140            if (!extension_loaded($extname)) {
141                die("The extension '$extname' couldn't be found.\n".
142                    "Please make sure your version of PHP was built ".
143                    "with '$extname' support.\n");
144                return false;
145            }
146        }
147    }
148    // }}}
149
150    // {{{ destructor
151    function _Archive_Tar()
152    {
153        $this->_close();
154        // ----- Look for a local copy to delete
155        if ($this->_temp_tarname != '')
156            @unlink($this->_temp_tarname);
157        $this->_PEAR();
158    }
159    // }}}
160
161    // {{{ create()
162    /**
163    * This method creates the archive file and add the files / directories
164    * that are listed in $p_filelist.
165    * If a file with the same name exist and is writable, it is replaced
166    * by the new tar.
167    * The method return false and a PEAR error text.
168    * The $p_filelist parameter can be an array of string, each string
169    * representing a filename or a directory name with their path if
170    * needed. It can also be a single string with names separated by a
171    * single blank.
172    * For each directory added in the archive, the files and
173    * sub-directories are also added.
174    * See also createModify() method for more details.
175    *
176    * @param array  $p_filelist An array of filenames and directory names, or a
177    *                           single string with names separated by a single
178    *                           blank space.
179    * @return                   true on success, false on error.
180    * @see createModify()
181    * @access public
182    */
183    function create($p_filelist)
184    {
185        return $this->createModify($p_filelist, '', '');
186    }
187    // }}}
188
189    // {{{ add()
190    /**
191    * This method add the files / directories that are listed in $p_filelist in
192    * the archive. If the archive does not exist it is created.
193    * The method return false and a PEAR error text.
194    * The files and directories listed are only added at the end of the archive,
195    * even if a file with the same name is already archived.
196    * See also createModify() method for more details.
197    *
198    * @param array  $p_filelist An array of filenames and directory names, or a
199    *                           single string with names separated by a single
200    *                           blank space.
201    * @return                   true on success, false on error.
202    * @see createModify()
203    * @access public
204    */
205    function add($p_filelist)
206    {
207        return $this->addModify($p_filelist, '', '');
208    }
209    // }}}
210
211    // {{{ extract()
212    function extract($p_path='')
213    {
214        return $this->extractModify($p_path, '');
215    }
216    // }}}
217
218    // {{{ listContent()
219    function listContent()
220    {
221        $v_list_detail = array();
222
223        if ($this->_openRead()) {
224            if (!$this->_extractList('', $v_list_detail, "list", '', '')) {
225                unset($v_list_detail);
226                $v_list_detail = 0;
227            }
228            $this->_close();
229        }
230
231        return $v_list_detail;
232    }
233    // }}}
234
235    // {{{ createModify()
236    /**
237    * This method creates the archive file and add the files / directories
238    * that are listed in $p_filelist.
239    * If the file already exists and is writable, it is replaced by the
240    * new tar. It is a create and not an add. If the file exists and is
241    * read-only or is a directory it is not replaced. The method return
242    * false and a PEAR error text.
243    * The $p_filelist parameter can be an array of string, each string
244    * representing a filename or a directory name with their path if
245    * needed. It can also be a single string with names separated by a
246    * single blank.
247    * The path indicated in $p_remove_dir will be removed from the
248    * memorized path of each file / directory listed when this path
249    * exists. By default nothing is removed (empty path '')
250    * The path indicated in $p_add_dir will be added at the beginning of
251    * the memorized path of each file / directory listed. However it can
252    * be set to empty ''. The adding of a path is done after the removing
253    * of path.
254    * The path add/remove ability enables the user to prepare an archive
255    * for extraction in a different path than the origin files are.
256    * See also addModify() method for file adding properties.
257    *
258    * @param array  $p_filelist     An array of filenames and directory names,
259    *                               or a single string with names separated by
260    *                               a single blank space.
261    * @param string $p_add_dir      A string which contains a path to be added
262    *                               to the memorized path of each element in
263    *                               the list.
264    * @param string $p_remove_dir   A string which contains a path to be
265    *                               removed from the memorized path of each
266    *                               element in the list, when relevant.
267    * @return boolean               true on success, false on error.
268    * @access public
269    * @see addModify()
270    */
271    function createModify($p_filelist, $p_add_dir, $p_remove_dir='')
272    {
273        $v_result = true;
274
275        if (!$this->_openWrite())
276            return false;
277
278        if ($p_filelist != '') {
279            if (is_array($p_filelist))
280                $v_list = $p_filelist;
281            elseif (is_string($p_filelist))
282                $v_list = explode($this->_separator, $p_filelist);
283            else {
284                $this->_cleanFile();
285                $this->_error('Invalid file list');
286                return false;
287            }
288
289            $v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir);
290        }
291
292        if ($v_result) {
293            $this->_writeFooter();
294            $this->_close();
295        } else
296            $this->_cleanFile();
297
298        return $v_result;
299    }
300    // }}}
301
302    // {{{ addModify()
303    /**
304    * This method add the files / directories listed in $p_filelist at the
305    * end of the existing archive. If the archive does not yet exists it
306    * is created.
307    * The $p_filelist parameter can be an array of string, each string
308    * representing a filename or a directory name with their path if
309    * needed. It can also be a single string with names separated by a
310    * single blank.
311    * The path indicated in $p_remove_dir will be removed from the
312    * memorized path of each file / directory listed when this path
313    * exists. By default nothing is removed (empty path '')
314    * The path indicated in $p_add_dir will be added at the beginning of
315    * the memorized path of each file / directory listed. However it can
316    * be set to empty ''. The adding of a path is done after the removing
317    * of path.
318    * The path add/remove ability enables the user to prepare an archive
319    * for extraction in a different path than the origin files are.
320    * If a file/dir is already in the archive it will only be added at the
321    * end of the archive. There is no update of the existing archived
322    * file/dir. However while extracting the archive, the last file will
323    * replace the first one. This results in a none optimization of the
324    * archive size.
325    * If a file/dir does not exist the file/dir is ignored. However an
326    * error text is send to PEAR error.
327    * If a file/dir is not readable the file/dir is ignored. However an
328    * error text is send to PEAR error.
329    *
330    * @param array      $p_filelist     An array of filenames and directory
331    *                                   names, or a single string with names
332    *                                   separated by a single blank space.
333    * @param string     $p_add_dir      A string which contains a path to be
334    *                                   added to the memorized path of each
335    *                                   element in the list.
336    * @param string     $p_remove_dir   A string which contains a path to be
337    *                                   removed from the memorized path of
338    *                                   each element in the list, when
339    *                                   relevant.
340    * @return                           true on success, false on error.
341    * @access public
342    */
343    function addModify($p_filelist, $p_add_dir, $p_remove_dir='')
344    {
345        $v_result = true;
346
347        if (!$this->_isArchive())
348            $v_result = $this->createModify($p_filelist, $p_add_dir,
349                                            $p_remove_dir);
350        else {
351            if (is_array($p_filelist))
352                $v_list = $p_filelist;
353            elseif (is_string($p_filelist))
354                $v_list = explode($this->_separator, $p_filelist);
355            else {
356                $this->_error('Invalid file list');
357                return false;
358            }
359
360            $v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir);
361        }
362
363        return $v_result;
364    }
365    // }}}
366
367    // {{{ addString()
368    /**
369    * This method add a single string as a file at the
370    * end of the existing archive. If the archive does not yet exists it
371    * is created.
372    *
373    * @param string     $p_filename     A string which contains the full
374    *                                   filename path that will be associated
375    *                                   with the string.
376    * @param string     $p_string       The content of the file added in
377    *                                   the archive.
378    * @return                           true on success, false on error.
379    * @access public
380    */
381    function addString($p_filename, $p_string)
382    {
383        $v_result = true;
384       
385        if (!$this->_isArchive()) {
386            if (!$this->_openWrite()) {
387                return false;
388            }
389            $this->_close();
390        }
391       
392        if (!$this->_openAppend())
393            return false;
394
395        // Need to check the get back to the temporary file ? ....
396        $v_result = $this->_addString($p_filename, $p_string);
397
398        $this->_writeFooter();
399
400        $this->_close();
401
402        return $v_result;
403    }
404    // }}}
405
406    // {{{ extractModify()
407    /**
408    * This method extract all the content of the archive in the directory
409    * indicated by $p_path. When relevant the memorized path of the
410    * files/dir can be modified by removing the $p_remove_path path at the
411    * beginning of the file/dir path.
412    * While extracting a file, if the directory path does not exists it is
413    * created.
414    * While extracting a file, if the file already exists it is replaced
415    * without looking for last modification date.
416    * While extracting a file, if the file already exists and is write
417    * protected, the extraction is aborted.
418    * While extracting a file, if a directory with the same name already
419    * exists, the extraction is aborted.
420    * While extracting a directory, if a file with the same name already
421    * exists, the extraction is aborted.
422    * While extracting a file/directory if the destination directory exist
423    * and is write protected, or does not exist but can not be created,
424    * the extraction is aborted.
425    * If after extraction an extracted file does not show the correct
426    * stored file size, the extraction is aborted.
427    * When the extraction is aborted, a PEAR error text is set and false
428    * is returned. However the result can be a partial extraction that may
429    * need to be manually cleaned.
430    *
431    * @param string $p_path         The path of the directory where the
432    *                               files/dir need to by extracted.
433    * @param string $p_remove_path  Part of the memorized path that can be
434    *                               removed if present at the beginning of
435    *                               the file/dir path.
436    * @return boolean               true on success, false on error.
437    * @access public
438    * @see extractList()
439    */
440    function extractModify($p_path, $p_remove_path)
441    {
442        $v_result = true;
443        $v_list_detail = array();
444
445        if ($v_result = $this->_openRead()) {
446            $v_result = $this->_extractList($p_path, $v_list_detail,
447                                            "complete", 0, $p_remove_path);
448            $this->_close();
449        }
450
451        return $v_result;
452    }
453    // }}}
454
455    // {{{ extractInString()
456    /**
457    * This method extract from the archive one file identified by $p_filename.
458    * The return value is a string with the file content, or NULL on error.
459    * @param string $p_filename     The path of the file to extract in a string.
460    * @return                       a string with the file content or NULL.
461    * @access public
462    */
463    function extractInString($p_filename)
464    {
465        if ($this->_openRead()) {
466            $v_result = $this->_extractInString($p_filename);
467            $this->_close();
468        } else {
469            $v_result = NULL;
470        }
471
472        return $v_result;
473    }
474    // }}}
475
476    // {{{ extractList()
477    /**
478    * This method extract from the archive only the files indicated in the
479    * $p_filelist. These files are extracted in the current directory or
480    * in the directory indicated by the optional $p_path parameter.
481    * If indicated the $p_remove_path can be used in the same way as it is
482    * used in extractModify() method.
483    * @param array  $p_filelist     An array of filenames and directory names,
484    *                               or a single string with names separated
485    *                               by a single blank space.
486    * @param string $p_path         The path of the directory where the
487    *                               files/dir need to by extracted.
488    * @param string $p_remove_path  Part of the memorized path that can be
489    *                               removed if present at the beginning of
490    *                               the file/dir path.
491    * @return                       true on success, false on error.
492    * @access public
493    * @see extractModify()
494    */
495    function extractList($p_filelist, $p_path='', $p_remove_path='')
496    {
497        $v_result = true;
498        $v_list_detail = array();
499
500        if (is_array($p_filelist))
501            $v_list = $p_filelist;
502        elseif (is_string($p_filelist))
503            $v_list = explode($this->_separator, $p_filelist);
504        else {
505            $this->_error('Invalid string list');
506            return false;
507        }
508
509        if ($v_result = $this->_openRead()) {
510            $v_result = $this->_extractList($p_path, $v_list_detail, "partial",
511                                            $v_list, $p_remove_path);
512            $this->_close();
513        }
514
515        return $v_result;
516    }
517    // }}}
518
519    // {{{ setAttribute()
520    /**
521    * This method set specific attributes of the archive. It uses a variable
522    * list of parameters, in the format attribute code + attribute values :
523    * $arch->setAttribute(ARCHIVE_TAR_ATT_SEPARATOR, ',');
524    * @param mixed $argv            variable list of attributes and values
525    * @return                       true on success, false on error.
526    * @access public
527    */
528    function setAttribute()
529    {
530        $v_result = true;
531       
532        // ----- Get the number of variable list of arguments
533        if (($v_size = func_num_args()) == 0) {
534            return true;
535        }
536       
537        // ----- Get the arguments
538        $v_att_list = &func_get_args();
539
540        // ----- Read the attributes
541        $i=0;
542        while ($i<$v_size) {
543
544            // ----- Look for next option
545            switch ($v_att_list[$i]) {
546                // ----- Look for options that request a string value
547                case ARCHIVE_TAR_ATT_SEPARATOR :
548                    // ----- Check the number of parameters
549                    if (($i+1) >= $v_size) {
550                        $this->_error('Invalid number of parameters for '
551                                      .'attribute ARCHIVE_TAR_ATT_SEPARATOR');
552                        return false;
553                    }
554
555                    // ----- Get the value
556                    $this->_separator = $v_att_list[$i+1];
557                    $i++;
558                break;
559
560                default :
561                    $this->_error('Unknow attribute code '.$v_att_list[$i].'');
562                    return false;
563            }
564
565            // ----- Next attribute
566            $i++;
567        }
568
569        return $v_result;
570    }
571    // }}}
572
573    // {{{ _error()
574    function _error($p_message)
575    {
576        // ----- To be completed
577        $this->raiseError($p_message);
578    }
579    // }}}
580
581    // {{{ _warning()
582    function _warning($p_message)
583    {
584        // ----- To be completed
585        $this->raiseError($p_message);
586    }
587    // }}}
588
589    // {{{ _isArchive()
590    function _isArchive($p_filename=NULL)
591    {
592        if ($p_filename == NULL) {
593            $p_filename = $this->_tarname;
594        }
595        clearstatcache();
596        return @is_file($p_filename);
597    }
598    // }}}
599
600    // {{{ _openWrite()
601    function _openWrite()
602    {
603        if ($this->_compress_type == 'gz')
604            $this->_file = @gzopen($this->_tarname, "wb9");
605        else if ($this->_compress_type == 'bz2')
606            $this->_file = @bzopen($this->_tarname, "wb");
607        else if ($this->_compress_type == 'none')
608            $this->_file = @fopen($this->_tarname, "wb");
609        else
610            $this->_error('Unknown or missing compression type ('
611                          .$this->_compress_type.')');
612
613        if ($this->_file == 0) {
614            $this->_error('Unable to open in write mode \''
615                          .$this->_tarname.'\'');
616            return false;
617        }
618
619        return true;
620    }
621    // }}}
622
623    // {{{ _openRead()
624    function _openRead()
625    {
626        if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') {
627
628          // ----- Look if a local copy need to be done
629          if ($this->_temp_tarname == '') {
630              $this->_temp_tarname = uniqid('tar').'.tmp';
631              if (!$v_file_from = @fopen($this->_tarname, 'rb')) {
632                $this->_error('Unable to open in read mode \''
633                              .$this->_tarname.'\'');
634                $this->_temp_tarname = '';
635                return false;
636              }
637              if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) {
638                $this->_error('Unable to open in write mode \''
639                              .$this->_temp_tarname.'\'');
640                $this->_temp_tarname = '';
641                return false;
642              }
643              while ($v_data = @fread($v_file_from, 1024))
644                  @fwrite($v_file_to, $v_data);
645              @fclose($v_file_from);
646              @fclose($v_file_to);
647          }
648
649          // ----- File to open if the local copy
650          $v_filename = $this->_temp_tarname;
651
652        } else
653          // ----- File to open if the normal Tar file
654          $v_filename = $this->_tarname;
655
656        if ($this->_compress_type == 'gz')
657            $this->_file = @gzopen($v_filename, "rb");
658        else if ($this->_compress_type == 'bz2')
659            $this->_file = @bzopen($v_filename, "rb");
660        else if ($this->_compress_type == 'none')
661            $this->_file = @fopen($v_filename, "rb");
662        else
663            $this->_error('Unknown or missing compression type ('
664                          .$this->_compress_type.')');
665
666        if ($this->_file == 0) {
667            $this->_error('Unable to open in read mode \''.$v_filename.'\'');
668            return false;
669        }
670
671        return true;
672    }
673    // }}}
674
675    // {{{ _openReadWrite()
676    function _openReadWrite()
677    {
678        if ($this->_compress_type == 'gz')
679            $this->_file = @gzopen($this->_tarname, "r+b");
680        else if ($this->_compress_type == 'bz2')
681            $this->_file = @bzopen($this->_tarname, "r+b");
682        else if ($this->_compress_type == 'none')
683            $this->_file = @fopen($this->_tarname, "r+b");
684        else
685            $this->_error('Unknown or missing compression type ('
686                          .$this->_compress_type.')');
687
688        if ($this->_file == 0) {
689            $this->_error('Unable to open in read/write mode \''
690                          .$this->_tarname.'\'');
691            return false;
692        }
693
694        return true;
695    }
696    // }}}
697
698    // {{{ _close()
699    function _close()
700    {
701        //if (isset($this->_file)) {
702        if (is_resource($this->_file)) {
703            if ($this->_compress_type == 'gz')
704                @gzclose($this->_file);
705            else if ($this->_compress_type == 'bz2')
706                @bzclose($this->_file);
707            else if ($this->_compress_type == 'none')
708                @fclose($this->_file);
709            else
710                $this->_error('Unknown or missing compression type ('
711                              .$this->_compress_type.')');
712
713            $this->_file = 0;
714        }
715
716        // ----- Look if a local copy need to be erase
717        // Note that it might be interesting to keep the url for a time : ToDo
718        if ($this->_temp_tarname != '') {
719            @unlink($this->_temp_tarname);
720            $this->_temp_tarname = '';
721        }
722
723        return true;
724    }
725    // }}}
726
727    // {{{ _cleanFile()
728    function _cleanFile()
729    {
730        $this->_close();
731
732        // ----- Look for a local copy
733        if ($this->_temp_tarname != '') {
734            // ----- Remove the local copy but not the remote tarname
735            @unlink($this->_temp_tarname);
736            $this->_temp_tarname = '';
737        } else {
738            // ----- Remove the local tarname file
739            @unlink($this->_tarname);
740        }
741        $this->_tarname = '';
742
743        return true;
744    }
745    // }}}
746
747    // {{{ _writeBlock()
748    function _writeBlock($p_binary_data, $p_len=null)
749    {
750      if (is_resource($this->_file)) {
751          if ($p_len === null) {
752              if ($this->_compress_type == 'gz')
753                  @gzputs($this->_file, $p_binary_data);
754              else if ($this->_compress_type == 'bz2')
755                  @bzwrite($this->_file, $p_binary_data);
756              else if ($this->_compress_type == 'none')
757                  @fputs($this->_file, $p_binary_data);
758              else
759                  $this->_error('Unknown or missing compression type ('
760                                .$this->_compress_type.')');
761          } else {
762              if ($this->_compress_type == 'gz')
763                  @gzputs($this->_file, $p_binary_data, $p_len);
764              else if ($this->_compress_type == 'bz2')
765                  @bzwrite($this->_file, $p_binary_data, $p_len);
766              else if ($this->_compress_type == 'none')
767                  @fputs($this->_file, $p_binary_data, $p_len);
768              else
769                  $this->_error('Unknown or missing compression type ('
770                                .$this->_compress_type.')');
771
772          }
773      }
774      return true;
775    }
776    // }}}
777
778    // {{{ _readBlock()
779    function _readBlock()
780    {
781      $v_block = null;
782      if (is_resource($this->_file)) {
783          if ($this->_compress_type == 'gz')
784              $v_block = @gzread($this->_file, 512);
785          else if ($this->_compress_type == 'bz2')
786              $v_block = @bzread($this->_file, 512);
787          else if ($this->_compress_type == 'none')
788              $v_block = @fread($this->_file, 512);
789          else
790              $this->_error('Unknown or missing compression type ('
791                            .$this->_compress_type.')');
792      }
793      return $v_block;
794    }
795    // }}}
796
797    // {{{ _jumpBlock()
798    function _jumpBlock($p_len=null)
799    {
800      if (is_resource($this->_file)) {
801          if ($p_len === null)
802              $p_len = 1;
803
804          if ($this->_compress_type == 'gz') {
805              @gzseek($this->_file, @gztell($this->_file)+($p_len*512));
806          }
807          else if ($this->_compress_type == 'bz2') {
808              // ----- Replace missing bztell() and bzseek()
809              for ($i=0; $i<$p_len; $i++)
810                  $this->_readBlock();
811          } else if ($this->_compress_type == 'none')
812              @fseek($this->_file, @ftell($this->_file)+($p_len*512));
813          else
814              $this->_error('Unknown or missing compression type ('
815                            .$this->_compress_type.')');
816
817      }
818      return true;
819    }
820    // }}}
821
822    // {{{ _writeFooter()
823    function _writeFooter()
824    {
825      if (is_resource($this->_file)) {
826          // ----- Write the last 0 filled block for end of archive
827          $v_binary_data = pack("a512", '');
828          $this->_writeBlock($v_binary_data);
829      }
830      return true;
831    }
832    // }}}
833
834    // {{{ _addList()
835    function _addList($p_list, $p_add_dir, $p_remove_dir)
836    {
837      $v_result=true;
838      $v_header = array();
839
840      // ----- Remove potential windows directory separator
841      $p_add_dir = $this->_translateWinPath($p_add_dir);
842      $p_remove_dir = $this->_translateWinPath($p_remove_dir, false);
843
844      if (!$this->_file) {
845          $this->_error('Invalid file descriptor');
846          return false;
847      }
848
849      if (sizeof($p_list) == 0)
850          return true;
851
852      foreach ($p_list as $v_filename) {
853          if (!$v_result) {
854              break;
855          }
856
857        // ----- Skip the current tar name
858        if ($v_filename == $this->_tarname)
859            continue;
860
861        if ($v_filename == '')
862            continue;
863
864        if (!file_exists($v_filename)) {
865            $this->_warning("File '$v_filename' does not exist");
866            continue;
867        }
868
869        // ----- Add the file or directory header
870        if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir))
871            return false;
872
873        if (@is_dir($v_filename)) {
874            if (!($p_hdir = opendir($v_filename))) {
875                $this->_warning("Directory '$v_filename' can not be read");
876                continue;
877            }
878            while (false !== ($p_hitem = readdir($p_hdir))) {
879                if (($p_hitem != '.') && ($p_hitem != '..')) {
880                    if ($v_filename != ".")
881                        $p_temp_list[0] = $v_filename.'/'.$p_hitem;
882                    else
883                        $p_temp_list[0] = $p_hitem;
884
885                    $v_result = $this->_addList($p_temp_list,
886                                                $p_add_dir,
887                                                $p_remove_dir);
888                }
889            }
890
891            unset($p_temp_list);
892            unset($p_hdir);
893            unset($p_hitem);
894        }
895      }
896
897      return $v_result;
898    }
899    // }}}
900
901    // {{{ _addFile()
902    function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir)
903    {
904      if (!$this->_file) {
905          $this->_error('Invalid file descriptor');
906          return false;
907      }
908
909      if ($p_filename == '') {
910          $this->_error('Invalid file name');
911          return false;
912      }
913
914      // ----- Calculate the stored filename
915      $p_filename = $this->_translateWinPath($p_filename, false);;
916      $v_stored_filename = $p_filename;
917      if (strcmp($p_filename, $p_remove_dir) == 0) {
918          return true;
919      }
920      if ($p_remove_dir != '') {
921          if (substr($p_remove_dir, -1) != '/')
922              $p_remove_dir .= '/';
923
924          if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir)
925              $v_stored_filename = substr($p_filename, strlen($p_remove_dir));
926      }
927      $v_stored_filename = $this->_translateWinPath($v_stored_filename);
928      if ($p_add_dir != '') {
929          if (substr($p_add_dir, -1) == '/')
930              $v_stored_filename = $p_add_dir.$v_stored_filename;
931          else
932              $v_stored_filename = $p_add_dir.'/'.$v_stored_filename;
933      }
934
935      $v_stored_filename = $this->_pathReduction($v_stored_filename);
936
937      if ($this->_isArchive($p_filename)) {
938          if (($v_file = @fopen($p_filename, "rb")) == 0) {
939              $this->_warning("Unable to open file '".$p_filename
940                              ."' in binary read mode");
941              return true;
942          }
943
944          if (!$this->_writeHeader($p_filename, $v_stored_filename))
945              return false;
946
947          while (($v_buffer = fread($v_file, 512)) != '') {
948              $v_binary_data = pack("a512", "$v_buffer");
949              $this->_writeBlock($v_binary_data);
950          }
951
952          fclose($v_file);
953
954      } else {
955          // ----- Only header for dir
956          if (!$this->_writeHeader($p_filename, $v_stored_filename))
957              return false;
958      }
959
960      return true;
961    }
962    // }}}
963
964    // {{{ _addString()
965    function _addString($p_filename, $p_string)
966    {
967      if (!$this->_file) {
968          $this->_error('Invalid file descriptor');
969          return false;
970      }
971
972      if ($p_filename == '') {
973          $this->_error('Invalid file name');
974          return false;
975      }
976
977      // ----- Calculate the stored filename
978      $p_filename = $this->_translateWinPath($p_filename, false);;
979
980      if (!$this->_writeHeaderBlock($p_filename, strlen($p_string),
981                                    0, 0, "", 0, 0))
982          return false;
983
984      $i=0;
985      while (($v_buffer = substr($p_string, (($i++)*512), 512)) != '') {
986          $v_binary_data = pack("a512", $v_buffer);
987          $this->_writeBlock($v_binary_data);
988      }
989
990      return true;
991    }
992    // }}}
993
994    // {{{ _writeHeader()
995    function _writeHeader($p_filename, $p_stored_filename)
996    {
997        if ($p_stored_filename == '')
998            $p_stored_filename = $p_filename;
999        $v_reduce_filename = $this->_pathReduction($p_stored_filename);
1000
1001        if (strlen($v_reduce_filename) > 99) {
1002          if (!$this->_writeLongHeader($v_reduce_filename))
1003            return false;
1004        }
1005
1006        $v_info = stat($p_filename);
1007        $v_uid = sprintf("%6s ", DecOct($v_info[4]));
1008        $v_gid = sprintf("%6s ", DecOct($v_info[5]));
1009        $v_perms = sprintf("%6s ", DecOct(fileperms($p_filename)));
1010
1011        $v_mtime = sprintf("%11s", DecOct(filemtime($p_filename)));
1012
1013        if (@is_dir($p_filename)) {
1014          $v_typeflag = "5";
1015          $v_size = sprintf("%11s ", DecOct(0));
1016        } else {
1017          $v_typeflag = '';
1018          clearstatcache();
1019          $v_size = sprintf("%11s ", DecOct(filesize($p_filename)));
1020        }
1021
1022        $v_linkname = '';
1023
1024        $v_magic = '';
1025
1026        $v_version = '';
1027
1028        $v_uname = '';
1029
1030        $v_gname = '';
1031
1032        $v_devmajor = '';
1033
1034        $v_devminor = '';
1035
1036        $v_prefix = '';
1037
1038        $v_binary_data_first = pack("a100a8a8a8a12A12",
1039                                    $v_reduce_filename, $v_perms, $v_uid,
1040                                    $v_gid, $v_size, $v_mtime);
1041        $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
1042                                   $v_typeflag, $v_linkname, $v_magic,
1043                                   $v_version, $v_uname, $v_gname,
1044                                   $v_devmajor, $v_devminor, $v_prefix, '');
1045
1046        // ----- Calculate the checksum
1047        $v_checksum = 0;
1048        // ..... First part of the header
1049        for ($i=0; $i<148; $i++)
1050            $v_checksum += ord(substr($v_binary_data_first,$i,1));
1051        // ..... Ignore the checksum value and replace it by ' ' (space)
1052        for ($i=148; $i<156; $i++)
1053            $v_checksum += ord(' ');
1054        // ..... Last part of the header
1055        for ($i=156, $j=0; $i<512; $i++, $j++)
1056            $v_checksum += ord(substr($v_binary_data_last,$j,1));
1057
1058        // ----- Write the first 148 bytes of the header in the archive
1059        $this->_writeBlock($v_binary_data_first, 148);
1060
1061        // ----- Write the calculated checksum
1062        $v_checksum = sprintf("%6s ", DecOct($v_checksum));
1063        $v_binary_data = pack("a8", $v_checksum);
1064        $this->_writeBlock($v_binary_data, 8);
1065
1066        // ----- Write the last 356 bytes of the header in the archive
1067        $this->_writeBlock($v_binary_data_last, 356);
1068
1069        return true;
1070    }
1071    // }}}
1072
1073    // {{{ _writeHeaderBlock()
1074    function _writeHeaderBlock($p_filename, $p_size, $p_mtime=0, $p_perms=0,
1075                               $p_type='', $p_uid=0, $p_gid=0)
1076    {
1077        $p_filename = $this->_pathReduction($p_filename);
1078
1079        if (strlen($p_filename) > 99) {
1080          if (!$this->_writeLongHeader($p_filename))
1081            return false;
1082        }
1083
1084        if ($p_type == "5") {
1085          $v_size = sprintf("%11s ", DecOct(0));
1086        } else {
1087          $v_size = sprintf("%11s ", DecOct($p_size));
1088        }
1089
1090        $v_uid = sprintf("%6s ", DecOct($p_uid));
1091        $v_gid = sprintf("%6s ", DecOct($p_gid));
1092        $v_perms = sprintf("%6s ", DecOct($p_perms));
1093
1094        $v_mtime = sprintf("%11s", DecOct($p_mtime));
1095
1096        $v_linkname = '';
1097
1098        $v_magic = '';
1099
1100        $v_version = '';
1101
1102        $v_uname = '';
1103
1104        $v_gname = '';
1105
1106        $v_devmajor = '';
1107
1108        $v_devminor = '';
1109
1110        $v_prefix = '';
1111
1112        $v_binary_data_first = pack("a100a8a8a8a12A12",
1113                                    $p_filename, $v_perms, $v_uid, $v_gid,
1114                                    $v_size, $v_mtime);
1115        $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
1116                                   $p_type, $v_linkname, $v_magic,
1117                                   $v_version, $v_uname, $v_gname,
1118                                   $v_devmajor, $v_devminor, $v_prefix, '');
1119
1120        // ----- Calculate the checksum
1121        $v_checksum = 0;
1122        // ..... First part of the header
1123        for ($i=0; $i<148; $i++)
1124            $v_checksum += ord(substr($v_binary_data_first,$i,1));
1125        // ..... Ignore the checksum value and replace it by ' ' (space)
1126        for ($i=148; $i<156; $i++)
1127            $v_checksum += ord(' ');
1128        // ..... Last part of the header
1129        for ($i=156, $j=0; $i<512; $i++, $j++)
1130            $v_checksum += ord(substr($v_binary_data_last,$j,1));
1131
1132        // ----- Write the first 148 bytes of the header in the archive
1133        $this->_writeBlock($v_binary_data_first, 148);
1134
1135        // ----- Write the calculated checksum
1136        $v_checksum = sprintf("%6s ", DecOct($v_checksum));
1137        $v_binary_data = pack("a8", $v_checksum);
1138        $this->_writeBlock($v_binary_data, 8);
1139
1140        // ----- Write the last 356 bytes of the header in the archive
1141        $this->_writeBlock($v_binary_data_last, 356);
1142
1143        return true;
1144    }
1145    // }}}
1146
1147    // {{{ _writeLongHeader()
1148    function _writeLongHeader($p_filename)
1149    {
1150        $v_size = sprintf("%11s ", DecOct(strlen($p_filename)));
1151
1152        $v_typeflag = 'L';
1153
1154        $v_linkname = '';
1155
1156        $v_magic = '';
1157
1158        $v_version = '';
1159
1160        $v_uname = '';
1161
1162        $v_gname = '';
1163
1164        $v_devmajor = '';
1165
1166        $v_devminor = '';
1167
1168        $v_prefix = '';
1169
1170        $v_binary_data_first = pack("a100a8a8a8a12A12",
1171                                    '././@LongLink', 0, 0, 0, $v_size, 0);
1172        $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
1173                                   $v_typeflag, $v_linkname, $v_magic,
1174                                   $v_version, $v_uname, $v_gname,
1175                                   $v_devmajor, $v_devminor, $v_prefix, '');
1176
1177        // ----- Calculate the checksum
1178        $v_checksum = 0;
1179        // ..... First part of the header
1180        for ($i=0; $i<148; $i++)
1181            $v_checksum += ord(substr($v_binary_data_first,$i,1));
1182        // ..... Ignore the checksum value and replace it by ' ' (space)
1183        for ($i=148; $i<156; $i++)
1184            $v_checksum += ord(' ');
1185        // ..... Last part of the header
1186        for ($i=156, $j=0; $i<512; $i++, $j++)
1187            $v_checksum += ord(substr($v_binary_data_last,$j,1));
1188
1189        // ----- Write the first 148 bytes of the header in the archive
1190        $this->_writeBlock($v_binary_data_first, 148);
1191
1192        // ----- Write the calculated checksum
1193        $v_checksum = sprintf("%6s ", DecOct($v_checksum));
1194        $v_binary_data = pack("a8", $v_checksum);
1195        $this->_writeBlock($v_binary_data, 8);
1196
1197        // ----- Write the last 356 bytes of the header in the archive
1198        $this->_writeBlock($v_binary_data_last, 356);
1199
1200        // ----- Write the filename as content of the block
1201        $i=0;
1202        while (($v_buffer = substr($p_filename, (($i++)*512), 512)) != '') {
1203            $v_binary_data = pack("a512", "$v_buffer");
1204            $this->_writeBlock($v_binary_data);
1205        }
1206
1207        return true;
1208    }
1209    // }}}
1210
1211    // {{{ _readHeader()
1212    function _readHeader($v_binary_data, &$v_header)
1213    {
1214        if (strlen($v_binary_data)==0) {
1215            $v_header['filename'] = '';
1216            return true;
1217        }
1218
1219        if (strlen($v_binary_data) != 512) {
1220            $v_header['filename'] = '';
1221            $this->_error('Invalid block size : '.strlen($v_binary_data));
1222            return false;
1223        }
1224
1225        // ----- Calculate the checksum
1226        $v_checksum = 0;
1227        // ..... First part of the header
1228        for ($i=0; $i<148; $i++)
1229            $v_checksum+=ord(substr($v_binary_data,$i,1));
1230        // ..... Ignore the checksum value and replace it by ' ' (space)
1231        for ($i=148; $i<156; $i++)
1232            $v_checksum += ord(' ');
1233        // ..... Last part of the header
1234        for ($i=156; $i<512; $i++)
1235           $v_checksum+=ord(substr($v_binary_data,$i,1));
1236
1237        $v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/"
1238                         ."a8checksum/a1typeflag/a100link/a6magic/a2version/"
1239                         ."a32uname/a32gname/a8devmajor/a8devminor",
1240                         $v_binary_data);
1241
1242        // ----- Extract the checksum
1243        $v_header['checksum'] = OctDec(trim($v_data['checksum']));
1244        if ($v_header['checksum'] != $v_checksum) {
1245            $v_header['filename'] = '';
1246
1247            // ----- Look for last block (empty block)
1248            if (($v_checksum == 256) && ($v_header['checksum'] == 0))
1249                return true;
1250
1251            $this->_error('Invalid checksum for file "'.$v_data['filename']
1252                          .'" : '.$v_checksum.' calculated, '
1253                          .$v_header['checksum'].' expected');
1254            return false;
1255        }
1256
1257        // ----- Extract the properties
1258        $v_header['filename'] = trim($v_data['filename']);
1259        $v_header['mode'] = OctDec(trim($v_data['mode']));
1260        $v_header['uid'] = OctDec(trim($v_data['uid']));
1261        $v_header['gid'] = OctDec(trim($v_data['gid']));
1262        $v_header['size'] = OctDec(trim($v_data['size']));
1263        $v_header['mtime'] = OctDec(trim($v_data['mtime']));
1264        if (($v_header['typeflag'] = $v_data['typeflag']) == "5") {
1265          $v_header['size'] = 0;
1266        }
1267        /* ----- All these fields are removed form the header because
1268        they do not carry interesting info
1269        $v_header[link] = trim($v_data[link]);
1270        $v_header[magic] = trim($v_data[magic]);
1271        $v_header[version] = trim($v_data[version]);
1272        $v_header[uname] = trim($v_data[uname]);
1273        $v_header[gname] = trim($v_data[gname]);
1274        $v_header[devmajor] = trim($v_data[devmajor]);
1275        $v_header[devminor] = trim($v_data[devminor]);
1276        */
1277
1278        return true;
1279    }
1280    // }}}
1281
1282    // {{{ _readLongHeader()
1283    function _readLongHeader(&$v_header)
1284    {
1285      $v_filename = '';
1286      $n = floor($v_header['size']/512);
1287      for ($i=0; $i<$n; $i++) {
1288        $v_content = $this->_readBlock();
1289        $v_filename .= $v_content;
1290      }
1291      if (($v_header['size'] % 512) != 0) {
1292        $v_content = $this->_readBlock();
1293        $v_filename .= $v_content;
1294      }
1295
1296      // ----- Read the next header
1297      $v_binary_data = $this->_readBlock();
1298
1299      if (!$this->_readHeader($v_binary_data, $v_header))
1300        return false;
1301
1302      $v_header['filename'] = $v_filename;
1303
1304      return true;
1305    }
1306    // }}}
1307
1308    // {{{ _extractInString()
1309    /**
1310    * This method extract from the archive one file identified by $p_filename.
1311    * The return value is a string with the file content, or NULL on error.
1312    * @param string $p_filename     The path of the file to extract in a string.
1313    * @return                       a string with the file content or NULL.
1314    * @access private
1315    */
1316    function _extractInString($p_filename)
1317    {
1318        $v_result_str = "";
1319
1320        While (strlen($v_binary_data = $this->_readBlock()) != 0)
1321        {
1322          if (!$this->_readHeader($v_binary_data, $v_header))
1323            return NULL;
1324
1325          if ($v_header['filename'] == '')
1326            continue;
1327
1328          // ----- Look for long filename
1329          if ($v_header['typeflag'] == 'L') {
1330            if (!$this->_readLongHeader($v_header))
1331              return NULL;
1332          }
1333
1334          if ($v_header['filename'] == $p_filename) {
1335              if ($v_header['typeflag'] == "5") {
1336                  $this->_error('Unable to extract in string a directory '
1337                                .'entry {'.$v_header['filename'].'}');
1338                  return NULL;
1339              } else {
1340                  $n = floor($v_header['size']/512);
1341                  for ($i=0; $i<$n; $i++) {
1342                      $v_result_str .= $this->_readBlock();
1343                  }
1344                  if (($v_header['size'] % 512) != 0) {
1345                      $v_content = $this->_readBlock();
1346                      $v_result_str .= substr($v_content, 0,
1347                                              ($v_header['size'] % 512));
1348                  }
1349                  return $v_result_str;
1350              }
1351          } else {
1352              $this->_jumpBlock(ceil(($v_header['size']/512)));
1353          }
1354        }
1355
1356        return NULL;
1357    }
1358    // }}}
1359
1360    // {{{ _extractList()
1361    function _extractList($p_path, &$p_list_detail, $p_mode,
1362                          $p_file_list, $p_remove_path)
1363    {
1364    $v_result=true;
1365    $v_nb = 0;
1366    $v_extract_all = true;
1367    $v_listing = false;
1368
1369    $p_path = $this->_translateWinPath($p_path, false);
1370    if ($p_path == '' || (substr($p_path, 0, 1) != '/'
1371        && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':'))) {
1372      $p_path = "./".$p_path;
1373    }
1374    $p_remove_path = $this->_translateWinPath($p_remove_path);
1375
1376    // ----- Look for path to remove format (should end by /)
1377    if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/'))
1378      $p_remove_path .= '/';
1379    $p_remove_path_size = strlen($p_remove_path);
1380
1381    switch ($p_mode) {
1382      case "complete" :
1383        $v_extract_all = TRUE;
1384        $v_listing = FALSE;
1385      break;
1386      case "partial" :
1387          $v_extract_all = FALSE;
1388          $v_listing = FALSE;
1389      break;
1390      case "list" :
1391          $v_extract_all = FALSE;
1392          $v_listing = TRUE;
1393      break;
1394      default :
1395        $this->_error('Invalid extract mode ('.$p_mode.')');
1396        return false;
1397    }
1398
1399    clearstatcache();
1400
1401    while (strlen($v_binary_data = $this->_readBlock()) != 0)
1402    {
1403      $v_extract_file = FALSE;
1404      $v_extraction_stopped = 0;
1405
1406      if (!$this->_readHeader($v_binary_data, $v_header))
1407        return false;
1408
1409      if ($v_header['filename'] == '') {
1410        continue;
1411      }
1412
1413      // ----- Look for long filename
1414      if ($v_header['typeflag'] == 'L') {
1415        if (!$this->_readLongHeader($v_header))
1416          return false;
1417      }
1418
1419      if ((!$v_extract_all) && (is_array($p_file_list))) {
1420        // ----- By default no unzip if the file is not found
1421        $v_extract_file = false;
1422
1423        for ($i=0; $i<sizeof($p_file_list); $i++) {
1424          // ----- Look if it is a directory
1425          if (substr($p_file_list[$i], -1) == '/') {
1426            // ----- Look if the directory is in the filename path
1427            if ((strlen($v_header['filename']) > strlen($p_file_list[$i]))
1428                && (substr($v_header['filename'], 0, strlen($p_file_list[$i]))
1429                    == $p_file_list[$i])) {
1430              $v_extract_file = TRUE;
1431              break;
1432            }
1433          }
1434
1435          // ----- It is a file, so compare the file names
1436          elseif ($p_file_list[$i] == $v_header['filename']) {
1437            $v_extract_file = TRUE;
1438            break;
1439          }
1440        }
1441      } else {
1442        $v_extract_file = TRUE;
1443      }
1444
1445      // ----- Look if this file need to be extracted
1446      if (($v_extract_file) && (!$v_listing))
1447      {
1448        if (($p_remove_path != '')
1449            && (substr($v_header['filename'], 0, $p_remove_path_size)
1450                == $p_remove_path))
1451          $v_header['filename'] = substr($v_header['filename'],
1452                                         $p_remove_path_size);
1453        if (($p_path != './') && ($p_path != '/')) {
1454          while (substr($p_path, -1) == '/')
1455            $p_path = substr($p_path, 0, strlen($p_path)-1);
1456
1457          if (substr($v_header['filename'], 0, 1) == '/')
1458              $v_header['filename'] = $p_path.$v_header['filename'];
1459          else
1460            $v_header['filename'] = $p_path.'/'.$v_header['filename'];
1461        }
1462        if (file_exists($v_header['filename'])) {
1463          if (   (@is_dir($v_header['filename']))
1464              && ($v_header['typeflag'] == '')) {
1465            $this->_error('File '.$v_header['filename']
1466                          .' already exists as a directory');
1467            return false;
1468          }
1469          if (   ($this->_isArchive($v_header['filename']))
1470              && ($v_header['typeflag'] == "5")) {
1471            $this->_error('Directory '.$v_header['filename']
1472                          .' already exists as a file');
1473            return false;
1474          }
1475          if (!is_writeable($v_header['filename'])) {
1476            $this->_error('File '.$v_header['filename']
1477                          .' already exists and is write protected');
1478            return false;
1479          }
1480          if (filemtime($v_header['filename']) > $v_header['mtime']) {
1481            // To be completed : An error or silent no replace ?
1482          }
1483        }
1484
1485        // ----- Check the directory availability and create it if necessary
1486        elseif (($v_result
1487                 = $this->_dirCheck(($v_header['typeflag'] == "5"
1488                                    ?$v_header['filename']
1489                                    :dirname($v_header['filename'])))) != 1) {
1490            $this->_error('Unable to create path for '.$v_header['filename']);
1491            return false;
1492        }
1493
1494        if ($v_extract_file) {
1495          if ($v_header['typeflag'] == "5") {
1496            if (!@file_exists($v_header['filename'])) {
1497                if (!@mkdir($v_header['filename'], 0777)) {
1498                    $this->_error('Unable to create directory {'
1499                                  .$v_header['filename'].'}');
1500                    return false;
1501                }
1502            }
1503          } else {
1504              if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) {
1505                  $this->_error('Error while opening {'.$v_header['filename']
1506                                .'} in write binary mode');
1507                  return false;
1508              } else {
1509                  $n = floor($v_header['size']/512);
1510                  for ($i=0; $i<$n; $i++) {
1511                      $v_content = $this->_readBlock();
1512                      fwrite($v_dest_file, $v_content, 512);
1513                  }
1514            if (($v_header['size'] % 512) != 0) {
1515              $v_content = $this->_readBlock();
1516              fwrite($v_dest_file, $v_content, ($v_header['size'] % 512));
1517            }
1518
1519            @fclose($v_dest_file);
1520
1521            // ----- Change the file mode, mtime
1522            @touch($v_header['filename'], $v_header['mtime']);
1523            // To be completed
1524            //chmod($v_header[filename], DecOct($v_header[mode]));
1525          }
1526
1527          // ----- Check the file size
1528          clearstatcache();
1529          if (filesize($v_header['filename']) != $v_header['size']) {
1530              $this->_error('Extracted file '.$v_header['filename']
1531                            .' does not have the correct file size \''
1532                            .filesize($v_header['filename'])
1533                            .'\' ('.$v_header['size']
1534                            .' expected). Archive may be corrupted.');
1535              return false;
1536          }
1537          }
1538        } else {
1539          $this->_jumpBlock(ceil(($v_header['size']/512)));
1540        }
1541      } else {
1542          $this->_jumpBlock(ceil(($v_header['size']/512)));
1543      }
1544
1545      /* TBC : Seems to be unused ...
1546      if ($this->_compress)
1547        $v_end_of_file = @gzeof($this->_file);
1548      else
1549        $v_end_of_file = @feof($this->_file);
1550        */
1551
1552      if ($v_listing || $v_extract_file || $v_extraction_stopped) {
1553        // ----- Log extracted files
1554        if (($v_file_dir = dirname($v_header['filename']))
1555            == $v_header['filename'])
1556          $v_file_dir = '';
1557        if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == ''))
1558          $v_file_dir = '/';
1559
1560        $p_list_detail[$v_nb++] = $v_header;
1561      }
1562    }
1563
1564        return true;
1565    }
1566    // }}}
1567
1568    // {{{ _openAppend()
1569    function _openAppend()
1570    {
1571        if (filesize($this->_tarname) == 0)
1572          return $this->_openWrite();
1573         
1574        if ($this->_compress) {
1575            $this->_close();
1576
1577            if (!@rename($this->_tarname, $this->_tarname.".tmp")) {
1578                $this->_error('Error while renaming \''.$this->_tarname
1579                              .'\' to temporary file \''.$this->_tarname
1580                              .'.tmp\'');
1581                return false;
1582            }
1583
1584            if ($this->_compress_type == 'gz')
1585                $v_temp_tar = @gzopen($this->_tarname.".tmp", "rb");
1586            elseif ($this->_compress_type == 'bz2')
1587                $v_temp_tar = @bzopen($this->_tarname.".tmp", "rb");
1588               
1589            if ($v_temp_tar == 0) {
1590                $this->_error('Unable to open file \''.$this->_tarname
1591                              .'.tmp\' in binary read mode');
1592                @rename($this->_tarname.".tmp", $this->_tarname);
1593                return false;
1594            }
1595
1596            if (!$this->_openWrite()) {
1597                @rename($this->_tarname.".tmp", $this->_tarname);
1598                return false;
1599            }
1600
1601            if ($this->_compress_type == 'gz') {
1602                $v_buffer = @gzread($v_temp_tar, 512);
1603
1604                // ----- Read the following blocks but not the last one
1605                if (!@gzeof($v_temp_tar)) {
1606                    do{
1607                        $v_binary_data = pack("a512", $v_buffer);
1608                        $this->_writeBlock($v_binary_data);
1609                        $v_buffer = @gzread($v_temp_tar, 512);
1610
1611                    } while (!@gzeof($v_temp_tar));
1612                }
1613
1614                @gzclose($v_temp_tar);
1615            }
1616            elseif ($this->_compress_type == 'bz2') {
1617                $v_buffered_lines   = array();
1618                $v_buffered_lines[] = @bzread($v_temp_tar, 512);
1619
1620                // ----- Read the following blocks but not the last one
1621                while (strlen($v_buffered_lines[]
1622                              = @bzread($v_temp_tar, 512)) > 0) {
1623                    $v_binary_data = pack("a512",
1624                                          array_shift($v_buffered_lines));
1625                    $this->_writeBlock($v_binary_data);
1626                }
1627
1628                @bzclose($v_temp_tar);
1629            }
1630
1631            if (!@unlink($this->_tarname.".tmp")) {
1632                $this->_error('Error while deleting temporary file \''
1633                              .$this->_tarname.'.tmp\'');
1634            }
1635
1636        } else {
1637            // ----- For not compressed tar, just add files before the last
1638            //       512 bytes block
1639            if (!$this->_openReadWrite())
1640               return false;
1641
1642            clearstatcache();
1643            $v_size = filesize($this->_tarname);
1644            fseek($this->_file, $v_size-512);
1645        }
1646
1647        return true;
1648    }
1649    // }}}
1650
1651    // {{{ _append()
1652    function _append($p_filelist, $p_add_dir='', $p_remove_dir='')
1653    {
1654        if (!$this->_openAppend())
1655            return false;
1656           
1657        if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir))
1658           $this->_writeFooter();
1659
1660        $this->_close();
1661
1662        return true;
1663    }
1664    // }}}
1665
1666    // {{{ _dirCheck()
1667
1668    /**
1669     * Check if a directory exists and create it (including parent
1670     * dirs) if not.
1671     *
1672     * @param string $p_dir directory to check
1673     *
1674     * @return bool TRUE if the directory exists or was created
1675     */
1676    function _dirCheck($p_dir)
1677    {
1678        if ((@is_dir($p_dir)) || ($p_dir == ''))
1679            return true;
1680
1681        $p_parent_dir = dirname($p_dir);
1682
1683        if (($p_parent_dir != $p_dir) &&
1684            ($p_parent_dir != '') &&
1685            (!$this->_dirCheck($p_parent_dir)))
1686             return false;
1687
1688        if (!@mkdir($p_dir, 0777)) {
1689            $this->_error("Unable to create directory '$p_dir'");
1690            return false;
1691        }
1692
1693        return true;
1694    }
1695
1696    // }}}
1697
1698    // {{{ _pathReduction()
1699
1700    /**
1701     * Compress path by changing for example "/dir/foo/../bar" to "/dir/bar",
1702     * rand emove double slashes.
1703     *
1704     * @param string $p_dir path to reduce
1705     *
1706     * @return string reduced path
1707     *
1708     * @access private
1709     *
1710     */
1711    function _pathReduction($p_dir)
1712    {
1713        $v_result = '';
1714
1715        // ----- Look for not empty path
1716        if ($p_dir != '') {
1717            // ----- Explode path by directory names
1718            $v_list = explode('/', $p_dir);
1719
1720            // ----- Study directories from last to first
1721            for ($i=sizeof($v_list)-1; $i>=0; $i--) {
1722                // ----- Look for current path
1723                if ($v_list[$i] == ".") {
1724                    // ----- Ignore this directory
1725                    // Should be the first $i=0, but no check is done
1726                }
1727                else if ($v_list[$i] == "..") {
1728                    // ----- Ignore it and ignore the $i-1
1729                    $i--;
1730                }
1731                else if (   ($v_list[$i] == '')
1732                         && ($i!=(sizeof($v_list)-1))
1733                         && ($i!=0)) {
1734                    // ----- Ignore only the double '//' in path,
1735                    // but not the first and last /
1736                } else {
1737                    $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?'/'
1738                                .$v_result:'');
1739                }
1740            }
1741        }
1742        $v_result = strtr($v_result, '\\', '/');
1743        return $v_result;
1744    }
1745
1746    // }}}
1747
1748    // {{{ _translateWinPath()
1749    function _translateWinPath($p_path, $p_remove_disk_letter=true)
1750    {
1751      if (OS_WINDOWS) {
1752          // ----- Look for potential disk letter
1753          if (   ($p_remove_disk_letter)
1754              && (($v_position = strpos($p_path, ':')) != false)) {
1755              $p_path = substr($p_path, $v_position+1);
1756          }
1757          // ----- Change potential windows directory separator
1758          if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
1759              $p_path = strtr($p_path, '\\', '/');
1760          }
1761      }
1762      return $p_path;
1763    }
1764    // }}}
1765
1766}
1767?>
Note: See TracBrowser for help on using the repository browser.