extractModify() public method

While extracting a file, if the directory path does not exists it is created. While extracting a file, if the file already exists it is replaced without looking for last modification date. While extracting a file, if the file already exists and is write protected, the extraction is aborted. While extracting a file, if a directory with the same name already exists, the extraction is aborted. While extracting a directory, if a file with the same name already exists, the extraction is aborted. While extracting a file/directory if the destination directory exist and is write protected, or does not exist but can not be created, the extraction is aborted. If after extraction an extracted file does not show the correct stored file size, the extraction is aborted. When the extraction is aborted, a PEAR error text is set and false is returned. However the result can be a partial extraction that may need to be manually cleaned.
See also: extractList()
public extractModify ( string $p_path, string $p_remove_path ) : boolean
$p_path string The path of the directory where the files/dir need to by extracted.
$p_remove_path string Part of the memorized path that can be removed if present at the beginning of the file/dir path.
return boolean true on success, false on error.
示例#1
0
 function doBundle($command, $options, $params)
 {
     $opts = array('force' => true, 'nodeps' => true, 'soft' => true, 'downloadonly' => true);
     $downloader =& $this->getDownloader($this->ui, $opts, $this->config);
     $reg =& $this->config->getRegistry();
     if (count($params) < 1) {
         return $this->raiseError("Please supply the package you want to bundle");
     }
     if (isset($options['destination'])) {
         if (!is_dir($options['destination'])) {
             System::mkdir('-p ' . $options['destination']);
         }
         $dest = realpath($options['destination']);
     } else {
         $pwd = getcwd();
         $dir = $pwd . DIRECTORY_SEPARATOR . 'ext';
         $dest = is_dir($dir) ? $dir : $pwd;
     }
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $err = $downloader->setDownloadDir($dest);
     PEAR::staticPopErrorHandling();
     if (PEAR::isError($err)) {
         return PEAR::raiseError('download directory "' . $dest . '" is not writeable.');
     }
     $result =& $downloader->download(array($params[0]));
     if (PEAR::isError($result)) {
         return $result;
     }
     if (!isset($result[0])) {
         return $this->raiseError('unable to unpack ' . $params[0]);
     }
     $pkgfile =& $result[0]->getPackageFile();
     $pkgname = $pkgfile->getName();
     $pkgversion = $pkgfile->getVersion();
     // Unpacking -------------------------------------------------
     $dest .= DIRECTORY_SEPARATOR . $pkgname;
     $orig = $pkgname . '-' . $pkgversion;
     $tar = new Archive_Tar($pkgfile->getArchiveFile());
     if (!$tar->extractModify($dest, $orig)) {
         return $this->raiseError('unable to unpack ' . $pkgfile->getArchiveFile());
     }
     $this->ui->outputData("Package ready at '{$dest}'");
     // }}}
 }
示例#2
0
    public static function hotfixInstall($file)

    {

        $result = array();



        $dirHotfix = PATH_DATA . "hotfixes";



        $arrayPathInfo = pathinfo($file);



        $f = ($arrayPathInfo["dirname"] == ".")? $dirHotfix . PATH_SEP . $file : $file;



        $swv  = 1;

        $msgv = "";



        if (!file_exists($dirHotfix)) {

            G::mk_dir($dirHotfix, 0777);

        }



        if (!file_exists($f)) {

            $swv  = 0;

            $msgv = $msgv . (($msgv != "")? "\n": null) . "- The file \"$f\" does not exist";

        }



        if ($arrayPathInfo["extension"] != "tar") {

            $swv  = 0;

            $msgv = $msgv . (($msgv != "")? "\n": null) . "- The file extension \"$file\" is not \"tar\"";

        }



        if ($swv == 1) {

            G::LoadThirdParty("pear/Archive", "Tar");



            //Extract

            $tar = new Archive_Tar($f);



            $swTar = $tar->extractModify(PATH_TRUNK, "processmaker"); //true on success, false on error



            if ($swTar) {

                $result["status"] = 1;

                $result["message"] = "- Hotfix installed successfully \"$f\"";

            } else {

                $result["status"] = 0;

                $result["message"] = "- Could not extract file \"$f\"";

            }

        } else {

            $result["status"] = 0;

            $result["message"] = $msgv;

        }



        return $result;

    }
 /**
  * Extracts the package archive file
  * @return boolean True on success, False on error
  */
 function extractArchive()
 {
     $base_Dir = DOCMAN_Compat::mosPathName(JPATH_ROOT . '/media');
     $archivename = $base_Dir . $this->installArchive();
     $tmpdir = uniqid('install_');
     $extractdir = DOCMAN_Compat::mosPathName($base_Dir . $tmpdir);
     $archivename = DOCMAN_Compat::mosPathName($archivename, false);
     $this->unpackDir($extractdir);
     if (preg_match('/.zip$/i', $archivename)) {
         // Extract functions
         require_once JPATH_ADMINISTRATOR . DS . 'includes' . DS . 'pcl' . DS . 'pclzip.lib.php';
         require_once JPATH_ADMINISTRATOR . DS . 'includes' . DS . 'pcl' . DS . 'pclerror.lib.php';
         $zipfile = new PclZip($archivename);
         if ($this->isWindows()) {
             define('OS_WINDOWS', 1);
         } else {
             define('OS_WINDOWS', 0);
         }
         $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
         if ($ret == 0) {
             $this->setError(1, 'Unrecoverable error "' . $zipfile->errorName(true) . '"');
             return false;
         }
     } else {
         require_once JPATH_ROOT . DS . 'includes' . DS . 'Archive' . DS . 'Tar.php';
         $archive = new Archive_Tar($archivename);
         $archive->setErrorHandling(PEAR_ERROR_PRINT);
         if (!$archive->extractModify($extractdir, '')) {
             $this->setError(1, 'Extract Error');
             return false;
         }
     }
     $this->installDir($extractdir);
     // Try to find the correct install dir. in case that the package have subdirs
     // Save the install dir for later cleanup
     $filesindir = DOCMAN_Compat::mosReadDirectory($this->installDir(), '');
     if (count($filesindir) == 1) {
         if (is_dir($extractdir . $filesindir[0])) {
             $this->installDir(DOCMAN_Compat::mosPathName($extractdir . $filesindir[0]));
         }
     }
     return true;
 }
 /**
  * プラグインアーカイブを解凍する.
  *
  * @param string $path アーカイブパス
  * @return boolean Archive_Tar::extractModify()のエラー
  */
 function unpackPluginArchive($path)
 {
     // 圧縮フラグTRUEはgzip解凍をおこなう
     $tar = new Archive_Tar($path, true);
     $dir = dirname($path);
     $file_name = basename($path);
     // 拡張子を切り取る
     $unpacking_name = preg_replace("/(\\.tar|\\.tar\\.gz)\$/", '', $file_name);
     // 指定されたフォルダ内に解凍する
     $result = $tar->extractModify($dir . '/', $unpacking_name);
     GC_Utils_Ex::gfPrintLog(t('c_Decompression:_01') . $dir . '/' . $file_name . '->' . $dir . '/' . $unpacking_name);
     // 解凍元のファイルを削除する.
     unlink($path);
     return $result;
 }
