コード例 #1
0
ファイル: Backup.php プロジェクト: Dulciane/jaws
 /**
  * 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);
 }
コード例 #2
0
ファイル: Themes.php プロジェクト: juniortux/jaws
 /**
  * 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;
 }
コード例 #3
0
ファイル: export_m.php プロジェクト: restiaka/Guinn-App-Gen
 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()));
 }
コード例 #4
0
ファイル: Upload.php プロジェクト: jonatanolofsson/solidba.se
 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;
     }
 }
コード例 #5
0
 /**
  * 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;
     }
 }
コード例 #6
0
ファイル: Upload.php プロジェクト: Dulciane/jaws
 /**
  * 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;
 }
コード例 #7
0
ファイル: Export.php プロジェクト: Dulciane/jaws
 /**
  * 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();
 }
コード例 #8
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);
    }
コード例 #9
0
 /**
  * _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;
 }
コード例 #10
0
 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);
 }
コード例 #11
0
ファイル: test.php プロジェクト: andychang88/jianzhanseo.com
 function testMultiWriter()
 {
     $this->assertTrue(!PEAR::isError(File_Archive::extract(File_Archive::readMemory("ABCDEF", "A.txt"), File_Archive::toMulti(File_Archive::toVariable($a), File_Archive::toVariable($b)))) && $a == 'ABCDEF' && $b == 'ABCDEF');
 }
コード例 #12
0
 /**
  * バックアップXMLファイル->リストア配列変換処理
  *
  * @access  public
  */
 function getRestoreArray($upload_id, $backup_page_id, $module_id, $temporary_file_path)
 {
     set_time_limit(BACKUP_TIME_LIMIT);
     // メモリ最大サイズ設定
     ini_set('memory_limit', -1);
     $errorList =& $this->_actionChain->getCurErrorList();
     //if($backup_page_id == 0 || $upload_id == 0) {
     //	// フルバックアップをリストアしようとしている
     //	$errorList->add("backup", BACKUP_FAILURE_RESTORE);
     //	return false;
     //}
     //$uploads = $this->_db->selectExecute("uploads", array("upload_id" => $upload_id, "room_id" => $backup_page_id, "module_id" => $module_id));
     $uploads = $this->_db->selectExecute("uploads", array("upload_id" => $upload_id, "module_id" => $module_id));
     if ($uploads === false || !isset($uploads[0]) || count($uploads) > 1) {
         return false;
     }
     $uploads_file_path = FILEUPLOADS_DIR . "backup/" . $uploads[0]['physical_file_name'];
     if (!file_exists($uploads_file_path)) {
         // バックアップファイルなし
         $errorList->add("backup", BACKUP_NONE_RESTORE);
         return false;
     }
     if (file_exists($temporary_file_path)) {
         // 現在、同じバックアップファイル-リストア中
         // エラーとする
         $errorList->add("backup", BACKUP_RESTORING);
         return false;
     }
     if (!mkdir($temporary_file_path, 0777)) {
         $errorList->add("backup", BACKUP_RESTORE_ERROR);
         return false;
     }
     //
     // 解凍
     //
     File_Archive::extract(File_Archive::read($uploads_file_path . "/"), File_Archive::appender($temporary_file_path));
     if (!file_exists($temporary_file_path . BACKUP_ROOM_XML_FILE_NAME)) {
         // XMLファイルなし
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_FAILURE_RESTORE);
         return false;
     }
     // PHP 4 > 4.3.0, PHP 5
     $xml = file_get_contents($temporary_file_path . BACKUP_ROOM_XML_FILE_NAME);
     if ($xml === false) {
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_RESTORE_ERROR);
         return false;
     }
     if (!file_exists($temporary_file_path . BACKUP_ROOM_XML_INI_NAME)) {
         // XML INIファイルなし
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_FAILURE_RESTORE);
         return false;
     }
     $xml_ini = file_get_contents($temporary_file_path . BACKUP_ROOM_XML_INI_NAME);
     if ($xml_ini === false) {
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_RESTORE_ERROR);
         return false;
     }
     $unserializer =& new XML_Unserializer();
     //
     // 複合化チェック
     //
     $result = $unserializer->unserialize($xml_ini);
     if ($result !== true) {
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_FAILURE_UNSERIALIZE);
         return false;
     }
     $data_ini = $unserializer->getUnserializedData();
     // 共有設定されているかどうか
     if ($data_ini["host_field"] == BASE_URL . INDEX_FILE_NAME) {
         // 自サイトならば、無条件でOK
         $self_flag = true;
     } else {
         $self_flag = false;
         // サイトテーブルにあり、commons_flagが立っているものを許す
         $data_ini["host_field"] = preg_replace("/" . preg_quote(INDEX_FILE_NAME, "/") . "\$/i", "", $data_ini["host_field"]);
         $where_params = array("url" => $data_ini["host_field"], "commons_flag" => _ON);
         // 有効期限がいついつの公開鍵を取得
         $other_site = $this->_db->selectExecute("sites", $where_params, null, 1);
         if ($other_site === false) {
             $this->_fileAction->delDir($temporary_file_path);
             $errorList->add("backup", BACKUP_RESTORE_ERROR);
             return false;
         }
         if (!isset($other_site[0])) {
             // 共有設定されていない
             $this->_fileAction->delDir($temporary_file_path);
             $errorList->add("backup", BACKUP_RESTORE_COMMONS_ERROR);
             return false;
         }
     }
     $get_public_url = $data_ini["host_field"] . INDEX_FILE_NAME . "?action=encryption_view_publickey" . "&encrypt_data=" . rawurlencode($data_ini['encrypt_text']) . "&expiration_time=" . $data_ini['expiration_time'] . "&_header=" . _OFF;
     $public_key_html = $this->_requestMain->getResponseHtml($get_public_url);
     if ($public_key_html === false) {
         // 公開鍵取得失敗
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_RESTORE_PUBLIC_KEY_ERROR);
         return false;
     }
     if (is_string($public_key_html)) {
         $public_key_html = trim($public_key_html);
         $public_key = preg_replace("/^public_key=/i", "", $public_key_html);
     }
     if (isset($public_key) && $public_key_html == $public_key) {
         // 公開鍵取得失敗
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_RESTORE_PUBLIC_KEY_ERROR);
         return false;
     }
     // 複合化
     //$this->encryption =& $this->_container->getComponent("encryptionView");
     $decrypt_text = $this->encryption->decrypt($data_ini['encrypt_text'], $public_key);
     $hash_text = sha1($xml);
     if ($decrypt_text != $hash_text) {
         // 不正なファイルの可能性あり
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_FAILURE_RESTORE);
         return false;
     }
     //$options = array ('parseAttributes' => true);	属性値を含める
     //$unserializer =& new XML_Unserializer($options);
     $result = $unserializer->unserialize($xml);
     if ($result !== true) {
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_FAILURE_UNSERIALIZE);
         return false;
     }
     $data = $unserializer->getUnserializedData();
     //-----------------------------------------------------------------------------------
     // NetCommonsバージョンチェック
     // 上3桁目がいっしょならば、リストアを許す
     //-----------------------------------------------------------------------------------
     if (!isset($data["version"]) || !isset($data["version"]["_version"]) || !isset($data["_room_inf"])) {
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_FAILURE_RESTORE);
         return false;
     }
     $current_version = $data["version"]["_version"];
     $current_version_arr = explode(".", $current_version);
     $now_version_arr = explode(".", _NC_VERSION);
     if (count($current_version_arr) != 4 || count($now_version_arr) != 4) {
         // バージョン情報が不正
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_WRONG_VERSION);
         return false;
     }
     if ($now_version_arr[0] != $current_version_arr[0] || $now_version_arr[1] != $current_version_arr[1] || $now_version_arr[2] != $current_version_arr[2]) {
         // バージョン情報が一致しない
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", sprintf(BACKUP_DIFFER_VERSION, $current_version, _NC_VERSION));
         return false;
     }
     //-----------------------------------------------------------------------------------
     // リストア対象ルーム情報取得-チェック
     // DB項目が変わることもありえるので、すべての項目はチェックしない
     // 「バックアップファイル追加」時にチェックすればいい
     //-----------------------------------------------------------------------------------
     if (!isset($data["_room_inf"]["row"]) || !isset($data["_room_inf"]["row"]["page_id"]) || !isset($data["_room_inf"]["row"]["room_id"]) || !isset($data["_room_inf"]["row"]["private_flag"]) || !isset($data["_room_inf"]["row"]["space_type"]) || !isset($data["_room_inf"]["row"]["site_id"]) || !isset($data["_room_inf"]["row"]["thread_num"]) || !isset($data["_room_inf"]["row"]["parent_id"]) || $data["_room_inf"]["row"]["room_id"] != $data["_room_inf"]["row"]["page_id"]) {
         $this->_fileAction->delDir($temporary_file_path);
         $errorList->add("backup", BACKUP_WRONG_ROOMINF);
         return false;
     }
     $room_inf = $data["_room_inf"]["row"];
     if (!$self_flag) {
         $room_inf['site_id'] = $other_site[0]['site_id'];
         $room_inf['url'] = $data_ini["host_field"];
         if ($room_inf['thread_num'] == 2) {
             $room_inf['parent_id'] = 0;
         }
         $room_inf['room_id'] = 0;
     } else {
         $room_inf['url'] = '';
     }
     $room_inf['pre_page_name'] = $room_inf['page_name'];
     // スペースタイプがパブリックスペース or プライベートスペースならば上書き
     // それ以外ならば、追加登録
     if ($room_inf['thread_num'] == 0 && ($room_inf['private_flag'] == _ON || $room_inf['space_type'] == _SPACE_TYPE_PUBLIC)) {
         // パブリックスペース or プライベートスペース
         // 参加者や、その他、親カラムの情報は基本的にリストアしない(選択させる?)
         $restore_type = "top";
     } else {
         // グループルーム or サブグループ(新規ルームとしてリストア)
         if ($room_inf['thread_num'] == 2) {
             $restore_type = "subgroup";
         } else {
             if ($room_inf['space_type'] == _SPACE_TYPE_PUBLIC) {
                 $restore_type = "public_room";
             } else {
                 $restore_type = "group_room";
             }
         }
         // 同名のルームが存在したら、リネームする
         $first_room_name = $room_inf['page_name'];
         $rename_count = 1;
         while (1) {
             $chk_pages =& $this->_pagesView->getPages(array("thread_num" => $room_inf['thread_num'], "space_type" => $room_inf['space_type'], "private_flag" => $room_inf['private_flag'], "page_id=room_id" => null, "page_name" => $room_inf['page_name']));
             if ($chk_pages === false) {
                 $this->_fileAction->delDir($temporary_file_path);
                 return false;
             }
             if (isset($chk_pages[0])) {
                 // 同名のルームあり
                 $room_inf['page_name'] = sprintf(BACKUP_RESTORE_PREFIX_PAGE_NAME, $rename_count) . $first_room_name;
                 $rename_count++;
             } else {
                 break;
             }
         }
     }
     if (($restore_type == "public_room" || $restore_type == "top") && $room_inf['private_flag'] == _OFF) {
         // パブリックスペースであればサイト閉鎖中かどうかを取得(警告メッセージを表示するため)
         // サイト閉鎖中かどうか
         $closesite = $this->_configView->getConfigByConfname(_SYS_CONF_MODID, "closesite");
         if ($closesite === false) {
             $this->_fileAction->delDir($temporary_file_path);
             return false;
         }
         $closesite = $closesite['conf_value'];
     }
     //-----------------------------------------------------------------------------------
     // 各モジュールバージョンチェック
     // 上3桁目がいっしょならば、リストアを許す
     // インストールされていないモジュールはリストアしない
     //-----------------------------------------------------------------------------------
     $modules = $this->_modulesView->getModules(array("system_flag" => _OFF), null, null, null, array($this, "_fetchcallbackModules"), $this->_modulesView);
     if ($modules === false) {
         $this->_fileAction->delDir($temporary_file_path);
         return false;
     }
     $adodb = $this->_db->getAdoDbObject();
     foreach ($modules as $dirname => $module) {
         $buf_tablelist = $this->_databaseSqlutility->getTableList($dirname, false);
         if (is_array($buf_tablelist) && count($buf_tablelist) > 0) {
             foreach ($buf_tablelist as $table) {
                 // テーブルリスト取得
                 $this->tablePrimarylist[$dirname][$table] = $adodb->MetaPrimaryKeys($this->_db->getPrefix() . $table);
                 $this->tablelist[$table] = $dirname;
             }
         }
         unset($buf_tablelist);
     }
     $restore_modules = array();
     $restore_modules["system"]['restore_type'] = $restore_type;
     $restore_modules["system"]['self_flag'] = $self_flag;
     foreach ($data["version"] as $module_name => $module_version) {
         //if($module_name == "_version") {
         //	continue;
         //}
         if (preg_match("/^_/i", $module_name)) {
             // モジュール名称
             continue;
         }
         $restore_modules[$module_name] = array();
         $restore_modules[$module_name]['state'] = false;
         if (isset($modules[$module_name])) {
             $restore_modules[$module_name]['module_id'] = $modules[$module_name]['module_id'];
             $restore_modules[$module_name]['module_name'] = $modules[$module_name]['module_name'];
             $module_version_arr = explode(".", $module_version);
             $now_module_version_arr = explode(".", $modules[$module_name]['version']);
             if (count($current_version_arr) != 4 || count($now_version_arr) != 4) {
                 // モジュールのバージョンの書き方が不正(リストア対象からはずす)
                 $restore_modules[$module_name]['error_mes'] = BACKUP_WRONG_MODULE_VERSION;
                 continue;
             } else {
                 if ($now_module_version_arr[0] != $module_version_arr[0] || $now_module_version_arr[1] != $module_version_arr[1] || $now_module_version_arr[2] != $module_version_arr[2]) {
                     // バージョン情報が一致しない
                     $restore_modules[$module_name]['error_mes'] = BACKUP_DIFFER_MODULE_VERSION;
                     continue;
                 }
             }
             $this->restorelist[$module_name] = true;
             //$buf_tablelist = $this->_databaseSqlutility->getTableList($module_name, false);
             //if(is_array($buf_tablelist) && count($buf_tablelist) > 0) {
             //	foreach($buf_tablelist as $table) {
             //		// テーブルリスト取得
             //		$this->tablelist[$table] = $module_name;
             //	}
             //}
         } else {
             // 未インストールモジュール
             if (isset($data["version"]["_" . $module_name])) {
                 $restore_modules[$module_name]['module_name'] = $data["version"]["_" . $module_name];
             } else {
                 $restore_modules[$module_name]['module_name'] = $module_name;
             }
             $restore_modules[$module_name]['error_mes'] = BACKUP_UNINSTALL_MODULE;
             continue;
         }
         if ($modules[$module_name]['restore_action'] == "auto") {
             //
             // install.iniチェック
             // [Restore]
             // _transfer_id="bbs_id,post_id,topic_id,parent_id,room_id,block_id"
             //						     -> IDを振り替えるリスト($this->db->nextSeq($table_name))
             // topic_id = post_id	     -> post_idを振り替えた値をtopic_idに入れるという意味(topic_idでnextSeqしない)
             // parent_id = post_id      -> 上記と同様
             // room_id = core.room_id   -> coreのテーブルのroom_idがはいる
             // block_id = core.block_id  -> coreのテーブルのblock_idがはいる
             $file_path = MODULE_DIR . "/" . $module_name . '/install.ini';
             if (file_exists($file_path)) {
                 if (version_compare(phpversion(), "5.0.0", ">=")) {
                     $initializer =& DIContainerInitializerLocal::getInstance();
                     $install_ini = $initializer->read_ini_file($file_path, true);
                 } else {
                     $install_ini = parse_ini_file($file_path, true);
                 }
                 if (isset($install_ini['Restore']) && is_array($install_ini['Restore'])) {
                     $restore_modules[$module_name]['transfer_list'] = $install_ini['Restore'];
                 } else {
                     // リストア対象外モジュール
                     $restore_modules[$module_name]['error_mes'] = BACKUP_UNSUPPORTED_MODULE;
                 }
                 //if(isset($install_ini['CleanUp']) && is_array($install_ini['CleanUp'])) {
                 //	// uploadsテーブルのIDを振り替えるため、その振替元のカラムのupload_idの項目を更新しなければならない
                 //	// $install_ini['Restore']にそれを記述すると煩雑になるため、現状、CleanUpの項目を用いる
                 //	$restore_modules[$module_name]['transfer_uploads'] = $install_ini['CleanUp'];
                 //}
             }
         } else {
             if ($modules[$module_name]['restore_action'] == "") {
                 // リストア対象外モジュール
                 $restore_modules[$module_name]['error_mes'] = BACKUP_UNSUPPORTED_MODULE;
             } else {
                 // リストアアクションを呼ぶのみ
                 $restore_modules[$module_name]['transfer_list'] = $modules[$module_name]['restore_action'];
             }
         }
         $restore_modules[$module_name]['state'] = true;
     }
     // room毎に分割
     $this->data =& $data;
     //$this->_fileAction->delDir($temporary_file_path);
     return array($room_inf, $restore_modules, $data["version"], $modules);
 }
