<?php
/* (C) 2006 by legolas558
	Veloce php script v0.2.5
	Licensed under GPL

 * This program is free software and open source software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  or visit
 * http://www.gnu.org/licenses/gpl.html
 */
 
function mt_float()
{
   list($usec, $sec) = explode(' ', microtime());
   return ((float)$usec + (float)$sec);
}

$start = mt_float();

// to show all errors
error_reporting(-1);

// set maximum execution time, if possible
@ini_set('max_execution_time', 0);

$root = str_replace('\\','/', dirname(__FILE__)).'/';	//! the current folder absolute path

if (@$_GET['kill']==1) {

	$ext = file_ext($_GET['chosen']);
	if (($ext != 'tar') && ($ext != 'tgz') && ($ext) == 'gz') {
		header('Status: 400 Bad Request');
		exit;
	}

	if (@unlink($root.$_GET['chosen'])) {
//		unlink($root.'TarExtract.php');
		unlink($root.basename($_SERVER['PHP_SELF']));
		header('Location: '.default_redir($root));
	} else
		echo 'Could not delete files';
	exit;
}

/// start of TarBackupSkel.php file
if (!defined('__TBK_CHUNK')) {
	define('__TBK_CHUNK', 1 * 1024 * 1024);
}

class TarBackupSkel {
var $progress;
var $average;
var $errstr;
var $debug = 1;

function TarBackupSkel(&$var) {
	$this->progress =& $var;
	$this->errstr = '';
	$this->average = 0.0;
}

function GetTarballName() {
	return $this->progress->tarname;
}

function ErrorMsg() {
	return $this->errstr;
}

function Percent() {
	return sprintf('%.2f', ($this->progress->done*100/$this->progress->total));
}

function Finished() {
	return ($this->progress->done == $this->progress->total);
}

function _addFile($fn, $fs) {
	$this->progress->fname[] = $fn;
	$this->progress->fsize[] = $fs;
	$this->progress->total += $fs;
}

function _init($root, $p_tarname) {
	$this->progress = new stdClass();
	$this->progress->root = $root;
	$this->progress->tarname = $p_tarname;
	$this->progress->done = 0;
	$this->progress->total = 0;
	$this->progress->spent = 0.0;
	$this->progress->fname = array();
	$this->progress->fsize = array();
}

function _pclexec() {
	$args = func_get_args();
	$funcname = $args[0];
	$max_bytes = $args[1];

	$lista = array();
	$done = 0;
	$c = count($this->progress->fname);
	for ($i=0;$i<$c;$i++) {
		$done += $this->progress->fsize[$i];
		$lista[] = /*$this->progress->root.*/$this->progress->fname[$i];
		if ($done>$max_bytes) {
			$c = $i+1;
			break;
		}
	}
	
	if ($this->debug>0) {
		echo "Processing ".count($lista)."/".$c." files\n";
	}
	
	if (count($lista)==0)
		return true;

	array_splice($args, 0, 2);
	array_unshift($args, $lista);
	array_unshift($args, $this->progress->tarname);

	$er = error_reporting(-1 ^ E_NOTICE);
		$r = call_user_func_array($funcname, $args);
	error_reporting($er);
	
	if ($this->debug > 0) {
		echo "Extracted ".count($r)." files\n";
		foreach($r as $fb) {
			echo $fb['filename'].sprintf(' (CRC32=%x, mode=%o, size=%.2fkb, mtime=%u) %s',
					$fb['checksum'], $fb['mode'], $fb['size']/1024, $fb['mtime'], $fb['status'])."\n";
			@ob_flush();
		}
	}
	

	if (PclErrorCode() < 0) { // some error happened
		$this->errstr = PclErrorString($r);
		return false;
	}

	$this->progress->done += $done;
	array_splice($this->progress->fname, 0, $c);
	array_splice($this->progress->fsize, 0, $c);

	return true;
}

function _sync_average($start) {
	$spent = mt_float()-$start;
	$this->average = $this->progress->done / ($this->progress->spent+$spent);
	$this->_debug();
	return $spent;
}

function _debug() {
	echo 'Average speed: '.sprintf('%.2f', $this->average/1024).' kb/s<br>';
	echo 'Total data processed: '.sprintf('%.2f', $this->progress->done/1024).' kb<br>';
	echo 'Total data left: '.sprintf('%.2f', ($this->progress->total-$this->progress->done)/1024).' kb<br>';
	echo 'Total time spent: '.sprintf('%.2f', $this->progress->done/$this->average).' s<br>';
	echo 'PclErrorString: '.PclErrorString(PclErrorCode()).'<hr>';
	@ob_flush();
}

// main looping function
// will return TRUE if no error happened and the time was correctly spent executing $method
// will return FALSE if an error happened in _pclexec
function _loop($next_step_cb, $max_time, $method) {

	// in case of invalid or unspecified max execution time
	if ($max_time <= 0)
		$max_time += (int)ini_get('max_execution_time');

	$start = mt_float();

	// Perform an average checking cycle if necessary
	$do_avr = ($this->progress->spent == 0);
	if ($do_avr) {

		$r = $this->$method(__TBK_CHUNK);

		$spent = $this->_sync_average($start);
//		$this->average/=$this->progress->spent;
		if (!$r || ($max_time-$spent<1)) {
			$this->progress->spent += $spent;
			$this->_finalize($next_step_cb);
			return $r;
		}
	}

	if (!$do_avr || $this->$method(__TBK_CHUNK/5)) {
		do {
			$spent = $this->_sync_average($start);
			$left = $max_time-$spent;
			if ($this->debug > 0)
				echo sprintf("Time left: %.2F s\n", $left);
			$chunk = (int)($left*$this->average);
			if ($chunk > __TBK_CHUNK/2)
				$chunk = __TBK_CHUNK/2;
			else {
				$this->progress->spent += $this->_sync_average($start);
				$this->_finalize($next_step_cb);
				return true;
			}
			if ($this->Finished())
				break;
		} while ($this->$method($chunk));
	}
	$this->progress->spent += $this->_sync_average($start);
	$this->_finalize($next_step_cb);
	return true;
}function _finalize($next_step_cb) {
	$next_step_cb($this);
//	if ($this->Finished()) // eventually free the associated session variable
}

}
/// end of TarBackupSkel.php file