示例#5
0
 function doBundle($command, $options, $params)
 {
     if (empty($this->installer)) {
         $this->installer =& new PEAR_Installer($this->ui);
     }
     $installer =& $this->installer;
     if (sizeof($params) < 1) {
         return $this->raiseError("Please supply the package you want to bundle");
     }
     $pkgfile = $params[0];
     $need_download = false;
     if (preg_match('#^(http|ftp)://#', $pkgfile)) {
         $need_download = true;
     } elseif (!@is_file($pkgfile)) {
         if ($installer->validPackageName($pkgfile)) {
             $pkgfile = $installer->getPackageDownloadUrl($pkgfile);
             $need_download = true;
         } else {
             if (strlen($pkgfile)) {
                 return $this->raiseError("Could not open the package file: {$pkgfile}");
             } else {
                 return $this->raiseError("No package file given");
             }
         }
     }
     // Download package -----------------------------------------------
     if ($need_download) {
         $downloaddir = $installer->config->get('download_dir');
         if (empty($downloaddir)) {
             if (PEAR::isError($downloaddir = System::mktemp('-d'))) {
                 return $downloaddir;
             }
             $installer->log(2, '+ tmp dir created at ' . $downloaddir);
         }
         $callback = $this->ui ? array(&$installer, '_downloadCallback') : null;
         $file = $installer->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback);
         if (PEAR::isError($file)) {
             return $this->raiseError($file);
         }
         $pkgfile = $file;
     }
     // Parse xml file -----------------------------------------------
     $pkginfo = $installer->infoFromTgzFile($pkgfile);
     if (PEAR::isError($pkginfo)) {
         return $this->raiseError($pkginfo);
     }
     $installer->validatePackageInfo($pkginfo, $errors, $warnings);
     // XXX We allow warnings, do we have to do it?
     if (count($errors)) {
         if (empty($options['force'])) {
             return $this->raiseError("The following errors where found:\n" . implode("\n", $errors));
         } else {
             $this->log(0, "warning : the following errors were found:\n" . implode("\n", $errors));
         }
     }
     $pkgname = $pkginfo['package'];
     // Unpacking -------------------------------------------------
     if (isset($options['destination'])) {
         if (!is_dir($options['destination'])) {
             System::mkdir('-p ' . $options['destination']);
         }
         $dest = realpath($options['destination']);
     } else {
         $pwd = getcwd();
         if (is_dir($pwd . DIRECTORY_SEPARATOR . 'ext')) {
             $dest = $pwd . DIRECTORY_SEPARATOR . 'ext';
         } else {
             $dest = $pwd;
         }
     }
     $dest .= DIRECTORY_SEPARATOR . $pkgname;
     $orig = $pkgname . '-' . $pkginfo['version'];
     $tar = new Archive_Tar($pkgfile);
     if (!@$tar->extractModify($dest, $orig)) {
         return $this->raiseError("unable to unpack {$pkgfile}");
     }
     $this->ui->outputData("Package ready at '{$dest}'");
     // }}}
 }