コード例 #13
0
ファイル: Logs.php プロジェクト: Dulciane/jaws
 /**
  * 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();
 }
コード例 #14
0
ファイル: index.php プロジェクト: neofreko/anthologize
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;
}
コード例 #15
0
ファイル: Folder.php プロジェクト: jonatanolofsson/solidba.se
 /**
  * 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();
         }
     }
 }
コード例 #16
0
function extract_item($dir, $item)
{
    $mainframe =& JFactory::getApplication();
    if (!nx_isArchive($item)) {
        show_error($GLOBALS["error_msg"]["extract_noarchive"]);
    } else {
        $archive_name = realpath(get_abs_item($dir, $item));
        $file_info = pathinfo($archive_name);
        if (empty($dir)) {
            $extract_dir = realpath($GLOBALS['home_dir']);
        } else {
            $extract_dir = realpath($GLOBALS['home_dir'] . "/" . $dir);
        }
        $ext = $file_info["extension"];
        require_once _QUIXPLORER_PATH . "/libraries/Archive.php";
        $archive_name .= '/';
        $result = File_Archive::extract($archive_name, $extract_dir);
        if (PEAR::isError($result)) {
            show_error($GLOBALS["error_msg"]["extract_failure"]);
        }
    }
    $mainframe->redirect(make_link("list", $dir, null), $GLOBALS['messages']['extract_success']);
}
コード例 #17
0
/**
 * cmdGetDoc()
 *
 * @param  string $sPath
 * @return void
 */
