Example #1
0
 /**
  * Creates a .zip file of the theme in themes/ directory
  *
  * @access  public
  * @param   string  $theme      Name of the theme
  * @param   string  $srcDir     Source directory
  * @param   string  $destDir    Target directory
  * @param   bool    $copy_example_to_repository  If copy example.png too or not
  * @return  bool    Returns true if:
  *                    - Theme exists
  *                    - Theme exists and could be packed
  *                  Returns false if:
  *                    - Theme doesn't exist
  *                    - Theme doesn't exists and couldn't be packed
  */
 function packTheme($theme, $srcDir, $destDir, $copy_example_to_repository = true)
 {
     $themeSrc = $srcDir . '/' . $theme;
     if (!is_dir($themeSrc)) {
         return new Jaws_Error(_t('TMS_ERROR_THEME_DOES_NOT_EXISTS', $theme));
     }
     if (!Jaws_Utils::is_writable($destDir)) {
         return new Jaws_Error(_t('GLOBAL_ERROR_FAILED_DIRECTORY_UNWRITABLE', $destDir), $this->gadget->name);
     }
     $themeDest = $destDir . '/' . $theme . '.zip';
     //If file exists.. delete it
     if (file_exists($themeDest)) {
         @unlink($themeDest);
     }
     require_once PEAR_PATH . 'File/Archive.php';
     $reader = File_Archive::read($themeSrc, $theme);
     $innerWriter = File_Archive::toFiles();
     $writer = File_Archive::toArchive($themeDest, $innerWriter);
     $res = File_Archive::extract($reader, $writer);
     if (PEAR::isError($res)) {
         return new Jaws_Error(_t('TMS_ERROR_COULD_NOT_PACK_THEME'));
     }
     Jaws_Utils::chmod($themeDest);
     if ($copy_example_to_repository) {
         //Copy image to repository/images
         if (file_exists($srcDir . '/example.png')) {
             @copy($srcDir . '/example.png', JAWS_DATA . "themes/repository/Resources/images/{$theme}.png");
             Jaws_Utils::chmod(JAWS_DATA . 'themes/repository/Resources/images/' . $theme . '.png');
         }
     }
     return $themeDest;
 }
Example #2
0
 /**
  * @see File_Archive_Reader::next()
  */
 function next()
 {
     if (!parent::next()) {
         return false;
     }
     $this->nbRead++;
     $this->filePos = 0;
     if ($this->nbRead > 1) {
         return false;
     }
     $dataFilename = $this->source->getDataFilename();
     if ($dataFilename !== null) {
         $this->tmpName = null;
         $this->gzfile = gzopen($dataFilename, 'r');
     } else {
         $this->tmpName = tempnam(File_Archive::getOption('tmpDirectory'), 'far');
         //Generate the tmp data
         $dest = new File_Archive_Writer_Files();
         $dest->newFile($this->tmpName);
         $this->source->sendData($dest);
         $dest->close();
         $this->gzfile = gzopen($this->tmpName, 'r');
     }
     return true;
 }
Example #3
0
 /**
  * @see File_Archive_Reader::next()
  */
 function next()
 {
     if (!parent::next()) {
         return false;
     }
     $this->nbRead++;
     if ($this->nbRead > 1) {
         return false;
     }
     $dataFilename = $this->source->getDataFilename();
     if ($dataFilename !== null) {
         $this->tmpName = null;
         $this->bzfile = @bzopen($dataFilename, 'r');
         if ($this->bzfile === false) {
             return PEAR::raiseError("bzopen failed to open {$dataFilename}");
         }
     } else {
         $this->tmpName = tempnam(File_Archive::getOption('tmpDirectory'), 'far');
         //Generate the tmp data
         $dest = new File_Archive_Writer_Files();
         $dest->newFile($this->tmpName);
         $this->source->sendData($dest);
         $dest->close();
         $this->bzfile = bzopen($this->tmpName, 'r');
     }
     return true;
 }
Example #4
0
 /**
  * Returns downloadable backup file
  *
  * @access  public
  * @return void
  */
 function Backup()
 {
     $this->gadget->CheckPermission('Backup');
     $tmpDir = sys_get_temp_dir();
     $domain = preg_replace("/^(www.)|(:{$_SERVER['SERVER_PORT']})\$|[^a-z0-9\\-\\.]/", '', strtolower($_SERVER['HTTP_HOST']));
     $nameArchive = $domain . '-' . date('Y-m-d') . '.tar.gz';
     $pathArchive = $tmpDir . DIRECTORY_SEPARATOR . $nameArchive;
     //Dump database data
     $dbFileName = 'dbdump.xml';
     $dbFilePath = $tmpDir . DIRECTORY_SEPARATOR . $dbFileName;
     Jaws_DB::getInstance()->Dump($dbFilePath);
     $files = array();
     require_once PEAR_PATH . 'File/Archive.php';
     $files[] = File_Archive::read(JAWS_DATA);
     $files[] = File_Archive::read($dbFilePath, $dbFileName);
     File_Archive::extract($files, File_Archive::toArchive($pathArchive, File_Archive::toFiles()));
     Jaws_Utils::Delete($dbFilePath);
     // browser must download file from server instead of cache
     header("Expires: 0");
     header("Pragma: public");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     // force download dialog
     header("Content-Type: application/force-download");
     // set data type, size and filename
     header("Content-Disposition: attachment; filename=\"{$nameArchive}\"");
     header("Content-Transfer-Encoding: binary");
     header('Content-Length: ' . @filesize($pathArchive));
     @readfile($pathArchive);
     Jaws_Utils::Delete($pathArchive);
 }
