PHP Malware Analysis

unzipper.php

md5: 2c0054a3231fd40f5c65910b3f802a4b

Jump to:

Screenshot


Attributes

Input

Title

URLs


Deobfuscated PHP code

<?php

/**
 * The Unzipper extracts .zip or .rar archives and .gz files on webservers.
 * It's handy if you do not have shell access. E.g. if you want to upload a lot
 * of files (php framework or image collection) as an archive to save time.
 * As of version 0.1.0 it also supports creating archives.
 *
 * @author  Andreas Tasch, at[tec], attec.at
 * @license GNU GPL v3
 * @package attec.toolbox
 * @version 0.1.0
 */
define('VERSION', '0.1.0');
$timestart = microtime(TRUE);
$GLOBALS['status'] = array();
$unzipper = new Unzipper();
if (isset($_POST['dounzip'])) {
    //check if an archive was selected for unzipping
    $archive = isset($_POST['zipfile']) ? strip_tags($_POST['zipfile']) : '';
    $destination = isset($_POST['extpath']) ? strip_tags($_POST['extpath']) : '';
    $unzipper->prepareExtraction($archive, $destination);
}
if (isset($_POST['dozip'])) {
    $zippath = !empty($_POST['zippath']) ? strip_tags($_POST['zippath']) : '.';
    // Resulting zipfile e.g. zipper--2016-07-23--11-55.zip
    $zipfile = 'zipper-' . date("Y-m-d--H-i") . '.zip';
    Zipper::zipDir($zippath, $zipfile);
}
$timeend = microtime(TRUE);
$time = $timeend - $timestart;
/**
 * Class Unzipper
 */
class Unzipper
{
    public $localdir = '.';
    public $zipfiles = array();
    public function __construct()
    {
        //read directory and pick .zip and .gz files
        if ($dh = opendir($this->localdir)) {
            while (($file = readdir($dh)) !== FALSE) {
                if (pathinfo($file, PATHINFO_EXTENSION) === 'zip' || pathinfo($file, PATHINFO_EXTENSION) === 'gz' || pathinfo($file, PATHINFO_EXTENSION) === 'rar') {
                    $this->zipfiles[] = $file;
                }
            }
            closedir($dh);
            if (!empty($this->zipfiles)) {
                $GLOBALS['status'] = array('info' => '.zip or .gz or .rar files found, ready for extraction');
            } else {
                $GLOBALS['status'] = array('info' => 'No .zip or .gz or rar files found. So only zipping functionality available.');
            }
        }
    }
    /**
     * Prepare and check zipfile for extraction.
     *
     * @param $archive
     * @param $destination
     */
    public function prepareExtraction($archive, $destination)
    {
        // Determine paths.
        if (empty($destination)) {
            $extpath = $this->localdir;
        } else {
            $extpath = $this->localdir . '/' . $destination;
            // todo move this to extraction function
            if (!is_dir($extpath)) {
                mkdir($extpath);
            }
        }
        //allow only local existing archives to extract
        if (in_array($archive, $this->zipfiles)) {
            self::extract($archive, $extpath);
        }
    }
    /**
     * Checks file extension and calls suitable extractor functions.
     *
     * @param $archive
     * @param $destination
     */
    public static function extract($archive, $destination)
    {
        $ext = pathinfo($archive, PATHINFO_EXTENSION);
        switch ($ext) {
            case 'zip':
                self::extractZipArchive($archive, $destination);
                break;
            case 'gz':
                self::extractGzipFile($archive, $destination);
                break;
            case 'rar':
                self::extractRarArchive($archive, $destination);
                break;
        }
    }
    /**
     * Decompress/extract a zip archive using ZipArchive.
     *
     * @param $archive
     * @param $destination
     */
    public static function extractZipArchive($archive, $destination)
    {
        // Check if webserver supports unzipping.
        if (!class_exists('ZipArchive')) {
            $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support unzip functionality.');
            return;
        }
        $zip = new ZipArchive();
        // Check if archive is readable.
        if ($zip->open($archive) === TRUE) {
            // Check if destination is writable
            if (is_writeable($destination . '/')) {
                $zip->extractTo($destination);
                $zip->close();
                $GLOBALS['status'] = array('success' => 'Files unzipped successfully');
            } else {
                $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
            }
        } else {
            $GLOBALS['status'] = array('error' => 'Error: Cannot read .zip archive.');
        }
    }
    /**
     * Decompress a .gz File.
     *
     * @param $archive
     * @param $destination
     */
    public static function extractGzipFile($archive, $destination)
    {
        // Check if zlib is enabled
        if (!function_exists('gzopen')) {
            $GLOBALS['status'] = array('error' => 'Error: Your PHP has no zlib support enabled.');
            return;
        }
        $filename = pathinfo($archive, PATHINFO_FILENAME);
        $gzipped = gzopen($archive, "rb");
        $file = fopen($filename, "w");
        while ($string = gzread($gzipped, 4096)) {
            fwrite($file, $string, strlen($string));
        }
        gzclose($gzipped);
        fclose($file);
        // Check if file was extracted.
        if (file_exists($destination . '/' . $filename)) {
            $GLOBALS['status'] = array('success' => 'File unzipped successfully.');
        } else {
            $GLOBALS['status'] = array('error' => 'Error unzipping file.');
        }
    }
    /**
     * Decompress/extract a Rar archive using RarArchive.
     *
     * @param $archive
     * @param $destination
     */
    public static function extractRarArchive($archive, $destination)
    {
        // Check if webserver supports unzipping.
        if (!class_exists('RarArchive')) {
            $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support .rar archive functionality. <a class="info" href="http://php.net/manual/en/rar.installation.php" target="_blank">How to install RarArchive</a>');
            return;
        }
        // Check if archive is readable.
        if ($rar = RarArchive::open($archive)) {
            // Check if destination is writable
            if (is_writeable($destination . '/')) {
                $entries = $rar->getEntries();
                foreach ($entries as $entry) {
                    $entry->extract($destination);
                }
                $rar->close();
                $GLOBALS['status'] = array('success' => 'Files extracted successfully.');
            } else {
                $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
            }
        } else {
            $GLOBALS['status'] = array('error' => 'Error: Cannot read .rar archive.');
        }
    }
}
/**
 * Class Zipper
 *
 * Copied and slightly modified from http://at2.php.net/manual/en/class.ziparchive.php#110719
 * @author umbalaconmeogia
 */