示例#6
0
    foreach ($bootstrap_pkgs as $pkg) {
        $tarball = null;
        if (isset($local_dir[$pkg])) {
            echo str_pad("Using local package: {$pkg}", max(38, 21 + strlen($pkg) + 4), '.');
            copy($gopear_bundle_dir . '/' . $local_dir[$pkg], $local_dir[$pkg]);
            $tarball = $local_dir[$pkg];
        } else {
            print str_pad("Downloading package: {$pkg}", max(38, 21 + strlen($pkg) + 4), '.');
            $url = sprintf($urltemplate, $pkg);
            $pkg = str_replace('-stable', '', $pkg);
            $tarball = download_url($url, null, $http_proxy);
        }
        displayHTMLProgress($progress += round(19 / count($bootstrap_pkgs)));
        $fullpkg = substr($tarball, 0, strrpos($tarball, '.'));
        $tar = new Archive_Tar($tarball, $have_gzip);
        if (!$tar->extractModify($ptmp, $fullpkg)) {
            bail("Extraction for {$fullpkg} failed!\n");
        }
        $bootstrap_pkgs_tarballs[$pkg] = $tarball;
        print "ok\n";
    }
}
unset($noextract, $registry, $pkg, $tarball, $url, $fullpkg, $tar);
print "\n" . 'Preparing installer..................' . "\n";
displayHTMLProgress($progress = 40);
// Default for sig_bin
putenv('PHP_PEAR_SIG_BIN=""');
// Default for sig_keydir
putenv('PHP_PEAR_SIG_KEYDIR=""');
putenv('PHP_PEAR_DOWNLOAD_DIR=' . $temp_dir . '/download');
putenv('PHP_PEAR_TEMP_DIR=' . $temp_dir);
示例#7
0
function plug_new($root_name, $index_file = '')
{
    require_once 'Archive/Tar.php';
    $tar = new Archive_Tar($cfg_cms['cms_path'] . "tpl/pluginvorlage.tar");
    $tmp_plugmeta = $tar->extractInString('pluginvorlage.php');
    $tmp_plugmeta = str_replace('{pluginname}', $root_name, $tmp_plugmeta);
    if (!$tar->extractModify($cfg_cms['cms_path'] . 'plugins/' . $root_name . '/', '/')) {
        return '-1';
    }
    if (true != ($write = lib_write_file($cfg_cms['cms_path'] . 'plugins/' . $root_name . '/' . $root_name . '_meta.php', $tmp_plugmeta))) {
        return '-2';
    }
    if ('-1' == ($delete = lib_delete_file($cfg_cms['cms_path'] . 'plugins/' . $root_name . '/pluginvorlage.php'))) {
        return '-3';
    }
    if ($index_file != '' && !lib_check_file($cfg_cms['cms_path'] . 'plugins/' . $root_name . '/' . $index_file)) {
        $content = "<?PHP\n/*\n * Plugin-Indexfile\n */\n?" . ">\n";
        if (true != lib_write_file($cfg_cms['cms_path'] . 'plugins/' . $root_name . '/' . $index_file, $content)) {
            return '-4';
        }
    }
    return true;
}
 /**
  *
  * Extract theme from archive
  * @throws Exception
  * @param string $source_path archive path
  *
  * @return waTheme
  */
 public static function extract($source_path)
 {
     static $white_list = array('js', 'css', 'html', 'txt', 'png', 'jpg', 'jpeg', 'jpe', 'tiff', 'bmp', 'gif', 'svg', 'htc', 'cur', 'ttf', 'eot', 'otf', 'woff', '');
     $autoload = waAutoload::getInstance();
     $autoload->add('Archive_Tar', 'wa-installer/lib/vendors/PEAR/Tar.php');
     $autoload->add('PEAR', 'wa-installer/lib/vendors/PEAR/PEAR.php');
     $instance = null;
     if (class_exists('Archive_Tar')) {
         try {
             $tar_object = new Archive_Tar($source_path, true);
             $files = $tar_object->listContent();
             if (!$files) {
                 self::throwArchiveException('INVALID_OR_EMPTY_ARCHIVE');
             }
             //search theme info
             $info = false;
             $pattern = "@(/|^)" . wa_make_pattern(self::PATH, '@') . "\$@";
             foreach ($files as $file) {
                 if (preg_match($pattern, $file['filename'])) {
                     $info = $tar_object->extractInString($file['filename']);
                     break;
                 }
             }
             if (!$info) {
                 self::throwThemeException('MISSING_THEME_XML');
             }
             $xml = @simplexml_load_string($info);
             $app_id = (string) $xml['app'];
             $id = (string) $xml['id'];
             if (!$app_id) {
                 self::throwThemeException('MISSING_APP_ID');
             } elseif (!$id) {
                 self::throwThemeException('MISSING_THEME_ID');
             } else {
                 if ($app_info = wa()->getAppInfo($app_id)) {
                     //TODO check theme support
                     if ($parent_theme = (string) $xml['parent_theme_id']) {
                         $parent_theme = explode(':', $parent_theme, 2);
                         try {
                             if (count($parent_theme) == 2) {
                                 new waTheme($parent_theme[1], $parent_theme[0]);
                             } else {
                                 new waTheme($parent_theme[0], $app_id);
                             }
                         } catch (Exception $ex) {
                             self::throwThemeException('PARENT_THEME_NOT_FOUND', $ex->getMessage());
                         }
                     }
                 } else {
                     $message = sprintf(_w('Theme “%s” is for app “%s”, which is not installed in your Webasyst. Install the app, and upload theme once again.'), $id, $app_id);
                     throw new waException($message);
                 }
             }
             $wa_path = "wa-apps/{$app_id}/themes/{$id}";
             $wa_pattern = wa_make_pattern($wa_path, '@');
             $file = reset($files);
             if (preg_match("@^{$wa_pattern}(/|\$)@", $file['filename'])) {
                 $extract_path = $wa_path;
                 $extract_pattern = $wa_pattern;
             } else {
                 $extract_path = $id;
                 $extract_pattern = wa_make_pattern($id, '@');
                 if (!preg_match("@^{$extract_pattern}(/|\$)@", $file['filename'])) {
                     $extract_path = '';
                     $extract_pattern = false;
                 }
             }
             if ($extract_path) {
                 $extract_path = trim($extract_path, '/') . '/';
             }
             $missed_files = array();
             foreach ($xml->xpath('/theme/files/file') as $theme_file) {
                 $path = (string) $theme_file['path'];
                 $parent = intval((string) $theme_file['parent']);
                 if (!in_array(pathinfo($theme_file['path'], PATHINFO_EXTENSION), array('html', 'js', 'css'))) {
                     self::throwThemeException('UNEXPECTED_EDITABLE_FILE_TYPE', $theme_file['path']);
                 }
                 if (!$parent) {
                     $missed_files[$path] = $extract_path . $path;
                 }
             }
             #angry check
             foreach ($files as $file) {
                 if ($extract_pattern && !preg_match("@^{$extract_pattern}(/|\$)@", $file['filename'])) {
                     self::throwThemeException('UNEXPECTED_FILE_PATH', "{$file['filename']}. Expect files in [{$extract_path}] directory");
                 } elseif (preg_match('@\\.(php\\d*|pl)@', $file['filename'], $matches)) {
                     if (preg_match('@(^|/)build\\.php$@', $file['filename'])) {
                         $file['content'] = $tar_object->extractInString($file['filename']);
                         if (!preg_match('@^<\\?php[\\s\\n]+return[\\s\\n]+\\d+;[\\s\\n]*$@', $file['content'])) {
                             self::throwThemeException('UNEXPECTED_FILE_CONTENT', $file['filename']);
                         }
                     } else {
                         self::throwThemeException('UNEXPECTED_FILE_TYPE', $file['filename']);
                     }
                 } else {
                     if (preg_match('@(^|/)\\.htaccess$@', $file['filename'])) {
                         $file['content'] = $tar_object->extractInString($file['filename']);
                         if (preg_match('@\\b(add|set)Handler\\b@ui', $file['content'])) {
                             self::throwThemeException('INVALID_HTACCESS', $file['filename']);
                         }
                     } elseif (!in_array(pathinfo($file['filename'], PATHINFO_EXTENSION), $white_list)) {
                         if (!in_array(strtolower(basename($file['filename'])), array('theme.xml', 'build.php', '.htaccess', 'readme'))) {
                             self::throwThemeException('UNEXPECTED_FILE_TYPE', $file['filename']);
                         }
                     }
                     if ($extract_pattern) {
                         $file['filename'] = preg_replace("@^{$extract_pattern}/?@", '', $file['filename']);
                     }
                     if (empty($file['typeflag']) && !empty($file['filename']) && isset($missed_files[$file['filename']])) {
                         unset($missed_files[$file['filename']]);
                     }
                 }
             }
             if (!empty($missed_files)) {
                 self::throwThemeException('MISSING_DESCRIBED_FILES', implode(', ', $missed_files));
             }
             self::verify($id);
             self::protect($app_id);
             $target_path = wa()->getDataPath("themes/{$id}", true, $app_id, false);
             waFiles::delete($target_path);
             if ($extract_path && !$tar_object->extractModify($target_path, $extract_path)) {
                 self::throwArchiveException('INTERNAL_ARCHIVE_ERROR');
             } elseif (!$tar_object->extract($target_path)) {
                 self::throwArchiveException('INTERNAL_ARCHIVE_ERROR');
             }
             $instance = new self($id, $app_id);
             $instance->check();
         } catch (Exception $ex) {
             if (isset($target_path) && $target_path) {
                 waFiles::delete($target_path, true);
             }
             throw $ex;
         }
     } else {
         self::throwArchiveException('UNSUPPORTED_ARCHIVE_TYPE');
     }
     return $instance;
 }