Example #5
0
 function exportUploadedFiles($gid)
 {
     require_once "File/Archive.php";
     File_Archive::setOption('zipCompressionLevel', 0);
     $baseDir = CUSTOMER_IMAGE_DIR . $gid;
     $files = list_files_dir($baseDir);
     File_Archive::extract($files, File_Archive::toArchive("campaign_" . $gid . "_uploadedfiles_" . date('dFY') . ".zip", File_Archive::toOutput()));
 }
Example #6
0
 /**
  * @see File_Archive_Writer::newFile()
  *
  * Check that one single file is written in the GZip archive
  */
 function newFile($filename, $stat = array(), $mime = "application/octet-stream")
 {
     if ($this->nbFiles > 1) {
         return PEAR::raiseError("A Gz archive can only contain one single file." . "Use Tgz archive to be able to write several files");
     }
     $this->nbFiles++;
     $this->tmpName = tempnam(File_Archive::getOption('tmpDirectory'), 'far');
     $this->gzfile = gzopen($this->tmpName, 'w' . $this->compressionLevel);
     return true;
 }
 /**
  * validate実行
  *
  * @param   mixed   $attributes チェックする値
  * @param   string  $errStr     エラー文字列
  * @param   array   $params     オプション引数
  * @return  string  エラー文字列(エラーの場合)
  * @access  public
  */
 function validate($attributes, $errStr, $params)
 {
     $this->_cabinet = $attributes["cabinet"];
     $file = $attributes["file"];
     $container =& DIContainerFactory::getContainer();
     $commonMain =& $container->getComponent("commonMain");
     $this->_fileAction =& $commonMain->registerClass(WEBAPP_DIR . '/components/file/Action.class.php', "File_Action", "fileAction");
     $this->_fileView =& $commonMain->registerClass(WEBAPP_DIR . '/components/file/View.class.php', "File_View", "fileView");
     $this->_uploadsView =& $container->getComponent("uploadsView");
     $file_path = "cabinet/" . strtolower(session_id()) . timezone_date();
     if (file_exists(FILEUPLOADS_DIR . $file_path)) {
         $result = $this->_fileAction->delDir(FILEUPLOADS_DIR . $file_path);
         if ($result === false) {
             return $errStr;
         }
     }
     mkdir(FILEUPLOADS_DIR . $file_path, octdec(_UPLOAD_FOLDER_MODE));
     $request =& $container->getComponent("Request");
     $request->setParameter("file_path", $file_path);
     $result = $this->_uploadsView->getUploadById($file["upload_id"]);
     if ($result === false) {
         return $errStr;
     }
     $upload = $result[0];
     File_Archive::extract(File_Archive::read(FILEUPLOADS_DIR . $upload["file_path"] . $upload["physical_file_name"] . "/"), $dest = FILEUPLOADS_DIR . $file_path);
     $configView =& $container->getComponent("configView");
     $config = $configView->getConfigByConfname(_SYS_CONF_MODID, "allow_extension");
     if (!isset($config["conf_value"])) {
         return $errStr;
     }
     $this->_allow_extension = $config["conf_value"];
     $cabinetView =& $container->getComponent("cabinetView");
     $used_size = $cabinetView->getUsedSize();
     if ($used_size === false) {
         return $errStr;
     }
     $total_size = $used_size;
     $result = $this->_check(FILEUPLOADS_DIR . $file_path, $total_size);
     if ($result !== true) {
         $this->_fileAction->delDir(FILEUPLOADS_DIR . $file_path);
         return $result;
     }
     $decompress_size = $this->_fileView->getSize(FILEUPLOADS_DIR . $file_path);
     if ($this->_cabinet["cabinet_max_size"] != 0 && $this->_cabinet["cabinet_max_size"] < $used_size + $decompress_size) {
         $this->_fileAction->delDir(FILEUPLOADS_DIR . $file_path);
         $suffix_compresssize = $this->_fileView->formatSize($used_size + $decompress_size);
         $suffix_maxsize = $this->_fileView->formatSize($this->_cabinet["cabinet_max_size"]);
         return sprintf(CABINET_ERROR_DECOMPRESS_MAX_SIZE, $suffix_compresssize, $suffix_maxsize);
     }
     $result = $cabinetView->checkCapacitySize($decompress_size);
     if ($result !== true) {
         $this->_fileAction->delDir(FILEUPLOADS_DIR . $file_path);
         return $result;
     }
 }