function cmdGetDoc($sPath)
{
    if (isset($_SERVER['PWD'])) {
        chdir($_SERVER['PWD']);
    }
    File_Archive::extract(File_Archive::read(BLOCKEN_DOC_DIR), File_Archive::toArchive('BlockenDoc.zip', File_Archive::toFiles($sPath)));
}
コード例 #18
0
 /**
  * 圧縮処理
  *
  * @return boolean
  * @access public
  */
 function compressFile()
 {
     $cabinet = $this->_request->getParameter("cabinet");
     $file = $this->_request->getParameter("file");
     $module_id = $this->_request->getParameter("module_id");
     $configView =& $this->_container->getComponent("configView");
     $config = $configView->getConfigByConfname($module_id, "compress_ext");
     if ($config === false) {
         return false;
     }
     if (defined($config['conf_value'])) {
         $extension = constant($config['conf_value']);
     } else {
         $extension = $config['conf_value'];
     }
     $file_path = "cabinet/";
     if (!file_exists(FILEUPLOADS_DIR . "/" . $file_path)) {
         mkdir(FILEUPLOADS_DIR . "/" . $file_path, octdec(_UPLOAD_FOLDER_MODE));
     }
     $file_name = $this->_cabinetView->renameFile($file["org_file_name"], $extension);
     $params = array("room_id" => $this->_request->getParameter("room_id"), "module_id" => $module_id, "unique_id" => $file["cabinet_id"], "file_name" => $file_name . "." . $extension, "physical_file_name" => "", "file_path" => $file_path, "action_name" => "common_download_main", "file_size" => 0, "mimetype" => $this->_uploadsView->mimeinfo("type", $file_name . "." . $extension), "extension" => $extension, "garbage_flag" => _ON);
     $upload_id = $this->_uploadsAction->insUploads($params);
     if ($upload_id === false) {
         return false;
     }
     $archive_file_name = $upload_id;
     $this->archive_full_path = FILEUPLOADS_DIR . "/" . $file_path . "/" . $archive_file_name . "." . $extension;
     if (stristr($_SERVER['HTTP_USER_AGENT'], "Mac")) {
         // Macの場合
         $this->encode = "UTF-8";
     } else {
         if (stristr($_SERVER['HTTP_USER_AGENT'], "Windows")) {
             // Windowsの場合
             $this->encode = "SJIS";
         } else {
             $this->encode = _CHARSET;
         }
     }
     if ($file["file_type"] == CABINET_FILETYPE_FOLDER) {
         $result = $this->_compressFile($file["file_id"], mb_convert_encoding($file["org_file_name"], $this->encode, "auto") . "/");
         if ($result === false) {
             return false;
         }
         if (count($this->_source) > 0) {
             File_Archive::extract($this->_source, File_Archive::toArchive($this->archive_full_path, File_Archive::toFiles()));
         }
     } else {
         $sql = "SELECT F.file_id, F.parent_id, F.file_type, F.file_name, F.extension, U.file_path, U.physical_file_name " . "FROM {cabinet_file} F " . "LEFT JOIN {uploads} U ON (F.upload_id=U.upload_id) ";
         $sql .= "WHERE F.cabinet_id = ? ";
         $sql .= "AND F.file_id = ? ";
         $params = array("cabinet_id" => $file["cabinet_id"], "file_id" => $file["file_id"]);
         $result = $this->_db->execute($sql, $params);
         if ($result === false) {
             $this->_db->addError();
             return false;
         }
         $physical_file = FILEUPLOADS_DIR . $result[0]["file_path"] . $result[0]["physical_file_name"];
         $target_file = mb_convert_encoding($file["org_file_name"], $this->encode, "auto") . "." . $file["extension"];
         if (file_exists($physical_file)) {
             File_Archive::extract(File_Archive::read($physical_file, $target_file), File_Archive::toArchive($this->archive_full_path, File_Archive::toFiles()));
         }
     }
     if (file_exists($this->archive_full_path)) {
         $file_size = filesize($this->archive_full_path);
     } else {
         return false;
     }
     if ($cabinet["compress_download"] == _OFF) {
         $result = $this->_uploadsAction->updUploads(array("file_size" => $file_size, "garbage_flag" => _OFF), array("upload_id" => $upload_id));
         if ($result === false) {
             return false;
         }
         $params = array("cabinet_id" => $file["cabinet_id"], "upload_id" => $upload_id, "parent_id" => $file["parent_id"], "file_name" => $file_name, "extension" => $extension, "depth" => $file["depth"], "size" => $file_size, "download_num" => 0, "file_type" => CABINET_FILETYPE_FILE, "display_sequence" => 0);
         $file_id = $this->_db->insertExecute("cabinet_file", $params, true, "file_id");
         $params = array("file_id" => $file_id, "comment" => "");
         $result = $this->_db->insertExecute("cabinet_comment", $params, true);
         if ($result === false) {
             return false;
         }
     } else {
         $result = $this->_uploadsAction->updUploads(array("file_size" => $file_size), array("upload_id" => $upload_id));
         if ($result === false) {
             return false;
         }
         $pathname = FILEUPLOADS_DIR . $file_path;
         $filename = $file_name . "." . $extension;
         $physical_file_name = $archive_file_name . "." . $extension;
         clearstatcache();
         $this->_uploadsView->headerOutput($pathname, $filename, $physical_file_name);
         $result = $this->_uploadsAction->delUploadsById($upload_id);
         if ($file['file_type'] == CABINET_FILETYPE_FILE) {
             $this->setDownload($file['file_id']);
         }
         exit;
     }
     return true;
 }