/// start of TarExtract.php file

class TarExtract extends TarBackupSkel {

	function BeginExtract($root, $p_tarname, $dest='') {
		$er = error_reporting(-1 ^ E_NOTICE);
		$list = PclTarList($p_tarname);

		$this->_init($root, $p_tarname);

		foreach ($list as $fn)
			$this->_addFile($fn['filename'], $fn['size']);
			
		$this->progress->dest = $dest;
	}

	function ExtractStep($max_bytes = __TBK_CHUNK) {
		return $this->_pclexec('PclTarExtractList', $max_bytes, $this->progress->dest );
	}

	function Extract($next_step_cb, $max_time = null) {
		return $this->_loop($next_step_cb, $max_time, 'ExtractStep');
	}

}
/// end of TarExtract.php file

$max_time = @ini_get('max_execution_time');
if (!$max_time) $max_time = 30;
else $max_time -= (int)($max_time/3);

//$max_time = 30;

// --------------------------------------------------------------------------------
// PhpConcept Library - Tar Module 1.3
// --------------------------------------------------------------------------------
// License GNU/GPL - Vincent Blavet - August 2001
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// Presentation :
//   PclTar is a library that allow you to create a GNU TAR + GNU ZIP archive,
//   to add files or directories, to extract all the archive or a part of it.
//   So far tests show that the files generated by PclTar are readable by
//   gzip tools and WinZip application.
//
// Description :
//   See readme.txt (English & Français) and http://www.phpconcept.net
//
// Warning :
//   This library and the associated files are non commercial, non professional
//   work.
//   It should not have unexpected results. However if any damage is caused by
//   this software the author can not be responsible.
//   The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------

  // ----- Error codes
  //   -1 : Unable to open file in binary write mode
  //   -2 : Unable to open file in binary read mode
  //   -3 : Invalid parameters
  //   -4 : File does not exist
  //   -5 : Filename is too long (max. 99)
  //   -6 : Not a valid tar file
  //   -7 : Invalid extracted file size
  //   -8 : Unable to create directory
  //   -9 : Invalid archive extension
  //  -10 : Invalid archive format
  //  -11 : Unable to delete file (unlink)
  //  -12 : Unable to rename file (rename)
  //  -13 : Invalid header checksum// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