示例#9
0
function extractArchive($filename)
{
    $absolute_path = JPATH_ROOT;
    $base_Dir = $absolute_path . '/tmp/';
    $archivename = $base_Dir . $filename;
    $tmpdir = uniqid('install_');
    $extractdir = $base_Dir . $tmpdir;
    //$archivename 	= mosPathName( $archivename;
    //echo $archivename;
    //$this->unpackDir( $extractdir );
    if (preg_match('/.zip$/', $archivename)) {
        // Extract functions
        require_once $absolute_path . '/administrator/components/com_swmenufree/pcl/pclzip.lib.php';
        require_once $absolute_path . '/administrator/components/com_swmenufree/pcl/pclerror.lib.php';
        require_once $absolute_path . '/administrator/components/com_swmenufree/pcl/pcltrace.lib.php';
        //require_once( $absolute_path . '/administrator/includes/pcl/pcltar.lib.php' );
        $zipfile = new PclZip($archivename);
        //if($this->isWindows()) {
        //		define('OS_WINDOWS',1);
        //	} else {
        //		define('OS_WINDOWS',0);
        //	}
        $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
        if ($ret == 0) {
            //$this->setError( 1, 'Unrecoverable error "'.$zipfile->errorName(true).'"' );
            return false;
        }
    } else {
        require_once $absolute_path . '/administrator/components/com_swmenufree/pcl/Tar.php';
        $archive = new Archive_Tar($archivename);
        $archive->setErrorHandling(PEAR_ERROR_PRINT);
        if (!$archive->extractModify($extractdir, '')) {
            $this->setError(1, 'Extract Error');
            return false;
        }
    }
    return $extractdir;
}
示例#10
0
 /**
  * Decompress a tar archive of a site.
  * 
  * @param string $archivePath
  * @param string $decompressDir
  * @return void
  * @access public
  * @since 3/14/08
  */
 public function decompressArchive($archivePath, $decompressDir)
 {
     if (!file_exists($archivePath)) {
         throw new Exception("Archive, '" . basename($archivePath) . "' does not exist.");
     }
     if (!is_readable($archivePath)) {
         throw new Exception("Archive, '" . basename($archivePath) . "' is not readable.");
     }
     // Decompress the archive into our temp-dir
     $archive = new Archive_Tar($archivePath);
     // Check for a containing directory and strip it if needed.
     $content = @$archive->listContent();
     if (!is_array($content) || !count($content)) {
         throw new Exception("Invalid Segue archive. '" . basename($archivePath) . "' is not a valid GZIPed Tar archive.");
     }
     $containerName = null;
     // 			printpre($content);
     if ($content[0]['typeflag'] == 5) {
         $containerName = trim($content[0]['filename'], '/') . '/';
         for ($i = 1; $i < count($content); $i++) {
             // if one of the files isn't in the container, then we don't have a container of all
             if (strpos($content[$i]['filename'], $containerName) === false) {
                 $containerName = null;
                 break;
             }
         }
     }
     // 			printpre($containerName);
     $decompressResult = @$archive->extractModify($decompressDir, $containerName);
     if (!$decompressResult) {
         throw new Exception("Could not decompress Segue archive: '" . basename($archivePath) . "' size, " . ByteSize::withValue(filesize($archivePath))->asString() . ".");
     }
     if (!file_exists($decompressDir . "/site.xml")) {
         throw new Exception("Invalid Segue archive. 'site.xml' was not found in '" . implode("', '", scandir($decompressDir)) . "'.");
     }
 }
 /**
  * Extract files from an archive using pclzip.lib.php or Archive_Tar.php
  *
  * @param string  $path  archive path
  * @param array $archiver
  * @return bool
  */
 protected function PhpExtract($path, $archiver)
 {
     // create archive object
     @ini_set('memory_limit', '256M');
     switch ($archiver['ext']) {
         case 'zip':
             include 'pclzip.lib.php';
             $archive = new PclZip($path);
             break;
         case 'tbz':
         case 'tgz':
         case 'tar':
             include 'Archive_Tar.php';
             $archive = new Archive_Tar($path);
             break;
         default:
             return $this->setError('Unknown archive type');
     }
     $list = $archive->listContent();
     if (!count($list)) {
         return $this->setError('Empty Archive');
     }
     // destination path .. determine if we need to create a folder for the files in the archive
     $root_names = $this->ArchiveRoots($list);
     $extract_args = array();
     $remove_path = '';
     if (count($root_names) > 1) {
         $dest = $this->ArchiveDestination($path);
     } elseif (count($list) == 1) {
         //$dest = dirname($path);
         $dest = $this->ArchiveDestination($path);
         //not ideal, but the listing is updated this way
     } else {
         $name = array_shift($root_names);
         $remove_path = $name;
         $dest = $this->IncrementName(dirname($path), $name);
     }
     // extract
     switch ($archiver['ext']) {
         case 'zip':
             if (!$archive->extract($dest, $remove_path)) {
                 return $this->setError('Extract Failed');
             }
             break;
         case 'tbz':
         case 'tgz':
         case 'tar':
             if (!$archive->extractModify($dest, $remove_path)) {
                 return $this->setError('Extract Failed');
             }
             break;
     }
     return $dest;
 }