コード例 #19
0
 function extractArchive($file, $forceExtractionFolder = true)
 {
     $extensions = array('zip', 'tar', 'gz', 'tar.gz', 'tgz', 'tar.bz2', 'tbz');
     $extension = $this->getExtension($file['path']);
     $originalIncludePath = ini_get('include_path');
     ini_set('include_path', dirname(__FILE__) . '/pear');
     if (!function_exists('file_archive_cleancache')) {
         require_once 'File/Archive.php';
     }
     $retval = array();
     if (in_array($extension, (array) $extensions)) {
         if (is_callable(array('File_Archive', 'extract')) && is_callable(array('File_Archive', 'read'))) {
             $backupCWD = getcwd();
             $path = dirname($file['path']);
             chdir($path);
             $source = basename($file['path']) . '/';
             if ($forceExtractionFolder) {
                 $destination = basename($file['path'], ".{$extension}");
             } else {
                 $destination = $path;
             }
             $error = File_Archive::extract($source, $destination);
             chdir($backupCWD);
             if (PEAR::isError($error)) {
                 $retval = array('extracted' => false, 'error' => sprintf(__('Extraction failed: %s', $this->_var), $error->getMessage()));
             } else {
                 $retval = array('destination' => path_join($path, $destination), 'extracted' => true, 'error' => false);
             }
         } else {
             $retval = array('extracted' => false, 'error' => __('Unable to execute File_Archive::extract', $this->_var));
         }
     } else {
         $retval = array('extracted' => false, 'error' => false);
     }
     ini_set('include_path', $originalIncludePath);
     return $retval;
 }