// --------------------------------------------------------------------------------

  // ----- Global variables
  $g_pcltar_version = "1.3";

  $g_pcltar_lib_dir = str_replace('\\', '/', dirname(__FILE__)).'/';

  // ----- Extract extension type (.php3/.php/...)
  $g_pcltar_extension = substr(strrchr(__FILE__, '.'), 1);  // --------------------------------------------------------------------------------
  // Function : PclTarList()
  // Description :
  //   Gives the list of all the files present in the tar archive $p_tarname.
  //   The list is the function result, it will be 0 on error.
  //   Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
  //   function will determine the type of the archive.
  // Parameters :
  //   $p_tarname : Name of an existing tar file
  //   $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
  // Return Values :
  //  0 on error (Use PclErrorCode() and PclErrorString() for more info)
  //  or
  //  An array containing file properties. Each file properties is an array of
  //  properties.
  //  The properties (array field names) are :
  //    filename, size, mode, uid, gid, mtime, typeflag, status
  //  Exemple : $v_list = PclTarList("my.tar");
  //            for ($i=0; $i<sizeof($v_list); $i++)
  //              echo "Filename :'".$v_list[$i][filename]."'<br>";
  // --------------------------------------------------------------------------------
  function PclTarList($p_tarname, $p_mode="")
  {

    $v_result=1;

    // ----- Extract the tar format from the extension
    if (($p_mode == "") || (($p_mode!="tar") && ($p_mode!="tgz")))
    {
      if (($p_mode = PclTarHandleExtension($p_tarname)) == "")
      {
        // ----- Return

        return 0;
      }
    }

    // ----- Call the extracting fct
    $p_list = array();
    if (($v_result = PclTarHandleExtract($p_tarname, 0, $p_list, "list", "", $p_mode, "")) != 1)
    {
      unset($p_list);

      return(0);
    }

    // ----- Return

    return $p_list;
  }
  // --------------------------------------------------------------------------------

  // --------------------------------------------------------------------------------
  // Function : PclTarExtractList()
  // Description :
  //   Extract the files present in the archive $p_tarname and specified in
  //   $p_filelist, in the directory
  //   $p_path. The relative path of the archived files are keep and become
  //   relative to $p_path.
  //   If a directory is spécified in the list, all the files from this directory
  //   will be extracted.
  //   If a file with the same name already exists it will be replaced.
  //   If the path to the file does not exist, it will be created.
  //   Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
  //   function will determine the type of the archive.
  // Parameters :
  //   $p_tarname : Name of an existing tar file
  //   $p_filelist : An array containing file or directory names, or
  //                 a string containing one filename or directory name, or
  //                 a string containing a list of filenames and/or directory
  //                 names separated by spaces.
  //   $p_path : Path where the files will be extracted. The files will use
  //             their memorized path from $p_path.
  //             If $p_path is "", files will be extracted in "./".
  //   $p_remove_path : Path to remove (from the file memorized path) while writing the
  //                    extracted files. If the path does not match the file path,
  //                    the file is extracted with its memorized path.
  //                    $p_path and $p_remove_path are commulative.
  //   $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
  // Return Values :
  //   Same as PclTarList()
  // --------------------------------------------------------------------------------
  function PclTarExtractList($p_tarname, $p_filelist, $p_path="./", $p_remove_path="", $p_mode="")
  {

	$v_result=1;

    // ----- Extract the tar format from the extension
    if (($p_mode == "") || (($p_mode!="tar") && ($p_mode!="tgz")))
    {
      if (($p_mode = PclTarHandleExtension($p_tarname)) == "")
      {
        // ----- Return

        return 0;
      }
    }

    // ----- Look if the $p_filelist is really an array
    if (is_array($p_filelist))
    {
      // ----- Call the extracting fct

      if (($v_result = PclTarHandleExtract($p_tarname, $p_filelist, $p_list, "partial", $p_path, $v_tar_mode, $p_remove_path)) != 1)
      {

        return(0);
      }
    }

    // ----- Look if the $p_filelist is a string
    else if (is_string($p_filelist))
    {
      // ----- Create a list with the elements from the string
      $v_list = explode(" ", $p_filelist);

      // ----- Call the extracting fct
      if (($v_result = PclTarHandleExtract($p_tarname, $v_list, $p_list, "partial", $p_path, $v_tar_mode, $p_remove_path)) != 1)
      {

        return(0);
      }
    }

    // ----- Invalid variable
    else
    {
      // ----- Error log
      PclErrorLog(-3, "Invalid variable type p_filelist");

      // ----- Return

      return 0;
    }

    // ----- Return

    return $p_list;
  }
  // --------------------------------------------------------------------------------// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