Example #8
0
 function saveChanges()
 {
     global $CONFIG;
     $_REQUEST->setType('uncompress', 'any');
     if (isset($_FILES['uFiles']) && $this->may($USER, EDIT)) {
         $u = false;
         $ue = false;
         $extensions = $CONFIG->Files->filter;
         foreach ($_FILES['uFiles']['error'] as $i => $e) {
             $parts = explode('.', $_FILES['uFiles']['name'][$i]);
             $extension = array_pop($parts);
             if ($e == UPLOAD_ERR_NO_FILE) {
                 continue;
             }
             $newPath = $this->that->path . '/' . $_FILES['uFiles']['name'][$i];
             if ($e == UPLOAD_ERR_OK) {
                 if ($_REQUEST['uncompress'] && in_array(strtolower(strrchr($_FILES['uFiles']['name'][$i], '.')), array('.tar', '.gz', '.tgz', '.bz2', '.tbz', '.zip', '.ar', '.deb'))) {
                     $tmpfile = $_FILES['uFiles']['tmp_name'][$i] . $_FILES['uFiles']['name'][$i];
                     rename($_FILES['uFiles']['tmp_name'][$i], $tmpfile);
                     $u = true;
                     require_once "File/Archive.php";
                     error_reporting(E_ALL);
                     $curdir = getcwd();
                     chdir($this->path);
                     //FIXME: FIXME!
                     if (@File_Archive::extract(File_Archive::filter(File_Archive::predExtension($extensions), File_Archive::read($tmpfile . '/*')), File_Archive::toFiles()) == null) {
                         $ue = true;
                     } else {
                         Flash::queue(__('Extraction failed'));
                     }
                     chdir($curdir);
                 } elseif (!in_array(strtolower($extension), $extensions)) {
                     Flash::queue(__('Invalid format:') . ' ' . $_FILES['uFiles']['name'][$i], 'warning');
                     continue;
                 } else {
                     $u = (bool) @move_uploaded_file($_FILES['uFiles']['tmp_name'][$i], $newPath);
                 }
             }
             if (!$u) {
                 Flash::queue(__('Upload of file') . ' "' . $_FILES['uFiles']['name'][$i] . '" ' . __('failed') . ' (' . ($e ? $e : __('Check permissions')) . ')', 'warning');
             }
         }
         if ($u) {
             $this->loadStructure(true);
             Flash::queue(__('Your file(s) were uploaded'));
             return true;
         }
         if ($ue) {
             $this->loadStructure(true);
             Flash::queue(__('Your file(s) were uploaded and extracted'));
             return true;
         }
         return false;
     }
 }
Example #9
0
 /**
  * Check if input (an array of $_FILES) are .tar or .zip files, if they
  * are then these get unpacked and returns an managed as $_FILES (returning
  * an array with the same structure $_FILES uses and move pics to /tmp)
  *
  * @access  public
  * @param   array   $files   $_FILES
  * @return  array   $_FILES format
  */
 function UnpackFiles($files)
 {
     if (!is_array($files)) {
         return array();
     }
     $cleanFiles = array();
     $tmpDir = sys_get_temp_dir();
     $counter = 1;
     require_once PEAR_PATH . 'File/Archive.php';
     foreach ($files as $key => $file) {
         if (empty($file['tmp_name'])) {
             continue;
         }
         $ext = strrchr($file['name'], '.');
         switch ($ext) {
             case '.gz':
                 $ext = '.tgz';
                 break;
             case '.bz2':
             case '.bzip2':
                 $ext = '.tbz';
                 break;
         }
         $ext = strtolower(ltrim($ext, '.'));
         if (File_Archive::isKnownExtension($ext)) {
             $tmpArchiveName = $tmpDir . DIRECTORY_SEPARATOR . $file['name'];
             if (!move_uploaded_file($file['tmp_name'], $tmpArchiveName)) {
                 continue;
             }
             $reader = File_Archive::read($tmpArchiveName);
             $source = File_Archive::readArchive($ext, $reader);
             if (!PEAR::isError($source)) {
                 while ($source->next()) {
                     $destFile = $tmpDir . DIRECTORY_SEPARATOR . basename($source->getFilename());
                     $sourceFile = $tmpArchiveName . '/' . $source->getFilename();
                     $extract = File_Archive::extract($sourceFile, $tmpDir);
                     if (PEAR::IsError($extract)) {
                         continue;
                     }
                     $cleanFiles['photo' . $counter] = array('name' => basename($source->getFilename()), 'type' => $source->getMime(), 'tmp_name' => $destFile, 'size' => @filesize($destFile), 'error' => 0);
                     $counter++;
                 }
             }
         } else {
             $cleanFiles['photo' . $counter] = $file;
             $counter++;
         }
     }
     return $cleanFiles;
 }
Example #10
0
 /**
  * Export language
  *
  * @access  public
  * @return  void
  */
 function Export()
 {
     $lang = jaws()->request->fetch('lang', 'get');
     require_once PEAR_PATH . 'File/Archive.php';
     $tmpDir = sys_get_temp_dir();
     $tmpFileName = "{$lang}.tar";
     $tmpArchiveName = $tmpDir . DIRECTORY_SEPARATOR . $tmpFileName;
     $writerObj = File_Archive::toFiles();
     $src = File_Archive::read(JAWS_DATA . "languages/{$lang}", $lang);
     $dst = File_Archive::toArchive($tmpArchiveName, $writerObj);
     $res = File_Archive::extract($src, $dst);
     if (!PEAR::isError($res)) {
         return Jaws_Utils::Download($tmpArchiveName, $tmpFileName);
     }
     Jaws_Header::Referrer();
 }