示例#12
0
 function upload_save($redirect = true)
 {
     global $my, $mainframe, $database, $option, $priTask, $subTask;
     global $WBG_CONFIG, $wbGalleryDB_cat, $wbGallery_common, $wbGallery_eng;
     // Prepare Runtime
     $tempDir = null;
     $known_images = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/gif');
     $time = time();
     // Importing
     $importFolder = mosGetParam($_REQUEST, 'folder', '');
     if ($importFolder && !file_exists($importFolder)) {
         echo "<script> alert('Import Folder Does Not Exist'); document.location.href='index2.php?option=" . $option . "&task=image.upload'; </script>\n";
         exit;
     }
     // Default Values
     $defRow = new wbGalleryDB_img($database);
     $defRow->bind($_POST);
     // Debug
     echo "Image Processing Start: " . $time . '<br/>';
     // ==============================v========================================
     // Single File Upload
     if (!empty($_FILES['img']['tmp_name'])) {
         // Debug
         echo "Single File Detected <br/>";
         if (!in_array($_FILES['img']['type'], $known_images)) {
             echo "<script> alert('Image type: " . $_FILES['img']['type'] . " is an unknown type'); document.location.href='index2.php?option=" . $option . "&task=image.upload'; </script>\n";
             exit;
         }
         $wbGallery_eng->add($_FILES['img']['tmp_name'], $_FILES['img']['name'], $_FILES['img']['type'], $defRow);
         if ($redirect) {
             mosRedirect('index2.php?option=' . $option . '&task=image.upload', 'Image Saved');
         }
     }
     // ==============================v========================================
     // Zip File Upload
     if (!empty($_FILES['zip']['tmp_name'])) {
         //zip file upload
         // Debug
         echo "Compressed File Uploaded <br/>";
         // Create / Define Temporary Folder for Unzipped Files
         if (!mkdir($mainframe->getCfg('absolute_path') . '/media/' . $time)) {
             if (!mkdir('/tmp/' . $time)) {
                 echo "<script> alert('Unable to Create Temp Directory'); history.back(); </script>\n";
                 exit;
             } else {
                 $tempDir = '/tmp/' . $time;
             }
         } else {
             $tempDir = $mainframe->getCfg('absolute_path') . '/media/' . $time;
         }
         // Uncompress ZIP or TAR.GZ
         if (preg_match('/zip$/i', $_FILES['zip']['name'])) {
             // Load ZIP functions
             require_once $mainframe->getCfg('absolute_path') . '/administrator/includes/pcl/pclzip.lib.php';
             require_once $mainframe->getCfg('absolute_path') . '/administrator/includes/pcl/pclerror.lib.php';
             $zipfile = new PclZip($_FILES['zip']['tmp_name']);
             if (substr(PHP_OS, 0, 3) == 'WIN') {
                 define('OS_WINDOWS', 1);
             } else {
                 define('OS_WINDOWS', 0);
             }
             $ret = $zipfile->extract(PCLZIP_OPT_PATH, $tempDir);
             if ($ret == 0) {
                 $wbGallery_common->remove_dir($tempDir);
                 echo "<script> alert('ZIP Extraction Error: " . $zipfile->errorName(true) . "'); history.back(); </script>\n";
                 exit;
             }
         } elseif (preg_match('/tar.gz$/i', $_FILES['zip']['name'])) {
             // Load TAR functions
             require_once $mainframe->getCfg('absolute_path') . '/includes/Archive/Tar.php';
             $archive = new Archive_Tar($_FILES['zip']['tmp_name']);
             $archive->setErrorHandling(PEAR_ERROR_PRINT);
             if (!$archive->extractModify($tempDir, '')) {
                 $wbGallery_common->remove_dir($tempDir);
                 echo "<script> alert('TAR Extraction Error'); history.back(); </script>\n";
                 exit;
             }
         } else {
             // Unknown File...
             $wbGallery_common->remove_dir($tempDir);
             echo "<script> alert('Unknown File Format - Must be .ZIP or .TAR.GZ'); history.back(); </script>\n";
             exit;
         }
     }
     // Zip File Upload
     // ==============================v========================================
     // Process Files from Folder
     if ($tempDir || $importFolder) {
         $processDirs = array();
         $files_added = 0;
         $files_skipped = 0;
         if ($tempDir) {
             $processDirs[] = array('path' => $tempDir, 'remove' => 1);
         }
         if ($importFolder) {
             $processDirs[] = array('path' => $importFolder, 'remove' => 0);
         }
         if (count($processDirs)) {
             foreach ($processDirs as $procDir) {
                 // Read Files from Temp Folder
                 $regImg = array();
                 foreach ($known_images as $k) {
                     $regImg[] = preg_replace('/^.*\\//', '', $k) . '$';
                 }
                 $regStr = '/' . join('|', $regImg) . '/';
                 $files = $wbGallery_common->find_files($procDir['path'], $regStr);
                 unset($regImg);
                 unset($regStr);
                 // Debug
                 echo "Unzipped " . count($files) . " for processing <br/>";
                 if (count($files)) {
                     foreach ($files as $file) {
                         $filePath = $file['path'] . '/' . $file['name'];
                         $res = getimagesize($filePath);
                         $fileType = $res['mime'];
                         if (in_array($fileType, $known_images)) {
                             if ($wbGallery_eng->add($filePath, $file['name'], $fileType, $defRow)) {
                                 $files_added++;
                             } else {
                                 $files_skipped++;
                             }
                         } else {
                             $files_skipped++;
                         }
                     }
                 }
                 if ($procDir['remove']) {
                     $wbGallery_common->remove_dir($procDir['path']);
                 }
             }
             // foreach processDirs
         }
         // if processDirs
         if ($redirect) {
             if (!$files_added && !$files_skipped) {
                 mosRedirect('index2.php?option=' . $option . '&task=image.upload', 'Error: No Files were Processed or Error Finding Files');
             } else {
                 mosRedirect('index2.php?option=' . $option . '&task=image.upload', $files_added . ' images added - ' . $files_skipped . ' files skipped');
             }
         } else {
             if (!$files_added && !$files_skipped) {
                 return false;
             } else {
                 return true;
             }
         }
     }
     mosRedirect('index2.php?option=' . $option . '&task=image.upload', 'Please Specify Images for Processing');
     return false;
 }
示例#13
0
 function pullAndro()
 {
     ob_start();
     x_EchoFlush("Obtaining information about Node Manager");
     $info = SQL_AllRows("Select n.node_url\n            from applications a\n            join nodes        n ON a.node = n.node\n           where a.application='andro'");
     if (count($info) == 0) {
         x_EchoFlush("ERROR!  There is no entry for the node manager!");
         return;
     }
     // Pull the two pieces we need to know
     $URL = $info[0]['node_url'];
     x_EchoFlush("We will pull latest code from:");
     x_EchoFlush("  {$URL}");
     $URL = "http://" . $URL . "/andro/pages/public_downloads/";
     x_EchoFlush("Complete URL will be:");
     x_EchoFlush("  {$URL}");
     x_EchoFlush("Requesting name of latest file from remote URL");
     $URL_req = $URL . "latest_filename.php";
     x_EchoFlush(" Complete request string is " . $URL_req);
     $filename = file_get_contents($URL_req);
     x_EchoFLush("Remote URL reports latest file is: {$filename}");
     x_EchoFlush("Beginning download of {$filename}");
     $file = file_get_contents($URL . $filename);
     x_EchoFlush("Download complete. Filesize is " . strlen($file) . ' bytes');
     $fileapps = $GLOBALS['AG']['dirs']['root'] . "pkg-apps";
     $filespec = $GLOBALS['AG']['dirs']['root'] . "pkg-apps/{$filename}";
     // KFD 7/25/07, this does not appear on windows systems
     if (!file_exists($fileapps)) {
         mkdir($fileapps);
     }
     x_EchoFlush("Saving as {$filespec}");
     x_EchoFlush("Bytes written: " . file_put_contents($filespec, $file));
     // Here is the extraction code
     x_EchoFlush("Extracting locally");
     require_once "Archive/Tar.php";
     $tar = new Archive_Tar($filespec, 'gz');
     $tar->extract($fileapps);
     // Protect flag
     $protect = strtolower(Option_Get("NM_PROTECT"));
     if (in_array($protect, array('yes', 'true', 'y'))) {
         x_EchoFlush("");
         x_EchoFlush("ERROR!");
         x_EchoFlush("The system variable NM_PROTECT has value -{$protect}-");
         x_EchoFlush("This prevents any overwriting of node manager code");
         x_EchoFlush("On this node.  This is an undocumented option and");
         x_EchoFlush("would not normally be set by accident.");
         return;
     }
     // If we didn't abort because we're Ken's laptop, expand
     // directly over the currently running node manager.
     //
     x_echoFlush("Unpacking with PEAR Archive_Tar library.");
     $filedest = $GLOBALS['AG']['dirs']['root'];
     $remove_path = basename($filespec, ".tgz");
     $tar->extractModify($filedest, $remove_path);
     x_EchoFlush("Done");
     echo ob_get_clean();
 }
 /**
  * プラグインアーカイブを解凍する.
  *
  * @param  string  $path アーカイブパス
  * @return boolean Archive_Tar::extractModify()のエラー
  */
 public function unpackPluginArchive($path)
 {
     // 圧縮フラグTRUEはgzip解凍をおこなう
     $tar = new Archive_Tar($path, true);
     $dir = dirname($path);
     $file_name = basename($path);
     // 指定されたフォルダ内に解凍する
     $result = $tar->extractModify($dir . '/', '');
     GC_Utils_Ex::gfPrintLog("解凍: {$path} -> {$dir}");
     // 解凍元のファイルを削除する.
     unlink($path);
     return $result;
 }