// *****                                                        *****
// *****       THESES FUNCTIONS MUST NOT BE USED DIRECTLY       *****
// --------------------------------------------------------------------------------  // --------------------------------------------------------------------------------
  // Function : PclTarHandleExtract()
  // Description :
  // Parameters :
  //   $p_tarname : Filename of the tar (or tgz) archive
  //   $p_file_list : An array which contains the list of files to extract, this
  //                  array may be empty when $p_mode is 'complete'
  //   $p_list_detail : An array where will be placed the properties of  each extracted/listed file
  //   $p_mode : 'complete' will extract all files from the archive,
  //             'partial' will look for files in $p_file_list
  //             'list' will only list the files from the archive without any extract
  //   $p_path : Path to add while writing the extracted files
  //   $p_tar_mode : 'tar' for GNU TAR archive, 'tgz' for compressed archive
  //   $p_remove_path : Path to remove (from the file memorized path) while writing the
  //                    extracted files. If the path does not match the file path,
  //                    the file is extracted with its memorized path.
  //                    $p_remove_path does not apply to 'list' mode.
  //                    $p_path and $p_remove_path are commulative.
  // Return Values :
  // --------------------------------------------------------------------------------
  function PclTarHandleExtract($p_tarname, $p_file_list, &$p_list_detail, $p_mode, $p_path, $p_tar_mode, $p_remove_path)
  {

    $v_result=1;
    $v_nb = 0;
    $v_extract_all = TRUE;
    $v_listing = FALSE;

    // ----- Check the path
    if (!isset($p_path[0]))
      $p_path = './';
	  
    // ----- Look for path to remove format (should end by /)
    if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
    {
      $p_remove_path .= '/';
    }
    $p_remove_path_size = strlen($p_remove_path);

    // ----- Study the mode
    switch ($p_mode) {
      case "complete" :
        // ----- Flag extract of all files
        $v_extract_all = TRUE;
        $v_listing = FALSE;
      break;
      case "partial" :
          // ----- Flag extract of specific files
          $v_extract_all = FALSE;
          $v_listing = FALSE;
      break;
      case "list" :
          // ----- Flag list of all files
          $v_extract_all = FALSE;
          $v_listing = TRUE;
      break;
      default :
        // ----- Error log
        PclErrorLog(-3, "Invalid extract mode ($p_mode)");

        // ----- Return

        return PclErrorCode();
    }

    // ----- Open the tar file
    if ($p_tar_mode == "tar")
    {

      $v_tar = fopen($p_tarname, "rb");
    }
    else
    {

      $v_tar = @gzopen($p_tarname, "rb");
    }

    // ----- Check that the archive is open
    if ($v_tar == 0)
    {
      // ----- Error log
      PclErrorLog(-2, "Unable to open archive '$p_tarname' in binary read mode");

      // ----- Return

      return PclErrorCode();
    }

    // ----- Read the blocks
    While (!($v_end_of_file = ($p_tar_mode == "tar"?feof($v_tar):gzeof($v_tar))))
    {      // ----- Clear cache of file infos
      clearstatcache();

      // ----- Reset extract tag
      $v_extract_file = FALSE;
      $v_extraction_stopped = 0;

      // ----- Read the 512 bytes header
      if ($p_tar_mode == "tar")
        $v_binary_data = fread($v_tar, 512);
      else
        $v_binary_data = gzread($v_tar, 512);

      // ----- Read the header properties
      if (($v_result = PclTarHandleReadHeader($v_binary_data, $v_header)) != 1)
      {
        // ----- Close the archive file
        if ($p_tar_mode == "tar")
          fclose($v_tar);
        else
          gzclose($v_tar);

        // ----- Return

        return $v_result;
      }

      // ----- Look for empty blocks to skip
      if ($v_header[filename] == "")
      {

        continue;
      }
      // ----- Look for partial extract
      if ((!$v_extract_all) && (is_array($p_file_list)))
      {        // ----- By default no unzip if the file is not found
        $v_extract_file = FALSE;

        // ----- Look into the file list
        for ($i=0; $i<sizeof($p_file_list); $i++)
        {          // ----- Look if it is a directory
          if (substr($p_file_list[$i], -1) == "/")
          {            // ----- Look if the directory is in the filename path
            if ((strlen($v_header[filename]) > strlen($p_file_list[$i])) && (substr($v_header[filename], 0, strlen($p_file_list[$i])) == $p_file_list[$i]))
            {
              // ----- The file is in the directory, so extract it

              $v_extract_file = TRUE;

              // ----- End of loop
              break;
            }
          }

          // ----- It is a file, so compare the file names
          else if ($p_file_list[$i] == $v_header[filename])
          {
            // ----- File found

            $v_extract_file = TRUE;

            // ----- End of loop
            break;
          }
        }        if (!$v_extract_file)
        {

        }
      }
      else
      {
        // ----- All files need to be extracted
        $v_extract_file = TRUE;
      }

      // ----- Look if this file need to be extracted
      if (($v_extract_file) && (!$v_listing))
      {
        // ----- Look for path to remove
        if (($p_remove_path != "")
            && (substr($v_header[filename], 0, $p_remove_path_size) == $p_remove_path))
        {

          // ----- Remove the path
          $v_header[filename] = substr($v_header[filename], $p_remove_path_size);

        }

        // ----- Add the path to the file
        if (($p_path != "./") && ($p_path != "/"))
        {
          // ----- Look for the path end '/'
          while (substr($p_path, -1) == "/")
          {
            $p_path = substr($p_path, 0, strlen($p_path)-1);
          }

		// fix the $p_path
          if (substr($v_header[filename], 0, 1) != "/")
			$p_path.='/';
        }

        // ----- Check that the file does not exists
        if (file_exists($p_path.$v_header[filename]))
        {          // ----- Look if file is a directory
          if (is_dir($p_path.$v_header[filename]))
          {            // ----- Change the file status
            $v_header[status] = "already_a_directory";

            // ----- Skip the extract
            $v_extraction_stopped = 1;
            $v_extract_file = 0;
          }
          // ----- Look if file is write protected
          else if (!is_writeable($p_path.$v_header[filename]))
          {            // ----- Change the file status
            $v_header[status] = "write_protected";

            // ----- Skip the extract
            $v_extraction_stopped = 1;
            $v_extract_file = 0;
          }
          // ----- Look if the extracted file is older
          else if (filemtime($p_path.$v_header[filename]) > $v_header[mtime])
          {            // ----- Change the file status
            $v_header[status] = "newer_exist";

            // ----- Skip the extract
            $v_extraction_stopped = 1;
            $v_extract_file = 0;
          }
        }

        // ----- Check the directory availability and create it if necessary
        else
        {
          if ($v_header[typeflag]=="5")
            $v_dir_to_check = $v_header[filename];
          else if (!strstr($v_header[filename], "/"))
            $v_dir_to_check = "";
          else
            $v_dir_to_check = dirname($v_header[filename]);
			
          if (($v_result = PclTarHandlerDirCheck($v_dir_to_check, $p_path)) != 1)
          {            // ----- Change the file status
            $v_header[status] = "path_creation_fail";

            // ----- Skip the extract
            $v_extraction_stopped = 1;
            $v_extract_file = 0;
          }
        }

        // ----- Do the extraction
        if (($v_extract_file) && ($v_header[typeflag]!="5"))
        {
          // ----- Open the destination file in write mode
          if (($v_dest_file = @fopen($p_path.$v_header[filename], "wb")) == 0)
          {            // ----- Change the file status
            $v_header[status] = "write_error";

            // ----- Jump to next file

            if ($p_tar_mode == "tar")
              fseek($v_tar, ftell($v_tar)+(ceil(($v_header[size]/512))*512));
            else
              gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));
          }
          else
          {            // ----- Read data
            $n = floor($v_header[size]/512);
            for ($i=0; $i<$n; $i++)
            {

              if ($p_tar_mode == "tar")
                $v_content = fread($v_tar, 512);
              else
                $v_content = gzread($v_tar, 512);
              fwrite($v_dest_file, $v_content, 512);
            }
            if (($v_header[size] % 512) != 0)
            {

              if ($p_tar_mode == "tar")
                $v_content = fread($v_tar, 512);
              else
                $v_content = gzread($v_tar, 512);
              fwrite($v_dest_file, $v_content, ($v_header[size] % 512));
            }

            // ----- Close the destination file
            fclose($v_dest_file);

            // ----- Change the file mode, mtime
            @touch($p_path.$v_header[filename], $v_header[mtime]);
            //chmod($v_header[filename], DecOct($v_header[mode]));
          }

          // ----- Check the file size
          clearstatcache();
          if (filesize($p_path.$v_header[filename]) != $v_header[size])
          {
            // ----- Close the archive file
            if ($p_tar_mode == "tar")
              fclose($v_tar);
            else
              gzclose($v_tar);

            // ----- Error log
            PclErrorLog(-7, "Extracted file '$p_path$v_header[filename]' does not have the correct file size '".filesize($v_filename)."' ('$v_header[size]' expected). Archive may be corrupted.");

            // ----- Return

            return PclErrorCode();
          }

  

        }

        else
        {          // ----- Jump to next file

          if ($p_tar_mode == "tar")
            fseek($v_tar, ftell($v_tar)+(ceil(($v_header[size]/512))*512));
          else
            gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));
        }
      }

      // ----- Look for file that is not to be unzipped
      else
      {

        // ----- Jump to next file
        if ($p_tar_mode == "tar")
          fseek($v_tar, ($p_tar_mode=="tar"?ftell($v_tar):gztell($v_tar))+(ceil(($v_header[size]/512))*512));
        else
          gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));      }

      if ($p_tar_mode == "tar")
        $v_end_of_file = feof($v_tar);
      else
        $v_end_of_file = gzeof($v_tar);

      // ----- File name and properties are logged if listing mode or file is extracted
      if ($v_listing || $v_extract_file || $v_extraction_stopped)
      {        // ----- Log extracted files
        if (($v_file_dir = dirname($p_path.$v_header[filename])) == $p_path.$v_header[filename])
          $v_file_dir = "";
        if ((substr($p_path.$v_header[filename], 0, 1) == "/") && ($v_file_dir == ""))
          $v_file_dir = "/";

        // ----- Add the array describing the file into the list
        $p_list_detail[$v_nb] = $v_header;

        // ----- Increment
        $v_nb++;
      }
    }

    // ----- Close the tarfile
    if ($p_tar_mode == "tar")
      fclose($v_tar);
    else
      gzclose($v_tar);

    // ----- Return

    return $v_result;
  }
  // --------------------------------------------------------------------------------

  // --------------------------------------------------------------------------------
  // Function : PclTarHandleReadHeader()
  // Description :
  // Parameters :
  // Return Values :
  // --------------------------------------------------------------------------------
  function PclTarHandleReadHeader($v_binary_data, &$v_header)
  {

    $v_result=1;

    // ----- Read the 512 bytes header
    /*
    if ($p_tar_mode == "tar")
      $v_binary_data = fread($p_tar, 512);
    else
      $v_binary_data = gzread($p_tar, 512);
    */

    // ----- Look for no more block
    if (strlen($v_binary_data)==0)
    {
      $v_header[filename] = "";
      $v_header[status] = "empty";

      // ----- Return

      return $v_result;
    }

    // ----- Look for invalid block size
    if (strlen($v_binary_data) != 512)
    {
      $v_header[filename] = "";
      $v_header[status] = "invalid_header";      // ----- Error log
      PclErrorLog(-10, "Invalid block size : ".strlen($v_binary_data));

      // ----- Return

      return PclErrorCode();
    }

    // ----- Calculate the checksum
    $v_checksum = 0;
    // ..... First part of the header
    for ($i=0; $i<148; $i++)
    {
      $v_checksum+=ord($v_binary_data{$i});
    }
    // ..... Ignore the checksum value and replace it by ' ' (space)
    for ($i=148; $i<156; $i++)
    {
      $v_checksum += ord(' ');
    }
    // ..... Last part of the header
    for ($i=156; $i<512; $i++)
    {
      $v_checksum+=ord($v_binary_data{$i});
    }    // ----- Extract the values

    $v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor", $v_binary_data);
	
    // ----- Extract the checksum for check
    $v_header[checksum] = OctDec(trim($v_data[checksum]));

    if ($v_header[checksum] != $v_checksum)
    {      $v_header[filename] = "";
      $v_header[status] = "invalid_header";

      // ----- Look for last block (empty block)
      if (($v_checksum == 256) && ($v_header[checksum] == 0))
      {
        $v_header[status] = "empty";
        // ----- Return

        return $v_result;
      }

      // ----- Error log
      PclErrorLog(-13, "Invalid checksum : $v_checksum calculated, $v_header[checksum] expected");

      // ----- Return

      return PclErrorCode();
    }    // ----- Extract the properties
    $v_header[filename] = trim($v_data[filename]);

    $v_header[mode] = OctDec(trim($v_data[mode]));

    $v_header[uid] = OctDec(trim($v_data[uid]));

    $v_header[gid] = OctDec(trim($v_data[gid]));

    $v_header[size] = OctDec(trim($v_data[size]));

    $v_header[mtime] = OctDec(trim($v_data[mtime]));

    if (($v_header[typeflag] = $v_data[typeflag]) == "5")
    {
      $v_header[size] = 0;

    }

    /* ----- All these fields are removed form the header because they do not carry interesting info
    $v_header[link] = trim($v_data[link]);

    $v_header[magic] = trim($v_data[magic]);

    $v_header[version] = trim($v_data[version]);

    $v_header[uname] = trim($v_data[uname]);

    $v_header[gname] = trim($v_data[gname]);

    $v_header[devmajor] = trim($v_data[devmajor]);

    $v_header[devminor] = trim($v_data[devminor]);

    */

    // ----- Set the status field
    $v_header[status] = "ok";

    // ----- Return

    return $v_result;
  }
  // --------------------------------------------------------------------------------

  // --------------------------------------------------------------------------------
  // Function : PclTarHandlerDirCheck ( )
  // Description :
  //   Check if a directory exists, if not it creates it and all the parents directory
  //   which may be useful.
  // Parameters :
  //   $p_dir : Directory path to check (without / at the end).
  // Return Values :
  //    1 : OK
  //   -1 : Unable to create directory
  // --------------------------------------------------------------------------------
  function PclTarHandlerDirCheck($p_dir, $p_path)
  {
    $v_result = 1;
	
//L	echo "Checking dir <b>$p_dir</b><br>";
	
    // ----- Check the directory availability
    if (is_dir($p_path.$p_dir) || !isset($p_dir[0]))
		return 1;
		
    // ----- Look for file alone
    /*
    if (!strstr("$p_dir", "/"))
    {

      return 1;
    }
    */

    // ----- Extract parent directory
    $p_parent_dir = dirname($p_dir);    // ----- Just a check
    if ($p_parent_dir != $p_dir)
    {
//L		echo 'Needs parent folder <b>'.$p_parent_dir.'</b><br >';
      // ----- Look for parent directory
      if (($p_parent_dir !== "") && ($p_parent_dir!='.'))
      {
        if (($v_result = PclTarHandlerDirCheck($p_parent_dir, $p_path)) != 1)
          return $v_result;
      }
    }

    // ----- Create the directory

    if (!@mkdir($p_path.$p_dir))	// not using 0777 because might mess up some PHP configurations
    {
      // ----- Error log
      PclErrorLog(-8, "Unable to create directory '$p_path$p_dir'");

      // ----- Return

      return PclErrorCode();
    }

    // ----- Return

    return $v_result;
  }
  // --------------------------------------------------------------------------------

  // --------------------------------------------------------------------------------
  // Function : PclTarHandleExtension()
  // Description :
  // Parameters :
  // Return Values :
  // --------------------------------------------------------------------------------
  function PclTarHandleExtension($p_tarname)
  {    // ----- Look for file extension
    if ((substr($p_tarname, -7) == ".tar.gz") || (substr($p_tarname, -4) == ".tgz"))
    {

      $v_tar_mode = "tgz";
    }
    else if (substr($p_tarname, -4) == ".tar")
    {

      $v_tar_mode = "tar";
    }
    else
    {
      // ----- Error log
      PclErrorLog(-9, "Invalid archive extension");
      $v_tar_mode = "";
    }

    // ----- Return

    return $v_tar_mode;
  }

  // ----- Internal variables
  // These values must only be change by PclError library functions
  $g_pcl_error_string = "";
  $g_pcl_error_code = 1;  // --------------------------------------------------------------------------------
  // Function : PclErrorLog()
  // Description :
  // Parameters :
  // --------------------------------------------------------------------------------
  function PclErrorLog($p_error_code=0, $p_error_string="")
  {
    global $g_pcl_error_string;
    global $g_pcl_error_code;

    $g_pcl_error_code = $p_error_code;
    $g_pcl_error_string = $p_error_string;

	echo $p_error_string.'<br>';

  }
  // --------------------------------------------------------------------------------

  // --------------------------------------------------------------------------------
  // Function : PclErrorFatal()
  // Description :
  // Parameters :
  // --------------------------------------------------------------------------------
  function PclErrorFatal($p_file, $p_line, $p_error_string="")
  {
    global $g_pcl_error_string;
    global $g_pcl_error_code;

    $v_message =  "<html><body>";
    $v_message .= "<p align=center><font color=red bgcolor=white><b>PclError Library has detected a fatal error on file '$p_file', line $p_line</b></font></p>";
    $v_message .= "<p align=center><font color=red bgcolor=white><b>$p_error_string</b></font></p>";
    $v_message .= "</body></html>";
    die($v_message);
  }
  // --------------------------------------------------------------------------------

  // --------------------------------------------------------------------------------
  // Function : PclErrorReset()
  // Description :
  // Parameters :
  // --------------------------------------------------------------------------------
  function PclErrorReset()
  {
    global $g_pcl_error_string;
    global $g_pcl_error_code;

    $g_pcl_error_code = 1;
    $g_pcl_error_string = "";
  }
  // --------------------------------------------------------------------------------

  // --------------------------------------------------------------------------------
  // Function : PclErrorCode()
  // Description :
  // Parameters :
  // --------------------------------------------------------------------------------
  function PclErrorCode()
  {
    global $g_pcl_error_string;
    global $g_pcl_error_code;

    return($g_pcl_error_code);
  }
  // --------------------------------------------------------------------------------

  // --------------------------------------------------------------------------------
  // Function : PclErrorString()
  // Description :
  // Parameters :
  // --------------------------------------------------------------------------------
  function PclErrorString()
  {
    global $g_pcl_error_string;
    global $g_pcl_error_code;

    return($g_pcl_error_string." [code $g_pcl_error_code]");
  }
  // --------------------------------------------------------------------------------
  // ----- End of double include look