Example #11
0
    /**
     * ダウンロードメイン表示クラス
     *
     * @access  public
     */
    function execute()
    {
        $header = <<<EOD
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>NetCommons</title>
</head>
<body>

EOD;
        $footer = <<<EOD
</body>
</html>
EOD;
        require_once "File/Archive.php";
        $dest = File_Archive::toArchive("document.zip", File_Archive::toOutput());
        $dest->newFile("document.html");
        $download_url = "?action=" . $this->download_action . "&upload_id=";
        $count = substr_count($this->content, $download_url);
        if (!$count) {
            $dest->writeData($header . $this->content . $footer);
            $dest->close();
            exit;
        }
        $upload_id = array();
        $files = array();
        $trans = array();
        $parts = explode($download_url, $this->content);
        for ($i = 1; $i <= $count; $i++) {
            $id = substr($parts[$i], 0, strpos($parts[$i], '"'));
            if (!isset($upload_id[$id])) {
                $upload_id[$id] = true;
                list($pathname, $filename, $physical_file_name, $space_type) = $this->uploadsView->downloadCheck($id, null, 0, "common_download_main");
                if ($pathname != null) {
                    $files[] = $pathname . $physical_file_name;
                    $trans[BASE_URL . '/' . $download_url . $id] = "./" . $physical_file_name;
                    $trans[$download_url . $id] = $physical_file_name;
                }
            }
        }
        clearstatcache();
        $dest->writeData($header . strtr($this->content, $trans) . $footer);
        File_Archive::extract($files, $dest);
    }
 /**
  * _unzipFile
  *
  * @return	bool
  **/
 public function _unzipFile()
 {
     // local file name
     $downloadDirPath = realpath($this->Xupdate->params['temp_path']);
     $downloadFilePath = $this->Xupdate->params['temp_path'] . '/' . $this->target_key . '.zip';
     $exploredDirPath = realpath($downloadDirPath . '/' . $this->target_key);
     if (empty($downloadFilePath)) {
         $this->_set_error_log('getDownloadFilePath not found error in: ' . $this->_getDownloadFilePath());
         return false;
     }
     if (!chdir($exploredDirPath)) {
         $this->_set_error_log('chdir error in: ' . $exploredDirPath);
         return false;
         //chdir error
     }
     File_Archive::extract(File_Archive::read($downloadFilePath . '/'), File_Archive::appender($exploredDirPath));
     return true;
 }
Example #13
0
 /**
  * Extract archive Files
  *
  * @access  public
  * @param   array   $files        $_FILES array
  * @param   string  $dest         Destination directory(include end directory separator)
  * @param   bool    $extractToDir Create separate directory for extracted files
  * @param   bool    $overwrite    Overwrite directory if exist
  * @param   int     $max_size     Max size of file
  * @return  bool    Returns TRUE on success or FALSE on failure
  */
 static function ExtractFiles($files, $dest, $extractToDir = true, $overwrite = true, $max_size = null)
 {
     if (empty($files) || !is_array($files)) {
         return new Jaws_Error(_t('GLOBAL_ERROR_UPLOAD'), __FUNCTION__);
     }
     if (isset($files['name'])) {
         $files = array($files);
     }
     require_once PEAR_PATH . 'File/Archive.php';
     foreach ($files as $key => $file) {
         if (isset($file['error']) && !empty($file['error']) || !isset($file['name'])) {
             return new Jaws_Error(_t('GLOBAL_ERROR_UPLOAD_' . $file['error']), __FUNCTION__);
         }
         if (empty($file['tmp_name'])) {
             continue;
         }
         $ext = strrchr($file['name'], '.');
         $filename = substr($file['name'], 0, -strlen($ext));
         if (false !== stristr($filename, '.tar')) {
             $filename = substr($filename, 0, strrpos($filename, '.'));
             switch ($ext) {
                 case '.gz':
                     $ext = '.tgz';
                     break;
                 case '.bz2':
                 case '.bzip2':
                     $ext = '.tbz';
                     break;
                 default:
                     $ext = '.tar' . $ext;
             }
         }
         $ext = strtolower(substr($ext, 1));
         if (!File_Archive::isKnownExtension($ext)) {
             return new Jaws_Error(_t('GLOBAL_ERROR_UPLOAD_INVALID_FORMAT', $file['name']), __FUNCTION__);
         }
         if ($extractToDir) {
             $dest = $dest . $filename;
         }
         if ($extractToDir && !Jaws_Utils::mkdir($dest)) {
             return new Jaws_Error(_t('GLOBAL_ERROR_FAILED_CREATING_DIR', $dest), __FUNCTION__);
         }
         if (!Jaws_Utils::is_writable($dest)) {
             return new Jaws_Error(_t('GLOBAL_ERROR_FAILED_DIRECTORY_UNWRITABLE', $dest), __FUNCTION__);
         }
         $archive = File_Archive::readArchive($ext, $file['tmp_name']);
         if (PEAR::isError($archive)) {
             return new Jaws_Error($archive->getMessage(), __FUNCTION__);
         }
         $writer = File_Archive::_convertToWriter($dest);
         $result = $archive->extract($writer);
         if (PEAR::isError($result)) {
             return new Jaws_Error($result->getMessage(), __FUNCTION__);
         }
         //@unlink($file['tmp_name']);
     }
     return true;
 }
 function init()
 {
     $oKTConfig =& KTConfig::getSingleton();
     $sBasedir = $oKTConfig->get("urls/tmpDirectory");
     $sTmpPath = tempnam($sBasedir, 'archiveimportstorage');
     if ($sTmpPath === false) {
         return PEAR::raiseError(_kt("Could not create temporary directory for archive storage"));
     }
     if (!file_exists($this->sZipPath)) {
         return PEAR::raiseError(_kt("Archive file given does not exist"));
     }
     unlink($sTmpPath);
     mkdir($sTmpPath, 0700);
     $this->sBasePath = $sTmpPath;
     // Set environment language to output character encoding
     $sOutputEncoding = $oKTConfig->get('export/encoding', 'UTF-8');
     $loc = $sOutputEncoding;
     putenv("LANG={$loc}");
     putenv("LANGUAGE={$loc}");
     $loc = setlocale(LC_ALL, $loc);
     // File Archive doesn't unzip properly so sticking to the original unzip functionality
     if ($this->sExtension == 'zip') {
         // ** Original zip functionality
         $sUnzipCommand = KTUtil::findCommand("import/unzip", "unzip");
         if (empty($sUnzipCommand)) {
             return PEAR::raiseError(_kt("unzip command not found on system"));
         }
         $aArgs = array($sUnzipCommand, "-q", "-n", "-d", $sTmpPath, $this->sZipPath);
         $aRes = KTUtil::pexec($aArgs);
         if ($aRes['ret'] !== 0) {
             return PEAR::raiseError(_kt("Could not retrieve contents from zip storage"));
         }
     } else {
         File_Archive::extract(File_Archive::readArchive($this->sExtension, File_Archive::readUploadedFile('file')), $dst = $sTmpPath);
     }
 }