示例#15
0
 /**
  *
  * Extract theme from archive
  * @throws Exception
  * @param string $source_path archive path
  *
  * @return waTheme
  */
 public static function extract($source_path)
 {
     $autoload = waAutoload::getInstance();
     $autoload->add('Archive_Tar', 'wa-installer/lib/vendors/PEAR/Tar.php');
     $autoload->add('PEAR', 'wa-installer/lib/vendors/PEAR/PEAR.php');
     if (class_exists('Archive_Tar')) {
         try {
             $tar_object = new Archive_Tar($source_path, true);
             $files = $tar_object->listContent();
             if (!$files) {
                 self::throwArchiveException('INVALID_OR_EMPTY_ARCHIVE');
             }
             //search theme info
             $theme_check_files = array(self::PATH);
             $theme_files_map = array();
             $info = false;
             $pattern = "/(\\/|^)" . wa_make_pattern(self::PATH) . "\$/";
             foreach ($files as $file) {
                 if (preg_match($pattern, $file['filename'])) {
                     $info = $tar_object->extractInString($file['filename']);
                     break;
                 }
             }
             if (!$info) {
                 self::throwThemeException('MISSING_THEME_XML');
             }
             $xml = @simplexml_load_string($info);
             $app_id = (string) $xml['app'];
             $id = (string) $xml['id'];
             if (!$app_id) {
                 self::throwThemeException('MISSING_APP_ID');
             } elseif (!$id) {
                 self::throwThemeException('MISSING_THEME_ID');
             } else {
                 if ($app_info = wa()->getAppInfo($app_id)) {
                     //TODO check theme support
                 } else {
                     $message = sprintf(_w('Theme “%s” is for app “%s”, which is not installed in your Webasyst. Install the app, and upload theme once again.'), $id, $app_id);
                     throw new waException($message);
                 }
             }
             $wa_path = "wa-apps/{$app_id}/themes/{$id}";
             $wa_pattern = wa_make_pattern($wa_path);
             $file = reset($files);
             if (preg_match("@^{$wa_pattern}(/|\$)@", $file['filename'])) {
                 $extract_path = $wa_path;
                 $extract_pattern = $wa_pattern;
             } else {
                 $extract_path = $id;
                 $extract_pattern = wa_make_pattern($id);
                 if (!preg_match("@^{$extract_pattern}(/|\$)@", $file['filename'])) {
                     $extract_path = '';
                     $extract_pattern = false;
                 }
             }
             foreach ($files as $file) {
                 if ($extract_pattern && !preg_match("@^{$extract_pattern}(/|\$)@", $file['filename'])) {
                     self::throwThemeException('UNEXPECTED_FILE_PATH', "{$file['filename']}. Expect files in [{$extract_path}] directory");
                 } elseif (preg_match('@\\.(php\\d*|pl)@', $file['filename'], $matches)) {
                     self::throwThemeException('UNEXPECTED_FILE_TYPE', $file['filename']);
                 }
             }
             self::verify($id);
             self::protect($app_id);
             $target_path = wa()->getDataPath("themes/{$id}", true, $app_id, false);
             waFiles::delete($target_path);
             if ($extract_path && !$tar_object->extractModify($target_path, $extract_path)) {
                 self::throwArchiveException('INTERNAL_ARCHIVE_ERROR');
             } elseif (!$tar_object->extract($target_path)) {
                 self::throwArchiveException('INTERNAL_ARCHIVE_ERROR');
             }
             $instance = new self($id, $app_id);
             $instance->check();
         } catch (Exception $ex) {
             if (isset($target_path) && $target_path) {
                 waFiles::delete($target_path, true);
             }
             throw $ex;
         }
     } else {
         self::throwArchiveException('UNSUPPORTED_ARCHIVE_TYPE');
     }
     return $instance;
 }