// veloce script begins

session_start();

if (@$_GET['auto'])
	$auto = 1;
else $auto = 0;

?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta name="author" content="legolas558">
<title>Veloce Extraction wizard</title>
</head>
<body<?php if ($auto) echo ' onLoad="do_auto()"';?>>
<div style="width:50%; height:20px; position: absolute; left: 10px; top:15px; background-color:black; text-align:right; color:white"><sub>by <a href="http://sf.net/users/legolas558">legolas558</a></sub>&nbsp;</div>
<div style="width:20px; height:50%; position: absolute; left: 20px; top:5px; background-color:gray"></div>
<div style="position: absolute; left:50px; top:45px; font-family: tahoma; background-color:#B1D3ED ">
<h2>Veloce extraction wizard</h2>
<form <?php if (isset($_GET['step'])) {?> onSubmit="return do_submit()"<?php } ?> name="veloce" method="get" action="<?php echo basename($_SERVER['PHP_SELF']);?>">
<?php

if (!isset($_GET['step'])) {

$found = archives_list($root);

$c = count($found);
if (!$c) {?>
	<p>No archives found in current folder</p>
	<p>Archives must have extension .tar, .gz or .tgz and must be packed with POSIX-compliant TAR headers</p>
	<?php } else {
	?><p>Select archive to extract</p><?php

	function one_option($filename, $ext) {
	global $root;
	?><label>
    <input type="radio" name="chosen" value="<?php echo $filename ?>"<?php echo $ext; ?>>
    <?php echo $filename.' ('.filesize($root.$filename).' bytes)'; ?></label>
    <br>
	<?php }

	one_option($found[0], ' checked="1"');

	for ($i=1;$i<$c;$i++)
		one_option($found[$i], '');

?><br><input type="submit" id="btnSubmit" value="Start">
	<label for="auto"><input id="auto" type="checkbox" name="auto">Continuous mode</label>
	<input name="step" type="hidden" value="0"><?php
	}

} else {
echo '<pre>';
$step = ((int)$_GET['step']);

$tar = new TarExtract($_SESSION['tarextract']);

if ($step==0) {

	// change here the (relative) destination path WITH TRAILING SLASH '/' please
	// or leave empty to use the current directory
	$dest = '';
	
	if ($dest==='')
		$wt = is__writable('./');
	else
		$wt = is__writable($dest);
		
	if (!$wt) {
		echo 'Sorry, folder '.$dest.' is not writable<br>';
		die;
	}

	$tar->BeginExtract($root, $root.$_GET['chosen'], $dest);
}
else
	if (!isset($tar->progress))
		trigger_error('Session lost, restart please', 256);

	function extract_cb($tbk) {
		global $message, $finished;

		if ($tbk->Finished()) {
			$message = 'Extraction 100% complete<br/><br/>Pressing "Exit &amp; Delete" will cause the archive <i>'.$_GET['chosen'].'</i> and this script <i>'.basename($_SERVER['PHP_SELF']).'</i> to be deleted';
			$finished = true;
		} else {
			$message = '<b>'.$tbk->Percent().'%</b> complete<br/>';
			$finished = false;
		}
	}

	$tar->Extract('extract_cb', $max_time + time() - $start - 4);

?>
<input type="hidden" name="step" value="<?php echo ($step+1); ?>">
<input type="hidden" name="auto" value="<?php echo $auto; ?>">
<input type="hidden" name="chosen" value="<?php echo $_GET['chosen']; ?>">
<p><?php
	echo $message;
	
?></p><?php if (!$finished) {?>
<script language="javascript" type="text/javascript">
function do_submit() {
	document.getElementById('btnSubmit').disabled = true;
	return true;
}
function do_auto() {
	document.forms[0].submit();
}
</script>
<input type="submit" id="btnSubmit" value="Continue"><?php } else {?>
<script language="javascript" type="text/javascript">
function do_submit() {	return true; }
function do_auto() { }
</script>
<input id="kill" type="hidden" name="kill" value="0">
<input type="button" value="Exit" onclick="document.location='<?php

echo default_redir($root);

?>'">
<input type="button" value="Exit &amp; Delete" onclick="document.getElementById('kill').value = 1; document.forms[0].submit();">
<?php
}
} ?>
</form>
</div>
</body>
</html>
<?php

