<?php
class ArchUtil {
	static function init($filePath, $ext = false) {
		global $fm, $config;
		$fileName = $fm->basename($filePath);
		if (!$ext) {$ext = $fm->getExtension($fileName);}
		if (in_array($ext, array("tar", "tar.gz", "tgz", "tar.bz2", "tbz"))) {
			require_once($config['path']['classes']."/arch/arch.tar.lib.php");
			return new ArchTar($filePath, $fileName, $ext);
		} else if (in_array($ext, array("zip", "jar"))) {
			require_once($config['path']['classes']."/arch/arch.zip.lib.php");
			if ($ext == "zip" && $config['app']['zip']['external']) {
				require_once($config['path']['classes']."/arch/arch.zip.external.lib.php");
				return new ArchZipExternal($filePath, $fileName, $ext);
			}
			return new ArchZip($filePath, $fileName, $ext);
		} else if (in_array($ext, array("gz"))) {
			require_once($config['path']['classes']."/arch/arch.gzip.lib.php");
			return new ArchGzip($filePath, $fileName, $ext);
		}
		return false;
	}
	static function isSupported($filePath) {
		global $fm;
		$fileName = $fm->basename($filePath);
		$ext = $fm->getExtension($fileName);
		if (in_array($ext, array("tar"))) {
			return true;
		} else if (in_array($ext, array("tar.bz2", "tbz"))) {
			if (function_exists("bzopen")) {
				return true;
			}
			//"This function requires <a href=\"http://www.php.net/manual/en/bzip2.installation.php\" target=\"_blank\">Bzip2</a> support to be enabled in PHP.";

		} else if (in_array($ext, array("zip", "jar", "tar.gz", "tgz", "gz"))) {
			if (function_exists("gzopen")) {
				return true;
			}
			//"This function requires <a href=\"http://www.php.net/manual/en/zlib.installation.php\" target=\"_blank\">Zlib</a> support to be enabled in PHP.";
		}
		return false;
	}
}

class AbstractArch {
	function __construct($filePath, $fileName = false, $ext = false) {
		$this->path = $filePath;
		$this->fileName = $fileName;
		$this->ext = $ext;
	}
	function open() {return true;}
	function close() {return true;}
	function add($srcPath, $removePath = false) {
		/*
		 * if it returns false it needs to set $this->error
		 */
	}
	function extract($targetPath) {
		$this->error = "unimplemented";
		/*
		 * if it returns false it needs to set $this->error
		 */
	}
	function getTOC() {
		$this->error = "unimplemented";
		/*
		 * should return the list of files with the following elements:
		            "checksum"
					"filename"
					"path"
					"filesize"
					"type" (folder|file)
		 * should also set $this->itemsCount
		 * */
	}
	function addDir($filePath, $relativePath = false) {}
	function addFile($filePath, $relativePath = false) {}
	function save() {}
}