Example #15
0
 function appendFile($filename, $dataFilename)
 {
     //Try to read from the cache
     $cache = File_Archive::getOption('cache', null);
     if ($cache !== null && $this->compressionLevel > 0) {
         $id = realpath($dataFilename);
         $id = urlencode($id);
         $id = str_replace('_', '%5F', $id);
         $group = 'FileArchiveZip' . $this->compressionLevel;
         $mtime = filemtime($dataFilename);
         //Tries to read from cache
         if (($data = $cache->get($id, $group)) !== false) {
             $info = unpack('Vmtime/Vcrc/Vnlength', substr($data, 0, 12));
             $data = substr($data, 12);
         }
         //If cache failed or file modified since then
         if ($data === false || $info['mtime'] != $mtime) {
             $data = file_get_contents($dataFilename);
             $info = array('crc' => crc32($data), 'nlength' => strlen($data), 'mtime' => $mtime);
             $data = gzcompress($data, $this->compressionLevel);
             $data = substr($data, 2, strlen($data) - 6);
             $data = pack('VVV', $info['mtime'], $info['crc'], $info['nlength']) . $data;
             $cache->save($data, $id, $group);
         }
         return $this->appendCompressedData($filename, stat($dataFilename), $data, $info['crc'], $info['nlength']);
     }
     //If no cache system, use the standard way
     return parent::appendFile($filename, $dataFilename);
 }
Example #16
0
 /**
  * Remove duplicates from the archive specified in the URL
  */
 function removeDuplicates($URL)
 {
     $source = null;
     return File_Archive::removeDuplicatesFromSource($source, $URL);
 }
Example #17
0
 /**
  * Ensure data has been extracted to $this->entryTmpName
  */
 function ensureDataExtracted()
 {
     if ($this->fileReader !== null) {
         return;
     }
     if ($this->entryTmpName === null) {
         $this->entryTmpName = tempnam(File_Archive::getOption('tmpDirectory'), 'far');
     }
     $this->rarEntry->extract(false, $this->entryTmpName);
     $this->fileReader = new File_Archive_Reader_File($this->entryTmpName, $this->rarEntry->getName());
 }
Example #18
0
 /**
  * Sends the current file to the Writer $writer
  * The data will be sent by chunks of at most $bufferSize bytes
  * If $bufferSize <= 0 (default), the blockSize option is used
  */
 function sendData(&$writer, $bufferSize = 0)
 {
     if (PEAR::isError($writer)) {
         return $writer;
     }
     if ($bufferSize <= 0) {
         $bufferSize = File_Archive::getOption('blockSize');
     }
     $filename = $this->getDataFilename();
     if ($filename !== null) {
         $error = $writer->writeFile($filename);
         if (PEAR::isError($error)) {
             return $error;
         }
     } else {
         while (($data = $this->getData($bufferSize)) !== null) {
             if (PEAR::isError($data)) {
                 return $data;
             }
             $error = $writer->writeData($data);
             if (PEAR::isError($error)) {
                 return $error;
             }
         }
     }
 }