// misc functions

function file_ext($file)
{
	$p = strrpos($file, '.');
	if ($p===false)return '';
	return strtolower(substr($file,$p+1));
}

function archives_list($parent)
{
	$allowed_ext = array('tgz','tar', 'gz');
	$dh=opendir($parent);
	$found = array();
	while (false !== ($filename = readdir($dh))) {
		if( $filename[0]=='.' ) continue;
		if (!is_dir( $parent.$filename ) && in_array(file_ext($filename), $allowed_ext))
			$found[] = $filename;
	}
	return $found;
}

function default_redir($root) {
if (file_exists($root.'install/index.php'))
	return 'install/index.php';
else
	return 'index.php';
}

// from Drake CMS project
function is__writable($path) {
//see http://bugs.php.net/bug.php?id=27609
//see http://bugs.php.net/bug.php?id=30931

	if ($path{strlen($path)-1}=='/') // recursively return a temporary file path
	    return is__writable($path.uniqid(mt_rand()).'.tmp');
	else if (is_dir($path))
		return is__writable($path.'/'.uniqid(mt_rand()).'.tmp');
	// check tmp file for read/write capabilities
	$rm = file_exists($path);
	$f = @fopen($path, 'a');
	if ($f===false)
		return false;
	fclose($f);
	if (!$rm)
		unlink($path);
	return true;
}

?>