示例#16
0
文件: stage.php 项目: rair/yacs
        include_once '../shared/zipfile.php';
        $zipfile = new zipfile();
        // extract archive components and save them in mentioned directory --strip yacs from path, if any
        if ($count = $zipfile->explode($id, 'scripts/staging', 'yacs/')) {
            $context['text'] .= '<p>' . sprintf(i18n::s('%d files have been extracted.'), $count) . "</p>\n";
            $success = TRUE;
        } else {
            Logger::error(sprintf(i18n::s('Nothing has been extracted from %s.'), $external_id));
        }
        // ensure we have the external library to explode other kinds of archives
    } elseif (!is_readable('../included/tar.php')) {
        Logger::error(i18n::s('Impossible to extract files.'));
    } else {
        include_once $context['path_to_root'] . 'included/tar.php';
        $handle = new Archive_Tar($id);
        if ($handle->extractModify($context['path_to_root'] . 'scripts/staging', 'yacs')) {
            $success = TRUE;
        } else {
            Logger::error(sprintf(i18n::s('Impossible to complete update of the staging store from %s'), basename($external_id)));
        }
    }
    // everything went fine
    if ($success) {
        $context['text'] .= '<p>' . i18n::s('The staging directory has been updated.') . '</p>';
        // forward to the update script
        $context['text'] .= '<form method="get" action="' . $context['url_to_root'] . 'scripts/update.php">' . "\n" . '<p>' . Skin::build_submit_button(i18n::s('Review staged scripts before the update')) . '</p>' . "\n" . '</form>' . "\n";
    }
    // contact remote server
} elseif (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
    // purge the staging directory
    $context['text'] .= '<p>' . i18n::s('Purging old staging files...') . BR . "\n";
示例#17
0
 /**
  * Extracts the package archive file
  * @return boolean True on success, False on error
  */
 function extractArchive()
 {
     global $mosConfig_absolute_path;
     $base_Dir = mosPathName($mosConfig_absolute_path . '/media');
     $archivename = $base_Dir . $this->installArchive();
     $tmpdir = uniqid('install_');
     $extractdir = mosPathName($base_Dir . $tmpdir);
     $archivename = mosPathName($archivename, false);
     $this->unpackDir($extractdir);
     if (eregi('.zip$', $archivename)) {
         // Extract functions
         require_once $mosConfig_absolute_path . '/administrator/includes/pcl/pclzip.lib.php';
         require_once $mosConfig_absolute_path . '/administrator/includes/pcl/pclerror.lib.php';
         //require_once( $mosConfig_absolute_path . '/administrator/includes/pcl/pcltrace.lib.php' );
         //require_once( $mosConfig_absolute_path . '/administrator/includes/pcl/pcltar.lib.php' );
         $zipfile = new PclZip($archivename);
         if ($this->isWindows()) {
             define('OS_WINDOWS', 1);
         } else {
             define('OS_WINDOWS', 0);
         }
         $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
         if ($ret == 0) {
             $this->setError(1, 'Unrecoverable error "' . $zipfile->errorName(true) . '"');
             return false;
         }
     } else {
         require_once $mosConfig_absolute_path . '/includes/Archive/Tar.php';
         $archive = new Archive_Tar($archivename);
         $archive->setErrorHandling(PEAR_ERROR_PRINT);
         if (!$archive->extractModify($extractdir, '')) {
             $this->setError(1, 'Extract Error');
             return false;
         }
     }
     $this->installDir($extractdir);
     // Try to find the correct install dir. in case that the package have subdirs
     // Save the install dir for later cleanup
     $filesindir = mosReadDirectory($this->installDir(), '');
     if (count($filesindir) == 1) {
         if (is_dir($extractdir . $filesindir[0])) {
             $this->installDir(mosPathName($extractdir . $filesindir[0]));
         }
     }
     return true;
 }
 /**
  * tarアーカイブを解凍する.
  *
  * @param string $path アーカイブパス
  * @return boolean Archive_Tar::extractModify()のエラー
  */
 function unpackFile($path)
 {
     // 圧縮フラグTRUEはgzip解凍をおこなう
     $tar = new Archive_Tar($path, true);
     $dir = dirname($path);
     $file_name = basename($path);
     // 拡張子を切り取る
     $unpacking_name = preg_replace("/(\\.tar|\\.tar\\.gz)\$/", '', $file_name);
     // 指定されたフォルダ内に解凍する
     $result = $tar->extractModify($dir . '/', $unpacking_name);
     GC_Utils_Ex::gfPrintLog('解凍:' . $dir . '/' . $file_name . '->' . $dir . '/' . $unpacking_name);
     // フォルダ削除
     SC_Helper_FileManager_Ex::deleteFile($dir . '/' . $unpacking_name);
     // 圧縮ファイル削除
     unlink($path);
     return $result;
 }
 /**
  * Extracts the package archive file
  * @return boolean True on success, False on error
  */
 function extractArchive()
 {
     global $_CB_framework;
     $base_Dir = _cbPathName($_CB_framework->getCfg('tmp_path'));
     $archivename = $this->installArchive();
     $tmpdir = uniqid('install_');
     $extractdir = _cbPathName($base_Dir . $tmpdir);
     $archivename = _cbPathName($archivename, false);
     $this->unpackDir($extractdir);
     if (preg_match("/\\.zip\$/i", $archivename)) {
         // Extract functions
         cbimport('pcl.pclziplib');
         $zipfile = new PclZip($archivename);
         if ($this->isWindows()) {
             define('OS_WINDOWS', 1);
         } else {
             define('OS_WINDOWS', 0);
         }
         $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
         if ($ret == 0) {
             $this->setError(1, 'Unrecoverable error "' . $zipfile->errorName(true) . '"');
             return false;
         }
     } else {
         cbimport('pcl.tar');
         // includes/Archive/Tar.php' );
         $archive = new Archive_Tar($archivename);
         $archive->setErrorHandling(PEAR_ERROR_PRINT);
         if (!$archive->extractModify($extractdir, '')) {
             $this->setError(1, 'Extract Error');
             return false;
         }
     }
     $this->installDir($extractdir);
     // Try to find the correct install dir. in case that the package have subdirs
     // Save the install dir for later cleanup
     $filesindir = cbReadDirectory($this->installDir(), '');
     if (count($filesindir) == 1) {
         if (is_dir($extractdir . $filesindir[0])) {
             $this->installDir(_cbPathName($extractdir . $filesindir[0]));
         }
     }
     return true;
 }
示例#20
0
 /**
  * Extracts the package archive file
  * @return boolean True on success, False on error
  */
 public function extractArchive()
 {
     $base_Dir = JPath::clean(JPATH_BASE . '/media');
     $archivename = $base_Dir . $this->_realname;
     $tmpdir = uniqid('install_');
     $extractdir = JPath::clean($base_Dir . $tmpdir);
     $archivename = JPath::clean($archivename, false);
     $this->_unpackdir = $extractdir;
     if (preg_match('/.zip$/', $archivename)) {
         // Extract functions
         require_once JPATH_ADMINISTRATOR . '/includes/pcl/pclzip.lib.php';
         require_once JPATH_ADMINISTRATOR . '/includes/pcl/pclerror.lib.php';
         $zipfile = new PclZip($this->_uploadfile);
         if ($this->_iswin) {
             define('OS_WINDOWS', 1);
         } else {
             define('OS_WINDOWS', 0);
         }
         $ret = $zipfile->extract(PCLZIP_OPT_PATH, $extractdir);
         if ($ret == 0) {
             $this->errno = 1;
             $this->error = 'Unrecoverable error "' . $zipfile->errorName(true) . '"';
             return false;
         }
     } else {
         require_once JPATH_SITE . '/includes/Archive/Tar.php';
         $archive = new Archive_Tar($this->_uploadfile);
         $archive->setErrorHandling(PEAR_ERROR_PRINT);
         if (!$archive->extractModify($extractdir, '')) {
             $this->setError(1, 'Extract Error');
             return false;
         }
     }
     // Try to find the correct install dir. in case that the package have subdirs
     // Save the install dir for later cleanup
     jimport('joomla.filesystem.folder');
     $this->_uploadfile = JFolder::files($extractdir, '');
     if (count($this->_uploadfile) == 1) {
         if (is_dir($extractdir . $this->_uploadfile[0])) {
             $this->_unpackdir = JPath::clean($extractdir . $this->_uploadfile[0]);
             $this->_uploadfile = JFolder::files($extractdir, '');
         }
     }
     return true;
 }
示例#21
0
 /**
  * tarアーカイブを解凍する.
  *
  * @param string $path アーカイブパス
  * @return string Archive_Tar::extractModify()のエラー
  */
 function unpackFile($path)
 {
     // 圧縮フラグTRUEはgzip解凍をおこなう
     $tar = new Archive_Tar($path, true);
     $dir = dirname($path);
     $file_name = basename($path);
     // 拡張子を切り取る
     $unpacking_name = preg_replace("/(\\.tar|\\.tar\\.gz)\$/", "", $file_name);
     // 指定されたフォルダ内に解凍する
     $tar->extractModify($dir . "/", $unpacking_name);
     GC_Utils_Ex::gfPrintLog("解凍:" . $dir . "/" . $file_name . "->" . $dir . "/" . $unpacking_name);
     // フォルダ削除
     SC_Utils::sfDelFile($dir . "/" . $unpacking_name);
     // 圧縮ファイル削除
     unlink($path);
 }
示例#22
0
    }
    $packages[] = $entry;
}
if (!empty($required)) {
    die('Following packages were not available in tar format in go-pear-tarballs: ' . implode(', ', $required) . "\n");
}
if (!file_exists("{$tardir}/tmp")) {
    mkdir("{$tardir}/tmp");
}
// Use the tar files for required Phar files
require_once 'Archive/Tar.php';
require_once 'System.php';
foreach ($packages as $package) {
    $name = substr($package, 0, -4);
    $tar = new Archive_Tar("{$tardir}/{$package}");
    $tar->extractModify("{$tardir}/tmp", $name);
}
chdir(__DIR__);
$pkg = new PEAR_PackageFile($config);
$pf = $pkg->fromPackageFile($tardir . '/tmp/package2.xml', PEAR_VALIDATE_NORMAL);
if (PEAR::isError($pf)) {
    foreach ($pf->getUserInfo() as $warn) {
        echo $warn['message'] . "\n";
    }
    die($pf->getMessage());
}
$pearver = $pf->getVersion();
$creator = new PHP_Archive_Creator('index.php', $outputFile);
// no compression
$creator->useDefaultFrontController('PEAR.php');
$creator->useSHA1Signature();
示例#23
0
 public function install()
 {
     G::LoadSystem('inputfilter');
     $filter = new InputFilter();
     //echo "Starting core installation...\n";
     $start = microtime(1);
     $filename = $this->addon->getDownloadFilename();
     $time = microtime(1);
     G::LoadThirdParty('pear/Archive', 'Tar');
     $archive = new Archive_Tar($filename);
     //printf("Time to open archive: %f\n", microtime(1) - $time);
     $time = microtime(1);
     $extractDir = dirname($this->addon->getDownloadFilename()) . "/extract";
     $extractDir = $filter->xssFilterHard($extractDir);
     $backupDir = dirname($this->addon->getDownloadFilename()) . "/backup";
     $backupDir = $filter->xssFilterHard($backupDir);
     if (file_exists($extractDir)) {
         G::rm_dir($extractDir);
     }
     if (file_exists($backupDir)) {
         G::rm_dir($backupDir);
     }
     if (!is_dir($backupDir)) {
         mkdir($backupDir);
     }
     //printf("Time to remove old directory: %f\n", microtime(1) - $time);
     $time = microtime(1);
     echo "Extracting files...\n";
     $archive->extractModify($extractDir, 'processmaker');
     //printf("Time to extract all files: %f\n", microtime(1) - $time);
     //$time = microtime(1);
     //$files = $archive->listContent();
     //printf("Time to get list of contents: %f\n", microtime(1) - $time);
     /*$time = microtime(1);
       foreach ($files as $fileinfo)
         if (basename($fileinfo['filename']) == 'checksum.txt') {
           $checksumFile = $archive->extractInString($fileinfo['filename']);
           break;
         }
       printf("Time to get checksum.txt: %f\n", microtime(1) - $time);
       */
     $checksumFile = file_get_contents("{$extractDir}/checksum.txt");
     $time = microtime(1);
     $checksums = array();
     foreach (explode("\n", $checksumFile) as $line) {
         $checksums[trim(substr($line, 33))] = substr($line, 0, 32);
     }
     //printf("Time to assemble list of checksums: %f\n", microtime(1) - $time);
     $checksum = array();
     $changedFiles = array();
     $time = microtime(1);
     $files = ls_dir($extractDir);
     //printf("Time to list files: %f\n", microtime(1) - $time);
     echo "Updating ProcessMaker files...\n";
     $time = microtime(1);
     $checksumTime = 0;
     foreach ($checksums as $filename => $checksum) {
         if (is_dir("{$extractDir}/{$filename}")) {
             $filename = $filter->xssFilterHard($filename);
             print $filename;
             continue;
         }
         $installedFile = PATH_TRUNK . "/{$filename}";
         if (!file_exists($installedFile)) {
             $installedMD5 = "";
         } else {
             $time = microtime(1);
             $installedMD5 = G::encryptFileOld($installedFile);
             $checksumTime += microtime(1) - $time;
         }
         $archiveMD5 = $checksum;
         if (strcasecmp($archiveMD5, $installedMD5) != 0) {
             $changedFiles[] = $filename;
             if (!is_dir(dirname($backupDir . '/' . $filename))) {
                 mkdir(dirname($backupDir . '/' . $filename), 0777, true);
             }
             if (file_exists($installedFile) && is_file($installedFile)) {
                 copy($installedFile, $backupDir . '/' . $filename);
             }
             if (!is_dir(dirname($installedFile))) {
                 mkdir(dirname($installedFile), 0777, true);
             }
             if (!copy("{$extractDir}/{$filename}", $installedFile)) {
                 throw new Exception("Could not overwrite '{$filename}'");
             }
         }
     }
     //printf("Time to create all checksums: %f\n", $checksumTime);
     //printf("Time to copy files: %f\n", microtime(1) - $time);
     printf("Updated %d files\n", count($changedFiles));
     printf("Clearing cache...\n");
     if (defined('PATH_C')) {
         G::rm_dir(PATH_C);
         mkdir(PATH_C, 0777, true);
     }
     $workspaces = System::listWorkspaces();
     $count = count($workspaces);
     $first = true;
     $num = 0;
     foreach ($workspaces as $index => $workspace) {
         try {
             $num += 1;
             printf("Upgrading workspaces ({$num}/{$count}): {$workspace->name}\n");
             $workspace->upgrade($first);
             $workspace->close();
             $first = false;
         } catch (Exception $e) {
             printf("Errors upgrading workspace {$workspace->name}: {$e->getMessage()}\n");
             //$errors = true;
         }
     }
     //printf("Time to install: %f\n", microtime(1) - $start);
 }