<?php

/**
* FIXME ... just fixme, like 99% of it. Count this as a draft or something. 
* 
*  
* 
* @package test
*
* Trying out File_Archive
*/
require_once '../../autoload.php';
try {
    Module::require('File_Archive');
} catch (Exception $e) {
    die('Script requires PEAR File_Archive to work.');
}
// Set cache dir for Cache Lite
$options = array('cacheDir' => 'tmp');
if (Module::isLoaded('Cache_Lite')) {
    File_Archive::setOption('cache', new Cache_Lite($options));
}
File_Archive::setOption('zipCompressionLevel', 0);
// $files is an array of path to the files that must be added to the archive
File_Archive::extract($files, File_Archive::toArchive('myFiles.zip', File_Archive::toOutput()));
Example #20
0
 /**
  * handle export
  */
 private function handleExportGet()
 {
     $request = Request::getInstance();
     if (!$request->exists('id')) {
         throw new Exception('Thema ontbreekt.');
     }
     $id = intval($request->getValue('id'));
     $key = array('id' => $id);
     $themedetail = $this->getDetail($key);
     $theme = $this->director->themeManager->getThemeFromId($key);
     $tempPath = $this->director->getTempPath() . "/theme" . session_id();
     $themePath = $themedetail['themePath'];
     $configPath = $theme->getConfigFile();
     mkdir($tempPath);
     Utils::copyRecursive($themePath, $tempPath);
     copy($configPath, $tempPath . "/" . basename($configPath));
     copy($themePath . "/script/ThemeInstaller.php", $tempPath . "/ThemeInstaller.php");
     $filename = sprintf("dif_%s_%s.tar.gz", strtolower($themedetail['classname']), $theme->getVersion());
     File_Archive::extract($tempPath, File_Archive::toArchive($filename, File_Archive::toOutput()));
     Utils::removeRecursive($tempPath);
     exit;
     /*
     $view = ViewManager::getInstance();
     
     $url = new Url(true);
     $url_back = clone $url;
     $url_back->setParameter($view->getUrlId(), ViewManager::ADMIN_OVERVIEW);
     $template->setVariable('href_back',  $url_back->getUrl(true), false);
     
     $theme->addBreadcrumb(array('name' => $themedetail['name'], 'path' => $url_back->getUrl(true)));
     $theme->addBreadcrumb(array('name' => $view->getName(), 'path' => $url->getUrl(true)));
     
     $this->template[$this->director->theme->getExport()->main_tag] = $template;
     */
 }
Example #21
0
 function _testRemove($extension)
 {
     $writer = File_Archive::toArchive("test.{$extension}", File_Archive::toVariable($x));
     $writer->newFile('foo.txt');
     $writer->writeData('ABCDEF');
     $writer->newFile('bla_to_remove.txt');
     $writer->writeData('GHIJKL');
     $writer->newFile('bar.txt');
     $writer->writeData('MNOP');
     $writer->close();
     File_Archive::removeFromSource(File_Archive::predEreg('_to_remove'), $source = File_Archive::readSource(File_Archive::readMemory($x, "test.{$extension}"), "test.{$extension}/"));
     $this->assertEquals("foo.txt\nbar.txt", implode("\n", $source->getFileList()));
 }
Example #22
0
	function ZipFileRead($zip_file,$dtype) {
		$datas=array();
		$line=0;

		//ライブラリ
		set_include_path(get_include_path() .PATH_SEPARATOR. DIR_ARCH_LIB);
		require_once "File/Archive.php";

		//圧縮ファイル読み込み
		$arr=array();
		$source = File_Archive::read( "$zip_file/" );
		while( true ){
			$w=CommonComponent::ZipFileReadBuffer($source);
			if ( $w == "" ){ break; }
			if ( $dtype == "csv" ){
				$w=mb_convert_encoding(rtrim($w),"UTF-8","SJIS-WIN");
			}else{
				$w=rtrim($w);
			}
			$datas[]=array("data"=>$w);
			$line++;
			if ( $line >= RESULT_LINE_MAX ){ break; }
		}
		$source->close();

		return $datas;
	}
 function _decompression($name, &$fileUpload)
 {
     $container =& DIContainerFactory::getContainer();
     $actionChain =& $container->getComponent("ActionChain");
     $session =& $container->getComponent("Session");
     $file_extra =& $container->getComponent("File");
     $commonMain =& $container->getComponent("commonMain");
     $fileAction =& $commonMain->registerClass(WEBAPP_DIR . '/components/file/Action.class.php', "File_Action", "fileAction");
     $action_name = $actionChain->getCurActionName();
     $pathList = explode("_", $action_name);
     $cur_sess_id = $session->getID();
     require_once "File/Archive.php";
     //
     // テンポラリーディレクトリ作成
     //
     if (!file_exists(FILEUPLOADS_DIR . $pathList[0])) {
         mkdir(FILEUPLOADS_DIR . $pathList[0], octdec(_UPLOAD_FOLDER_MODE));
     }
     $file_path = $pathList[0] . "/" . strtolower($cur_sess_id);
     if (file_exists(FILEUPLOADS_DIR . $file_path)) {
         $result = $fileAction->delDir(FILEUPLOADS_DIR . $file_path);
         if ($result === false) {
             return false;
         }
     }
     mkdir(FILEUPLOADS_DIR . $file_path, octdec(_UPLOAD_FOLDER_MODE));
     //
     // 圧縮ファイル取得
     //
     $files = $file_extra->getParameterRef($name);
     $file_name = FILEUPLOADS_DIR . $file_path . "/" . $files['name'];
     //
     // TODO:cabinetの場合、圧縮ファイルをFileクラスに登録したものを解凍しないといけないため
     // $fileUpload->moveで移動してしまうとエラーとなる。
     //
     $fileUpload->move(0, $file_name);
     //
     // 圧縮ファイル解凍
     //
     File_Archive::extract(File_Archive::read($file_name . "/"), $dest = FILEUPLOADS_DIR . $file_path);
     //
     // 圧縮ファイル削除
     //
     $fileAction->delDir($file_name);
     //
     // 解凍したファイルをアップロードファイルとしてセット
     //
     $commonMain =& $container->getComponent("commonMain");
     $uploadsAction =& $commonMain->registerClass(WEBAPP_DIR . '/components/uploads/Action.class.php', "Uploads_Action", "uploadsAction");
     $uploadsAction->setFileByPath(FILEUPLOADS_DIR . $file_path, $name);
 }