コード例 #20
0
<?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()));
コード例 #21
0
ファイル: step2.php プロジェクト: rludvik/phpfreechat
         // remote file
         $req =& new HTTP_Request($mirrors[$i] . "/" . $archivename, $param);
         if (!PEAR::isError($req->sendRequest())) {
             $archivecontent = $req->getResponseBody();
             file_put_contents($dstpath . "/" . $archivename, $archivecontent);
         }
     }
     if (file_exists($dstpath . "/" . $archivename)) {
         $copied = true;
     }
     // the archive has been copied (but maybe it just contains a html error page!)
     if ($copied) {
         require_once "File/Archive.php";
         $src = $dstpath . "/" . $archivename . "/";
         $dest = $dstpath;
         $res = @File_Archive::extract($src, $dest);
         if (PEAR::isError($res)) {
             $errors[$mirrors[$i]][] = $res->getMessage();
         } else {
             $unziped = true;
         }
     }
 }
 if ($unziped) {
     echo "<p>Done!</p>";
     echo "<p>Click <a href=\"./data/" . $archivename2 . "\">here</a> to visit your chat!</p>";
     @touch($dstpath . "/isinstalled");
 } else {
     echo "<p>Error!</p>";
     echo "<pre>";
     print_r($errors);
コード例 #22
0
 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);
     }
 }