class Zipper
{
    /**
     * Add files and sub-directories in a folder to zip file.
     *
     * @param string     $folder
     *   Path to folder that should be zipped.
     *
     * @param ZipArchive $zipFile
     *   Zipfile where files end up.
     *
     * @param int        $exclusiveLength
     *   Number of text to be exclusived from the file path.
     */
    private static function folderToZip($folder, &$zipFile, $exclusiveLength)
    {
        $handle = opendir($folder);
        while (FALSE !== ($f = readdir($handle))) {
            // Check for local/parent path or zipping file itself and skip.
            if ($f != '.' && $f != '..' && $f != basename("/var/www/html/unzipper.php.3ede35852730b4ed7e4b2001b323088f.bin")) {
                $filePath = "{$folder}/{$f}";
                // Remove prefix from file path before add to zip.
                $localPath = substr($filePath, $exclusiveLength);
                if (is_file($filePath)) {
                    $zipFile->addFile($filePath, $localPath);
                } elseif (is_dir($filePath)) {
                    // Add sub-directory.
                    $zipFile->addEmptyDir($localPath);
                    self::folderToZip($filePath, $zipFile, $exclusiveLength);
                }
            }
        }
        closedir($handle);
    }
    /**
     * Zip a folder (including itself).
     * Usage:
     *   Zipper::zipDir('path/to/sourceDir', 'path/to/out.zip');
     *
     * @param string $sourcePath
     *   Relative path of directory to be zipped.
     *
     * @param string $outZipPath
     *   Relative path of the resulting output zip file.
     */
    public static function zipDir($sourcePath, $outZipPath)
    {
        $pathInfo = pathinfo($sourcePath);
        $parentPath = $pathInfo['dirname'];
        $dirName = $pathInfo['basename'];
        $z = new ZipArchive();
        $z->open($outZipPath, ZipArchive::CREATE);
        $z->addEmptyDir($dirName);
        if ($sourcePath == $dirName) {
            self::folderToZip($sourcePath, $z, 0);
        } else {
            self::folderToZip($sourcePath, $z, strlen("{$parentPath}/"));
        }
        $z->close();
        $GLOBALS['status'] = array('success' => 'Successfully created archive ' . $outZipPath);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>File Unzipper + Zipper</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <style type="text/css">
    <!--
    body {
      font-family: Arial, sans-serif;
      line-height: 150%;
    }

    label {
      display: block;
      margin-top: 20px;
    }

    fieldset {
      border: 0;
      background-color: #EEE;
      margin: 10px 0 10px 0;
    }

    .select {
      padding: 5px;
      font-size: 110%;
    }

    .status {
      margin: 0;
      margin-bottom: 20px;
      padding: 10px;
      font-size: 80%;
      background: #EEE;
      border: 1px dotted #DDD;
    }

    .status--ERROR {
      background-color: red;
      color: white;
      font-size: 120%;
    }

    .status--SUCCESS {
      background-color: green;
      font-weight: bold;
      color: white;
      font-size: 120%
    }

    .small {
      font-size: 0.7rem;
      font-weight: normal;
    }

    .version {
      font-size: 80%;
    }

    .form-field {
      border: 1px solid #AAA;
      padding: 8px;
      width: 280px;
    }

    .info {
      margin-top: 0;
      font-size: 80%;
      color: #777;
    }

    .submit {
      background-color: #378de5;
      border: 0;
      color: #ffffff;
      font-size: 15px;
      padding: 10px 24px;
      margin: 20px 0 20px 0;
      text-decoration: none;
    }

    .submit:hover {
      background-color: #2c6db2;
      cursor: pointer;
    }
    -->
  </style>
</head>
<body>
<p class="status status--<?php 
echo strtoupper(key($GLOBALS['status']));
?>">
  Status: <?php 
echo reset($GLOBALS['status']);
?><br/>
  <span class="small">Processing Time: <?php 
echo $time;
?> seconds</span>
</p>
<form action="" method="POST">
  <fieldset>
    <h1>Archive Unzipper</h1>
    <label for="zipfile">Select .zip or .rar archive or .gz file you want to extract:</label>
    <select name="zipfile" size="1" class="select">
      <?php 
foreach ($unzipper->zipfiles as $zip) {
    echo "<option>{$zip}</option>";
}
?>
    </select>
    <label for="extpath">Extraction path (optional):</label>
    <input type="text" name="extpath" class="form-field" />
    <p class="info">Enter extraction path without leading or trailing slashes (e.g. "mypath"). If left empty current directory will be used.</p>
    <input type="submit" name="dounzip" class="submit" value="Unzip Archive"/>
  </fieldset>

  <fieldset>
    <h1>Archive Zipper</h1>
    <label for="zippath">Path that should be zipped (optional):</label>
    <input type="text" name="zippath" class="form-field" />
    <p class="info">Enter path to be zipped without leading or trailing slashes (e.g. "zippath"). If left empty current directory will be used.</p>
    <input type="submit" name="dozip" class="submit" value="Zip Archive"/>
  </fieldset>
</form>
<p class="version">Unzipper version: <?php 
echo "0.1.0";
?></p>
</body>
</html>

Execution traces

data/traces/2c0054a3231fd40f5c65910b3f802a4b_trace-1676257369.74.xt
Version: 3.1.0beta2
File format: 4
TRACE START [2023-02-13 01:03:15.637849]
1	0	1	0.000247	393528
1	3	0	0.000570	448096	{main}	1		/var/www/html/uploads/unzipper.php	0	0
2	4	0	0.000591	448096	define	0		/var/www/html/uploads/unzipper.php	13	2	'VERSION'	'0.1.0'
2	4	1	0.000609	448200
2	4	R			TRUE
2	5	0	0.000623	448128	microtime	0		/var/www/html/uploads/unzipper.php	15	1	TRUE
2	5	1	0.000635	448168
2	5	R			1676257369.7405
1		A						/var/www/html/uploads/unzipper.php	15	$timestart = 1676257369.7405
1		A						/var/www/html/uploads/unzipper.php	16	GLOBALS['status'] = []
2	6	0	0.000678	448208	Unzipper->__construct	1		/var/www/html/uploads/unzipper.php	18	0
3	7	0	0.000693	448208	opendir	0		/var/www/html/uploads/unzipper.php	46	1	'.'
3	7	1	0.000714	448600
3	7	R			resource(4) of type (stream)
2		A						/var/www/html/uploads/unzipper.php	46	$dh = resource(4) of type (stream)
3	8	0	0.000742	448568	readdir	0		/var/www/html/uploads/unzipper.php	47	1	resource(4) of type (stream)
3	8	1	0.000764	448648
3	8	R			'unzipper.php'
2		A						/var/www/html/uploads/unzipper.php	47	$file = 'unzipper.php'
3	9	0	0.000789	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	48	2	'unzipper.php'	4
3	9	1	0.000806	448704
3	9	R			'php'
3	10	0	0.000819	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	49	2	'unzipper.php'	4
3	10	1	0.000833	448704
3	10	R			'php'
3	11	0	0.000846	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	50	2	'unzipper.php'	4
3	11	1	0.000860	448704
3	11	R			'php'
3	12	0	0.000872	448608	readdir	0		/var/www/html/uploads/unzipper.php	47	1	resource(4) of type (stream)
3	12	1	0.000886	448680
3	12	R			'..'
2		A						/var/www/html/uploads/unzipper.php	47	$file = '..'
3	13	0	0.000909	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	48	2	'..'	4
3	13	1	0.000922	448696
3	13	R			''
3	14	0	0.000934	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	49	2	'..'	4
3	14	1	0.000947	448696
3	14	R			''
3	15	0	0.000959	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	50	2	'..'	4
3	15	1	0.000972	448696
3	15	R			''
3	16	0	0.000984	448600	readdir	0		/var/www/html/uploads/unzipper.php	47	1	resource(4) of type (stream)
3	16	1	0.000997	448672
3	16	R			'.'
2		A						/var/www/html/uploads/unzipper.php	47	$file = '.'
3	17	0	0.001020	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	48	2	'.'	4
3	17	1	0.001032	448696
3	17	R			''
3	18	0	0.001045	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	49	2	'.'	4
3	18	1	0.001057	448696
3	18	R			''
3	19	0	0.001069	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	50	2	'.'	4
3	19	1	0.001081	448696
3	19	R			''
3	20	0	0.001093	448600	readdir	0		/var/www/html/uploads/unzipper.php	47	1	resource(4) of type (stream)
3	20	1	0.001106	448680
3	20	R			'prepend.php'
2		A						/var/www/html/uploads/unzipper.php	47	$file = 'prepend.php'
3	21	0	0.001130	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	48	2	'prepend.php'	4
3	21	1	0.001143	448704
3	21	R			'php'
3	22	0	0.001155	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	49	2	'prepend.php'	4
3	22	1	0.001169	448704
3	22	R			'php'
3	23	0	0.001181	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	50	2	'prepend.php'	4
3	23	1	0.001194	448704
3	23	R			'php'
3	24	0	0.001206	448608	readdir	0		/var/www/html/uploads/unzipper.php	47	1	resource(4) of type (stream)
3	24	1	0.001220	448680
3	24	R			'data'
2		A						/var/www/html/uploads/unzipper.php	47	$file = 'data'
3	25	0	0.001243	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	48	2	'data'	4
3	25	1	0.001255	448664
3	25	R			''
3	26	0	0.001267	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	49	2	'data'	4
3	26	1	0.001280	448664
3	26	R			''
3	27	0	0.001291	448600	pathinfo	0		/var/www/html/uploads/unzipper.php	50	2	'data'	4
3	27	1	0.001304	448664
3	27	R			''
3	28	0	0.001316	448600	readdir	0		/var/www/html/uploads/unzipper.php	47	1	resource(4) of type (stream)
3	28	1	0.001335	448680
3	28	R			'.htaccess'
2		A						/var/www/html/uploads/unzipper.php	47	$file = '.htaccess'
3	29	0	0.001359	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	48	2	'.htaccess'	4
3	29	1	0.001372	448712
3	29	R			'htaccess'
3	30	0	0.001385	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	49	2	'.htaccess'	4
3	30	1	0.001399	448712
3	30	R			'htaccess'
3	31	0	0.001412	448608	pathinfo	0		/var/www/html/uploads/unzipper.php	50	2	'.htaccess'	4
3	31	1	0.001424	448712
3	31	R			'htaccess'
3	32	0	0.001437	448608	readdir	0		/var/www/html/uploads/unzipper.php	47	1	resource(4) of type (stream)
3	32	1	0.001451	448648
3	32	R			FALSE
2		A						/var/www/html/uploads/unzipper.php	47	$file = FALSE
3	33	0	0.001473	448568	closedir	0		/var/www/html/uploads/unzipper.php	55	1	resource(4) of type (stream)
3	33	1	0.001489	448384
3	33	R			NULL
2		A						/var/www/html/uploads/unzipper.php	61	GLOBALS['status'] = ['info' => 'No .zip or .gz or rar files found. So only zipping functionality available.']
2	6	1	0.001520	448320
1		A						/var/www/html/uploads/unzipper.php	18	$unzipper = class Unzipper { public $localdir = '.'; public $zipfiles = [] }
2	34	0	0.001555	448696	microtime	0		/var/www/html/uploads/unzipper.php	33	1	TRUE
2	34	1	0.001567	448736
2	34	R			1676257369.7414
1		A						/var/www/html/uploads/unzipper.php	33	$timeend = 1676257369.7414
1		A						/var/www/html/uploads/unzipper.php	34	$time = 0.00093197822570801
2	35	0	0.001605	448672	key	0		/var/www/html/uploads/unzipper.php	374	1	['info' => 'No .zip or .gz or rar files found. So only zipping functionality available.']
2	35	1	0.001622	448704
2	35	R			'info'
2	36	0	0.001635	448672	strtoupper	0		/var/www/html/uploads/unzipper.php	374	1	'info'
2	36	1	0.001648	448736
2	36	R			'INFO'
2	37	0	0.001662	448696	reset	0		/var/www/html/uploads/unzipper.php	375	1	['info' => 'No .zip or .gz or rar files found. So only zipping functionality available.']
2	37	1	0.001679	449104
2	37	R			'No .zip or .gz or rar files found. So only zipping functionality available.'
1	3	1	0.001701	449072
			0.001730	354440
TRACE END   [2023-02-13 01:03:15.639375]


Generated HTML code

<html><head>
  <title>File Unzipper + Zipper</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <style type="text/css">
    <!--
    body {
      font-family: Arial, sans-serif;
      line-height: 150%;
    }

    label {
      display: block;
      margin-top: 20px;
    }

    fieldset {
      border: 0;
      background-color: #EEE;
      margin: 10px 0 10px 0;
    }

    .select {
      padding: 5px;
      font-size: 110%;
    }

    .status {
      margin: 0;
      margin-bottom: 20px;
      padding: 10px;
      font-size: 80%;
      background: #EEE;
      border: 1px dotted #DDD;
    }

    .status--ERROR {
      background-color: red;
      color: white;
      font-size: 120%;
    }

    .status--SUCCESS {
      background-color: green;
      font-weight: bold;
      color: white;
      font-size: 120%
    }

    .small {
      font-size: 0.7rem;
      font-weight: normal;
    }

    .version {
      font-size: 80%;
    }

    .form-field {
      border: 1px solid #AAA;
      padding: 8px;
      width: 280px;
    }

    .info {
      margin-top: 0;
      font-size: 80%;
      color: #777;
    }

    .submit {
      background-color: #378de5;
      border: 0;
      color: #ffffff;
      font-size: 15px;
      padding: 10px 24px;
      margin: 20px 0 20px 0;
      text-decoration: none;
    }

    .submit:hover {
      background-color: #2c6db2;
      cursor: pointer;
    }
    -->
  </style>
</head>
<body>
<p class="status status--INFO">
  Status: No .zip or .gz or rar files found. So only zipping functionality available.<br>
  <span class="small">Processing Time: 5.1975250244141E-5 seconds</span>
</p>
<form action="" method="POST">
  <fieldset>
    <h1>Archive Unzipper</h1>
    <label for="zipfile">Select .zip or .rar archive or .gz file you want to extract:</label>
    <select name="zipfile" size="1" class="select">
          </select>
    <label for="extpath">Extraction path (optional):</label>
    <input type="text" name="extpath" class="form-field">
    <p class="info">Enter extraction path without leading or trailing slashes (e.g. "mypath"). If left empty current directory will be used.</p>
    <input type="submit" name="dounzip" class="submit" value="Unzip Archive">
  </fieldset>

  <fieldset>
    <h1>Archive Zipper</h1>
    <label for="zippath">Path that should be zipped (optional):</label>
    <input type="text" name="zippath" class="form-field">
    <p class="info">Enter path to be zipped without leading or trailing slashes (e.g. "zippath"). If left empty current directory will be used.</p>
    <input type="submit" name="dozip" class="submit" value="Zip Archive">
  </fieldset>
</form>
<p class="version">Unzipper version: 0.1.0</p>

</body></html>

Original PHP code

<?php
/**
 * The Unzipper extracts .zip or .rar archives and .gz files on webservers.
 * It's handy if you do not have shell access. E.g. if you want to upload a lot
 * of files (php framework or image collection) as an archive to save time.
 * As of version 0.1.0 it also supports creating archives.
 *
 * @author  Andreas Tasch, at[tec], attec.at
 * @license GNU GPL v3
 * @package attec.toolbox
 * @version 0.1.0
 */
define('VERSION', '0.1.0');

$timestart = microtime(TRUE);
$GLOBALS['status'] = array();

$unzipper = new Unzipper;
if (isset($_POST['dounzip'])) {
  //check if an archive was selected for unzipping
  $archive = isset($_POST['zipfile']) ? strip_tags($_POST['zipfile']) : '';
  $destination = isset($_POST['extpath']) ? strip_tags($_POST['extpath']) : '';
  $unzipper->prepareExtraction($archive, $destination);
}

if (isset($_POST['dozip'])) {
  $zippath = !empty($_POST['zippath']) ? strip_tags($_POST['zippath']) : '.';
  // Resulting zipfile e.g. zipper--2016-07-23--11-55.zip
  $zipfile = 'zipper-' . date("Y-m-d--H-i") . '.zip';
  Zipper::zipDir($zippath, $zipfile);
}

$timeend = microtime(TRUE);
$time = $timeend - $timestart;

/**
 * Class Unzipper
 */
class Unzipper {
  public $localdir = '.';
  public $zipfiles = array();

  public function __construct() {

    //read directory and pick .zip and .gz files
    if ($dh = opendir($this->localdir)) {
      while (($file = readdir($dh)) !== FALSE) {
        if (pathinfo($file, PATHINFO_EXTENSION) === 'zip'
          || pathinfo($file, PATHINFO_EXTENSION) === 'gz'
          || pathinfo($file, PATHINFO_EXTENSION) === 'rar'
        ) {
          $this->zipfiles[] = $file;
        }
      }
      closedir($dh);

      if (!empty($this->zipfiles)) {
        $GLOBALS['status'] = array('info' => '.zip or .gz or .rar files found, ready for extraction');
      }
      else {
        $GLOBALS['status'] = array('info' => 'No .zip or .gz or rar files found. So only zipping functionality available.');
      }
    }
  }

  /**
   * Prepare and check zipfile for extraction.
   *
   * @param $archive
   * @param $destination
   */
  public function prepareExtraction($archive, $destination) {
    // Determine paths.
    if (empty($destination)) {
      $extpath = $this->localdir;
    }
    else {
      $extpath = $this->localdir . '/' . $destination;
      // todo move this to extraction function
      if (!is_dir($extpath)) {
        mkdir($extpath);
      }
    }
    //allow only local existing archives to extract
    if (in_array($archive, $this->zipfiles)) {
      self::extract($archive, $extpath);
    }
  }

  /**
   * Checks file extension and calls suitable extractor functions.
   *
   * @param $archive
   * @param $destination
   */
  public static function extract($archive, $destination) {
    $ext = pathinfo($archive, PATHINFO_EXTENSION);
    switch ($ext) {
      case 'zip':
        self::extractZipArchive($archive, $destination);
        break;
      case 'gz':
        self::extractGzipFile($archive, $destination);
        break;
      case 'rar':
        self::extractRarArchive($archive, $destination);
        break;
    }

  }

  /**
   * Decompress/extract a zip archive using ZipArchive.
   *
   * @param $archive
   * @param $destination
   */
  public static function extractZipArchive($archive, $destination) {
    // Check if webserver supports unzipping.
    if (!class_exists('ZipArchive')) {
      $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support unzip functionality.');
      return;
    }

    $zip = new ZipArchive;

    // Check if archive is readable.
    if ($zip->open($archive) === TRUE) {
      // Check if destination is writable
      if (is_writeable($destination . '/')) {
        $zip->extractTo($destination);
        $zip->close();
        $GLOBALS['status'] = array('success' => 'Files unzipped successfully');
      }
      else {
        $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
      }
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error: Cannot read .zip archive.');
    }
  }

  /**
   * Decompress a .gz File.
   *
   * @param $archive
   * @param $destination
   */
  public static function extractGzipFile($archive, $destination) {
    // Check if zlib is enabled
    if (!function_exists('gzopen')) {
      $GLOBALS['status'] = array('error' => 'Error: Your PHP has no zlib support enabled.');
      return;
    }

    $filename = pathinfo($archive, PATHINFO_FILENAME);
    $gzipped = gzopen($archive, "rb");
    $file = fopen($filename, "w");

    while ($string = gzread($gzipped, 4096)) {
      fwrite($file, $string, strlen($string));
    }
    gzclose($gzipped);
    fclose($file);

    // Check if file was extracted.
    if (file_exists($destination . '/' . $filename)) {
      $GLOBALS['status'] = array('success' => 'File unzipped successfully.');
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error unzipping file.');
    }

  }

  /**
   * Decompress/extract a Rar archive using RarArchive.
   *
   * @param $archive
   * @param $destination
   */
  public static function extractRarArchive($archive, $destination) {
    // Check if webserver supports unzipping.
    if (!class_exists('RarArchive')) {
      $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support .rar archive functionality. <a class="info" href="http://php.net/manual/en/rar.installation.php" target="_blank">How to install RarArchive</a>');
      return;
    }
    // Check if archive is readable.
    if ($rar = RarArchive::open($archive)) {
      // Check if destination is writable
      if (is_writeable($destination . '/')) {
        $entries = $rar->getEntries();
        foreach ($entries as $entry) {
          $entry->extract($destination);
        }
        $rar->close();
        $GLOBALS['status'] = array('success' => 'Files extracted successfully.');
      }
      else {
        $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
      }
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error: Cannot read .rar archive.');
    }
  }

}

/**
 * Class Zipper
 *
 * Copied and slightly modified from http://at2.php.net/manual/en/class.ziparchive.php#110719
 * @author umbalaconmeogia
 */
class Zipper {
  /**
   * Add files and sub-directories in a folder to zip file.
   *
   * @param string     $folder
   *   Path to folder that should be zipped.
   *
   * @param ZipArchive $zipFile
   *   Zipfile where files end up.
   *
   * @param int        $exclusiveLength
   *   Number of text to be exclusived from the file path.
   */
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);

    while (FALSE !== $f = readdir($handle)) {
      // Check for local/parent path or zipping file itself and skip.
      if ($f != '.' && $f != '..' && $f != basename(__FILE__)) {
        $filePath = "$folder/$f";
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);

        if (is_file($filePath)) {
          $zipFile->addFile($filePath, $localPath);
        }
        elseif (is_dir($filePath)) {
          // Add sub-directory.
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }

  /**
   * Zip a folder (including itself).
   * Usage:
   *   Zipper::zipDir('path/to/sourceDir', 'path/to/out.zip');
   *
   * @param string $sourcePath
   *   Relative path of directory to be zipped.
   *
   * @param string $outZipPath
   *   Relative path of the resulting output zip file.
   */
  public static function zipDir($sourcePath, $outZipPath) {
    $pathInfo = pathinfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];

    $z = new ZipArchive();
    $z->open($outZipPath, ZipArchive::CREATE);
    $z->addEmptyDir($dirName);
    if ($sourcePath == $dirName) {
      self::folderToZip($sourcePath, $z, 0);
    }
    else {
      self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
    }
    $z->close();

    $GLOBALS['status'] = array('success' => 'Successfully created archive ' . $outZipPath);
  }
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>File Unzipper + Zipper</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <style type="text/css">
    <!--
    body {
      font-family: Arial, sans-serif;
      line-height: 150%;
    }

    label {
      display: block;
      margin-top: 20px;
    }

    fieldset {
      border: 0;
      background-color: #EEE;
      margin: 10px 0 10px 0;
    }

    .select {
      padding: 5px;
      font-size: 110%;
    }

    .status {
      margin: 0;
      margin-bottom: 20px;
      padding: 10px;
      font-size: 80%;
      background: #EEE;
      border: 1px dotted #DDD;
    }

    .status--ERROR {
      background-color: red;
      color: white;
      font-size: 120%;
    }

    .status--SUCCESS {
      background-color: green;
      font-weight: bold;
      color: white;
      font-size: 120%
    }

    .small {
      font-size: 0.7rem;
      font-weight: normal;
    }

    .version {
      font-size: 80%;
    }

    .form-field {
      border: 1px solid #AAA;
      padding: 8px;
      width: 280px;
    }

    .info {
      margin-top: 0;
      font-size: 80%;
      color: #777;
    }

    .submit {
      background-color: #378de5;
      border: 0;
      color: #ffffff;
      font-size: 15px;
      padding: 10px 24px;
      margin: 20px 0 20px 0;
      text-decoration: none;
    }

    .submit:hover {
      background-color: #2c6db2;
      cursor: pointer;
    }
    -->
  </style>
</head>
<body>
<p class="status status--<?php echo strtoupper(key($GLOBALS['status'])); ?>">
  Status: <?php echo reset($GLOBALS['status']); ?><br/>
  <span class="small">Processing Time: <?php echo $time; ?> seconds</span>
</p>
<form action="" method="POST">
  <fieldset>
    <h1>Archive Unzipper</h1>
    <label for="zipfile">Select .zip or .rar archive or .gz file you want to extract:</label>
    <select name="zipfile" size="1" class="select">
      <?php foreach ($unzipper->zipfiles as $zip) {
        echo "<option>$zip</option>";
      }
      ?>
    </select>
    <label for="extpath">Extraction path (optional):</label>
    <input type="text" name="extpath" class="form-field" />
    <p class="info">Enter extraction path without leading or trailing slashes (e.g. "mypath"). If left empty current directory will be used.</p>
    <input type="submit" name="dounzip" class="submit" value="Unzip Archive"/>
  </fieldset>

  <fieldset>
    <h1>Archive Zipper</h1>
    <label for="zippath">Path that should be zipped (optional):</label>
    <input type="text" name="zippath" class="form-field" />
    <p class="info">Enter path to be zipped without leading or trailing slashes (e.g. "zippath"). If left empty current directory will be used.</p>
    <input type="submit" name="dozip" class="submit" value="Zip Archive"/>
  </fieldset>
</form>
<p class="version">Unzipper version: <?php echo VERSION; ?></p>
</body>
</html>