Example #24
0
 /**
  * @see File_Archive_Reader::getData()
  */
 function getData($length = -1)
 {
     $error = $this->_ensureFileOpened();
     if (PEAR::isError($error)) {
         return $error;
     }
     if (feof($this->handle)) {
         return null;
     }
     if ($length == -1) {
         $contents = '';
         $blockSize = File_Archive::getOption('blockSize');
         while (!feof($this->handle)) {
             $contents .= fread($this->handle, $blockSize);
         }
         return $contents;
     } else {
         if ($length == 0) {
             return "";
         } else {
             return fread($this->handle, $length);
         }
     }
 }
Example #25
0
 /**
  * Attempt to change the current source (if the current file is an archive)
  * If this is the case, push the current source onto the stack and make the
  * good archive reader the current source. A file is considered as an
  * archive if its extension is one of tar, gz, zip, tgz
  *
  * @return bool whether the source has been pushed or not
  * @access private
  */
 function push()
 {
     if ($this->uncompressionLevel >= 0 && $this->baseDirCompressionLevel !== null && count($this->readers) >= $this->uncompressionLevel) {
         return false;
     }
     // Check the extension of the file (maybe we need to uncompress it?)
     $filename = $this->source->getFilename();
     $extensions = explode('.', strtolower($filename));
     $reader =& $this->source;
     $nbUncompressions = 0;
     while (($extension = array_pop($extensions)) !== null) {
         $nbUncompressions++;
         unset($next);
         $next = File_Archive::readArchive($extension, $reader, $nbUncompressions == 1);
         if ($next === false) {
             $extensions = array();
         } else {
             unset($reader);
             $reader =& $next;
         }
     }
     if ($nbUncompressions == 1) {
         return false;
     } else {
         $this->readers[count($this->readers)] =& $this->source;
         unset($this->source);
         $this->source = new File_Archive_Reader_AddBaseName($filename, $reader);
         return true;
     }
 }
Example #26
0
function zip_it($source, $destination)
{
    $source = realpath($source);
    if (is_readable($source) === true) {
        if (extension_loaded('zip') === true) {
            $zip = new ZipArchive();
            if ($zip->open($destination, ZIPARCHIVE::CREATE) === true) {
                $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
                // Iterate through files & directories and add to archive object
                foreach ($files as $file) {
                    if (is_dir($file) === true) {
                        $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                    } else {
                        if (is_file($file) === true) {
                            $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                        }
                    }
                }
            } else {
                echo "Couldn't create zip file<br />";
            }
            return $zip->close();
        } else {
            $original_dir = getcwd();
            chdir($source);
            File_Archive::extract(File_Archive::read('.'), File_Archive::toArchive($destination, File_Archive::toFiles(), 'zip'));
            chdir($original_dir);
            // TODO: add filesize check?
            if (is_readable($destination)) {
                return true;
            }
        }
    } else {
        echo "Source content does not exist or is not readable<br />";
    }
    return false;
}
Example #27
0
 /**
  * Export Logs
  *
  * @access  public
  * @return  void
  */
 function ExportLogs()
 {
     $this->gadget->CheckPermission('ExportLogs');
     $filters = jaws()->request->fetch(array('from_date', 'to_date', 'gname', 'user', 'priority', 'status'), 'get');
     $filters['gadget'] = $filters['gname'];
     unset($filters['gname']);
     $model = $this->gadget->model->load('Logs');
     $logs = $model->GetLogs($filters);
     if (Jaws_Error::IsError($logs) || count($logs) < 1) {
         return;
     }
     $tmpDir = sys_get_temp_dir();
     $tmpCSVFileName = uniqid(rand(), true) . '.csv';
     $fp = fopen($tmpDir . DIRECTORY_SEPARATOR . $tmpCSVFileName, 'w');
     $date = Jaws_Date::getInstance();
     foreach ($logs as $log) {
         $exportData = '';
         $exportData .= $log['id'] . ',';
         $exportData .= $log['username'] . ',';
         $exportData .= $log['gadget'] . ',';
         $exportData .= $log['action'] . ',';
         $exportData .= $log['priority'] . ',';
         $exportData .= $log['apptype'] . ',';
         $exportData .= $log['backend'] . ',';
         $exportData .= long2ip($log['ip']) . ',';
         $exportData .= $log['status'] . ',';
         $exportData .= $date->Format($log['insert_time'], 'Y-m-d H:i:s');
         $exportData .= PHP_EOL;
         fwrite($fp, $exportData);
     }
     fclose($fp);
     require_once PEAR_PATH . 'File/Archive.php';
     $tmpFileName = uniqid(rand(), true) . '.tar.gz';
     $tmpArchiveName = $tmpDir . DIRECTORY_SEPARATOR . $tmpFileName;
     $writerObj = File_Archive::toFiles();
     $src = File_Archive::read($tmpDir . DIRECTORY_SEPARATOR . $tmpCSVFileName);
     $dst = File_Archive::toArchive($tmpArchiveName, $writerObj);
     $res = File_Archive::extract($src, $dst);
     if (!PEAR::isError($res)) {
         return Jaws_Utils::Download($tmpArchiveName, $tmpFileName);
     }
     Jaws_Header::Referrer();
 }