コード例 #23
0
 /**
  * ルームバックアップ処理
  * @param  array page
  * @return boolean true or false
  * @access	private
  */
 function _roomBackUp(&$page)
 {
     //
     // uploadsテーブルInsert
     //
     $file_path = "backup/";
     $extension = BACKUP_COMPRESS_EXT;
     $download_action_name = BACKUP_DOWNLOAD_ACTION_NAME;
     $file_name = $page['page_name'] . "." . BACKUP_COMPRESS_EXT;
     $mimetype = $this->uploadsView->mimeinfo("type", $file_name);
     $garbage_flag = _ON;
     $params = array('room_id' => 0, 'module_id' => $this->module_id, 'unique_id' => 0, 'file_name' => $file_name, 'physical_file_name' => "", 'file_path' => $file_path, 'action_name' => $download_action_name, 'file_size' => 0, 'mimetype' => $mimetype, 'extension' => $extension, 'garbage_flag' => $garbage_flag);
     $upload_id = $this->uploadsAction->insUploads($params);
     if ($upload_id === false) {
         return false;
     }
     $params = array('upload_id' => $upload_id, 'site_id' => $this->session->getParameter("_site_id"), 'url' => '', 'parent_id' => $page['parent_id'], 'thread_num' => $page['thread_num'], 'space_type' => $page['space_type'], 'private_flag' => $page['private_flag'], 'room_id' => $page['page_id']);
     $result = $this->db->insertExecute("backup_uploads", $params, true);
     if ($result === false) {
         $this->_delUploads();
         return false;
     }
     if ($upload_id > 0) {
         $this->_upload_id = $upload_id;
         // バックアップ処理中をセッションに保持
         $this->session->setParameter(array("backup", "backingup", $this->_upload_id), _ON);
         $temporary_file_path = FILEUPLOADS_DIR . "backup/" . BACKUP_TEMPORARY_DIR_NAME . "/" . BACKUP_BACKUP_DIR_NAME . "/" . $page['page_id'] . "/";
         if (file_exists($temporary_file_path)) {
             // 現在、同じバックアップファイル作成中
             // エラーとする
             $this->_delUploads();
             $this->errorList->add("backup", BACKUP_BACKINGUP);
             return false;
         }
         $this->backupRestore->mkdirTemporary(BACKUP_BACKUP_DIR_NAME);
         if (mkdir($temporary_file_path, 0755)) {
             //
             // BackUp XML 作成
             //
             $write_xml_data = "<?xml version=\"1.0\" encoding=\"" . _CHARSET . "\"?>\n<rooms>\n";
             //
             // Version情報書き込み
             //
             $options = array(XML_SERIALIZER_OPTION_ROOT_NAME => "version", XML_SERIALIZER_OPTION_INDENT => "\t", XML_SERIALIZER_OPTION_XML_DECL_ENABLED => false, XML_SERIALIZER_OPTION_ENTITIES => XML_UTIL_ENTITIES_NONE);
             $serializer = new XML_Serializer($options);
             $data_arr = array();
             $data_arr['_version'] = _NC_VERSION;
             $modules = $this->modulesView->getModules(array("system_flag" => _OFF));
             if ($modules === false) {
                 $this->_delUploads();
                 return false;
             }
             if (isset($modules[0])) {
                 foreach ($modules as $module) {
                     $pathList = explode("_", $module['action_name']);
                     $dirname = $pathList[0];
                     $data_arr[$dirname] = $module['version'];
                     $data_arr["_" . $dirname] = "<![CDATA[" . $module['module_name'] . "]]>";
                     $data_arr["__" . $module['module_id']] = $dirname;
                 }
             }
             $serializer->serialize($data_arr);
             $xml_data = $serializer->getSerializedData();
             if ($xml_data != "") {
                 $xml_data .= "\n";
             }
             $write_xml_data .= $xml_data;
             //fwrite ($this->xml_handle, $xml_data);
             //
             // ルーム情報書き込み
             //
             $options = array(XML_SERIALIZER_OPTION_ROOT_NAME => "_room_inf", XML_SERIALIZER_OPTION_INDENT => "\t", XML_SERIALIZER_OPTION_XML_DECL_ENABLED => false, XML_SERIALIZER_OPTION_DEFAULT_TAG => "row", XML_SERIALIZER_OPTION_ENTITIES => XML_UTIL_ENTITIES_NONE);
             $serializer = new XML_Serializer($options);
             $data_arr = $this->_serializeXML("pages", array("page_id" => $page['page_id']), null, "");
             $serializer->serialize($data_arr);
             $xml_data = $serializer->getSerializedData();
             if ($xml_data != "") {
                 $xml_data .= "\n";
             }
             $write_xml_data .= $xml_data;
             //fwrite ($this->xml_handle, $xml_data);
             //
             // アップロードファイルコピー処理
             //
             if (!$this->_uploadCopy($temporary_file_path, $page)) {
                 $this->_delUploads();
                 return false;
             }
             $write_xml_data .= $this->_createDumpXML($page['page_id']);
             //if(!$this->_createDumpXML($page['page_id'])) return false;
             // 子グループがあれば、その子グループもバックアップ対象とする
             $where_params = array("parent_id" => $page['page_id'], "page_id = room_id" => null);
             $child_pages = $this->pagesView->getPages($where_params);
             if ($child_pages === false) {
                 return false;
             }
             if (count($child_pages) > 0) {
                 foreach ($child_pages as $child_page) {
                     if (!$this->_uploadCopy($temporary_file_path, $child_page)) {
                         $this->_delUploads();
                         return false;
                     }
                     $write_xml_data .= $this->_createDumpXML($child_page['page_id'], true);
                 }
             }
             //
             // 書き込み
             //
             $write_xml_data .= "</rooms>";
             $xml_handle = fopen($temporary_file_path . BACKUP_ROOM_XML_FILE_NAME, "w");
             if (!$xml_handle) {
                 $this->_delUploads();
                 $this->errorList->add("backup", BACKUP_MKDIR_ERROR);
                 return false;
             }
             $result = fwrite($xml_handle, $write_xml_data);
             fclose($xml_handle);
             if ($result === false) {
                 $this->errorList->add("backup", BACKUP_MKDIR_ERROR);
                 return false;
             }
             //
             // 暗号化したペアキーの有効期限書き込み
             //
             $ini_handle = fopen($temporary_file_path . BACKUP_ROOM_XML_INI_NAME, "w");
             if (!$ini_handle) {
                 $this->errorList->add("backup", BACKUP_MKDIR_ERROR);
                 $this->_delUploads();
                 return false;
             }
             // ハッシュ化データを秘密鍵で暗号化
             $encryption = $this->encryption->getEncryptionKeys();
             $hash_text = sha1($write_xml_data);
             $encrypt_text = $this->encryption->encrypt($hash_text, $encryption['private_key']);
             $xml_data = "<?xml version=\"1.0\" encoding=\"" . _CHARSET . "\"?>\n" . "<_expiration>\n" . "\t<encrypt_text>" . $encrypt_text . "</encrypt_text>\n" . "\t<host_field><![CDATA[" . BASE_URL . INDEX_FILE_NAME . "]]></host_field>\n" . "\t<expiration_time>" . $encryption['expiration_time'] . "</expiration_time>\n" . "</_expiration>\n";
             fwrite($ini_handle, $xml_data);
             fclose($ini_handle);
             //
             // 圧縮
             //
             //$physical_file = FILEUPLOADS_DIR."backup/".$upload_id.".".$extension;
             if (!is_dir(FILEUPLOADS_DIR . "backup/")) {
                 mkdir(FILEUPLOADS_DIR . "backup/", 0755);
             }
             $target_file = FILEUPLOADS_DIR . "backup/" . $upload_id . "." . $extension;
             //$target_file = mb_convert_encoding($file_obj["file_name"], $this->encode, "auto").".".$file_obj["extension"];
             if (file_exists($temporary_file_path)) {
                 File_Archive::extract(File_Archive::read($temporary_file_path), File_Archive::toArchive($target_file, File_Archive::toFiles()));
                 // テンポラリーファイル削除
                 $this->fileAction->delDir($temporary_file_path);
                 // file_size 更新
                 $params = array('file_size' => $this->fileView->getSize($target_file), 'garbage_flag' => _OFF);
                 $where_params = array("upload_id" => $upload_id);
                 $result = $this->uploadsAction->updUploads($params, $where_params);
                 if ($result === false) {
                     $this->_delUploads();
                     return false;
                 }
             }
             //
             // バックアップ暗号データ履歴登録
             //
             $params = array("encrypt_data" => $encrypt_text, "room_id" => $this->backup_page_id);
             $result = $this->db->insertExecute("backup_encrypt_history", $params, true);
             if ($result === false) {
                 return $result;
             }
         } else {
             $this->errorList->add("backup", BACKUP_MKDIR_ERROR);
             $this->_delUploads();
             return false;
         }
         //$physical_file_name = "${upload_id}.${extension}";
         //$this->fileUpload->move($i, FILEUPLOADS_DIR.$file_path.$physical_file_name);
     }
     return true;
 }