Example #28
0
	}
	if ( $file_cnt >= OUTPUT_FILE_LIMIT ){
		WriteFinFile($fin_file,"WAR:file size limit over\n");
		break;
	}
	$file_size += $row_len;
	$zip_file=sprintf("%s/%s/%s_%03d.zip",DIR_RESULT,$hive_uid,$hive_id,$file_cnt);
	$zip_file_in=sprintf("%s_%03d.csv",$hive_id,$file_cnt);

	//出力ファイルのオープン
	if ( $sv_zip_file != $zip_file ){
		if ( $sv_zip_file != "" ){
			WriteFinFile($fin_file,"OUT:$sv_zip_file\n");
			$ofp->close();
		}
		$ofp = File_Archive::toArchive($zip_file, File_Archive::toFiles(),"zip");
		$ofp->newFile($zip_file_in);
	}
	$sv_zip_file=$zip_file;

	//出力
	$row=mb_convert_encoding($row,"SJIS-WIN","UTF-8");
	$ofp->writeData($row);
}
pclose($ifp);

if ( $sv_zip_file != "" ){
	WriteFinFile($fin_file,"OUT:$sv_zip_file\n");
	$ofp->close();
}
Example #29
0
 /**
  * @see File_Archive_Reader::getData()
  */
 function getData($length = -1)
 {
     if ($this->fromSource) {
         $data = $this->source->getData($length);
         if (PEAR::isError($data)) {
             return $data;
         }
         fwrite($this->tmpFile, $data);
         return $data;
     } else {
         if ($length == 0) {
             return '';
         }
         if ($length > 0 && $this->pos + 1 < count($this->files)) {
             $maxSize = $this->files[$this->pos + 1]['pos'] - ftell($this->tmpFile);
             if ($maxSize == 0) {
                 return null;
             }
             if ($length > $maxSize) {
                 $length = $maxSize;
             }
             return fread($this->tmpFile, $length);
         } else {
             $contents = '';
             $blockSize = File_Archive::getOption('blockSize');
             while (!feof($this->tmpFile)) {
                 $contents .= fread($this->tmpFile, $blockSize);
             }
             return $contents == '' ? null : $contents;
         }
     }
 }
Example #30
0
 /**
  * Execute action when called for explicitly by the user
  *
  * This function also contains the actions available in the interface provided, including file
  * uploading, compressed file extraction and the creation of folders.
  * @return void
  */
 function run()
 {
     global $Templates, $USER, $Controller, $ID, $CONFIG;
     /**
      * User input types
      */
     $_REQUEST->setType('action', 'string');
     $_REQUEST->setType('popup', 'string');
     $_REQUEST->setType('filter', 'string');
     if (!$this->may($USER, READ)) {
         errorPage(401);
     } else {
         if (!in_array($CMPRExtension = $CONFIG->files->compression_format, array('tar', 'gz', 'tgz', 'tbz', 'zip', 'ar', 'deb'))) {
             $CONFIG->files->compression_format = $CMPRExtension = 'zip';
         }
         $render = true;
         switch ($_REQUEST['action']) {
             // All users
             case 'download':
                 global $PREVENT_CSIZE_HEADER;
                 $PREVENT_CSIZE_HEADER = true;
                 while (ob_get_level()) {
                     echo ob_get_clean();
                 }
                 require_once "File/Archive.php";
                 File_Archive::extract($this->path, File_Archive::toArchive($this->filename . '.' . $CMPRExtension, File_Archive::toOutput()));
                 die;
             default:
                 $this->setContent("main", $this->genHTML());
                 break;
         }
         if ($render) {
             $t = 'admin';
             if ($_REQUEST['popup']) {
                 $t = 'popup';
             }
             $Templates->{$t}->render();
         }
     }
 }