コード例 #24
0
ファイル: ThemeHandler.php プロジェクト: rverbrugge/dif
 /**
  * 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;
     */
 }
コード例 #25
0
 /**
  * Zip the temp folder
  */
 function createZipFile($bEchoStatus = FALSE)
 {
     if (empty($this->aPaths)) {
         return PEAR::raiseError(_kt("No folders or documents found to compress"));
     }
     $config = KTConfig::getSingleton();
     $useBinary = $config->get('export/useBinary', false);
     // Set environment language to output character encoding
     $loc = $this->sOutputEncoding;
     putenv("LANG={$loc}");
     putenv("LANGUAGE={$loc}");
     $loc = setlocale(LC_ALL, $loc);
     if ($useBinary) {
         $sManifest = sprintf("%s/%s", $this->sTmpPath, "MANIFEST");
         file_put_contents($sManifest, join("\n", $this->aPaths));
     }
     $sZipFile = sprintf("%s/%s." . $this->extension, $this->sTmpPath, $this->sZipFileName);
     $sZipFile = str_replace('<', '', str_replace('</', '', str_replace('>', '', $sZipFile)));
     if ($useBinary) {
         $sZipCommand = KTUtil::findCommand("export/zip", "zip");
         $aCmd = array($sZipCommand, "-r", $sZipFile, ".", "-i@MANIFEST");
         $sOldPath = getcwd();
         chdir($this->sTmpPath);
         // Note that the popen means that pexec will return a file descriptor
         $aOptions = array('popen' => 'r');
         $fh = KTUtil::pexec($aCmd, $aOptions);
         if ($bEchoStatus) {
             $last_beat = time();
             while (!feof($fh)) {
                 if ($i % 1000 == 0) {
                     $this_beat = time();
                     if ($last_beat + 1 < $this_beat) {
                         $last_beat = $this_beat;
                         print "&nbsp;";
                     }
                 }
                 $contents = fread($fh, 4096);
                 if ($contents) {
                     print nl2br($this->_convertEncoding($contents, false));
                 }
                 $i++;
             }
         }
         pclose($fh);
     } else {
         // Create the zip archive using the PEAR File_Archive
         File_Archive::extract(File_Archive::read($this->sTmpPath . '/Root Folder'), File_Archive::toArchive($this->sZipFileName . '.' . $this->extension, File_Archive::toFiles($this->sTmpPath), $this->extension));
     }
     // Save the zip file and path into session
     $_SESSION['zipcompression'] = KTUtil::arrayGet($_SESSION, 'zipcompression', array());
     $sExportCode = $this->exportCode;
     $_SESSION['zipcompression'][$sExportCode] = array('file' => $sZipFile, 'dir' => $this->sTmpPath);
     $_SESSION['zipcompression']['exportcode'] = $sExportCode;
     $this->sZipFile = $sZipFile;
     return $sExportCode;
 }