extract() public method

{{{ extract()
public extract ( $p_path = '' )
 public static function inflate($file, $outputPath)
 {
     // Sanity
     if (!file_exists($file) || !is_file($file) || strtolower(pathinfo($file, PATHINFO_EXTENSION)) != 'tar') {
         throw new Engine_Package_Exception('File does not exist or is not a tar file');
     }
     if (!file_exists($outputPath) || !is_dir($outputPath) || !is_writeable($outputPath)) {
         throw new Engine_Package_Exception('Output path does not exist, is not a directory, or is not writeable');
     }
     self::_loadArchiveClass();
     // Make other paths
     $outputSubPath = substr(basename($file), 0, strrpos(basename($file), '.'));
     $outputFullPath = rtrim($outputPath, '/\\') . DIRECTORY_SEPARATOR . $outputSubPath;
     // If output path already exists, remove
     if (file_exists($outputFullPath)) {
         self::_rmdirRecursive($outputFullPath, true);
     }
     // Try to make full output path
     if (!is_dir($outputFullPath)) {
         if (!mkdir($outputFullPath, 0777, true)) {
             throw new Engine_Package_Exception('Unable to create output folder');
         }
     }
     // Extract
     $archive = new Archive_Tar($file);
     $rval = $archive->extract($outputFullPath);
     // Throw error if failed
     if ($archive->isError($rval)) {
         throw new Engine_Package_Exception('Error in archive: ' . $rval->getMessage());
     }
     return $outputFullPath;
 }
 public function shakeDown()
 {
     $this->logTo = "echo";
     $s3 = Mage::helper('cloudbackup')->getS3Client();
     // Create the backup and send it to Amazon - don't clean up, otherwise they WILL be different...
     list($bucket_name, $key_name) = $this->createBackup(true, false);
     // Download it again - save it in /tmp
     $s3->getObject($bucket_name, $key_name, "/tmp" . DS . $key_name);
     // Extract it in /tmp
     $tar = new Archive_Tar("/tmp" . DS . $key_name);
     $tar->extract("/tmp/test") or die("Could not extract files!");
     // Diff it to check all the files are there - ignore errors about symlinks etc
     // TODO: why do we need to remove var/*
     // because cache and log entries can change during the running of this test...
     $output = exec("diff -rq . /tmp/test 2> /dev/null | grep -v var/");
     $this->log($output);
     // We expect only the uploaded backup to be different - because we do cleanup=false
     if ($output == "Only in .: " . $key_name) {
         echo "test passed\n";
         //clean up tmp we're all good
         exec("rm -f /tmp" . DS . $key_name);
         exec("rm -rf /tmp/test");
     } else {
         echo "test failed\n";
         // We don't clean up after a failure - so we can investigate...
     }
 }
function install($file)
{
    G::LoadThirdParty("pear/Archive", "Tar");
    $result = array();
    $status = 1;
    try {
        //Extract
        $tar = new Archive_Tar($file);
        $swTar = $tar->extract(PATH_OUTTRUNK);
        //true on success, false on error. //directory for extract
        //$swTar = $tar->extract(PATH_PLUGINS);
        if (!$swTar) {
            throw new Exception("Could not extract file.");
        }
        //Upgrade
        $option = array("http" => array("method" => "POST"));
        // Proxy settings
        $sysConf = System::getSystemConfiguration();
        if (isset($sysConf['proxy_host'])) {
            if ($sysConf['proxy_host'] != '') {
                if (!is_array($option['http'])) {
                    $option['http'] = array();
                }
                $option['http']['request_fulluri'] = true;
                $option['http']['proxy'] = 'tcp://' . $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '');
                if ($sysConf['proxy_user'] != '') {
                    if (!isset($option['http']['header'])) {
                        $option['http']['header'] = '';
                    }
                    $option['http']['header'] .= 'Proxy-Authorization: Basic ' . base64_encode($sysConf['proxy_user'] . ($sysConf['proxy_pass'] != '' ? ':' . $sysConf['proxy_pass'] : ''));
                }
            }
        }
        $context = stream_context_create($option);
        ///////
        $fileData = @fopen(EnterpriseUtils::getUrlServerName() . "/sys" . SYS_SYS . "/" . SYS_LANG . "/" . SYS_SKIN . "/enterprise/services/processMakerUpgrade", "rb", false, $context);
        if ($fileData === false) {
            throw new Exception("Could not open services url.");
        }
        $resultAux = G::json_decode(stream_get_contents($fileData));
        if ($resultAux->status == "OK") {
            $result["status"] = $resultAux->status;
            //OK
            $result["message"] = $resultAux->message;
        } else {
            throw new Exception($resultAux->message);
        }
    } catch (Exception $e) {
        $result["message"] = $e->getMessage();
        $status = 0;
    }
    if ($status == 0) {
        $result["status"] = "ERROR";
    }
    return $result;
}
Example #4
0
 public static function expand($path)
 {
     $path = realpath($path);
     $dir = dirname($path);
     #print ">> $path\n";
     $arch = new Archive_Tar($path, true);
     $arch->setErrorHandling(PEAR_ERROR_PRINT);
     if (false === $arch->extract($dir)) {
         throw new Pfw_Exception_Script(Pfw_Exception_Script::E_ARCHIVE_UNKNOWN);
     }
 }
 function archive_extract($path, $archive_dir, $config = array())
 {
     $result = FALSE;
     if (class_exists('Archive_Tar')) {
         if (file_safe(path_concat($archive_dir, 'file.txt'), $config)) {
             $tar = new Archive_Tar($path);
             $tar->extract($archive_dir);
             $result = file_exists($archive_dir);
         }
     }
     return $result;
 }
function extract_archive($path, $archive_dir)
{
    $result = FALSE;
    if (class_exists('Archive_Tar')) {
        if (safe_path($archive_dir)) {
            $tar = new Archive_Tar($path);
            $tar->extract(dirname($archive_dir));
            $result = file_exists($archive_dir);
        }
    }
    return $result;
}
 public function installFromFile($file)
 {
     require_once "/var/www/localhost/htdocs/papyrine/libraries/PEAR.php";
     require_once "/var/www/localhost/htdocs/papyrine/libraries/Archive_Tar.php";
     $tar = new Archive_Tar($file, 'bz2');
     $about = $tar->extractInString("about.xml");
     $xml = simplexml_load_string($about);
     $dir = "/var/www/localhost/htdocs/papyrine/data/plugins/tmp/" . $xml->id . "/";
     if (!is_dir($dir)) {
         $tar->extract($dir);
     }
     $this->installFromDirectory($dir);
 }
Example #8
0
 /**
  * Method to extract an archived and/or compressed file
  *
  * @param  string $to
  * @return void
  */
 public function extract($to = null)
 {
     if ($this->compression == 'bz') {
         $this->path = Compress\Bzip2::decompress($this->path);
         $this->archive = new \Archive_Tar($this->path);
     } else {
         if ($this->compression == 'gz') {
             $this->path = Compress\Gzip::decompress($this->path);
             $this->archive = new \Archive_Tar($this->path);
         }
     }
     $this->archive->extract(null !== $to ? $to : './');
 }
 protected function _untarIntoTemp($path)
 {
     $original_dir = getcwd();
     //create a temp file, turn it into a directory
     $dir = tempnam('/tmp', 'mt2c');
     unlink($dir);
     mkdir($dir);
     chdir($dir);
     $tar = new Archive_Tar($path);
     $tar->extract('.');
     chdir($original_dir);
     return $dir;
 }
Example #10
0
 static function install($source, $filename)
 {
     $target = SIMPLE_EXT . substr($filename, 0, -3);
     setup::out("{t}Download{/t}: " . $source . " ...");
     if ($fz = gzopen($source, "r") and $fp = fopen($target, "w")) {
         $i = 0;
         while (!gzeof($fz)) {
             $i++;
             setup::out(".", false);
             if ($i % 160 == 0) {
                 setup::out();
             }
             fwrite($fp, gzread($fz, 16384));
         }
         gzclose($fz);
         fclose($fp);
     } else {
         sys_die("{t}Error{/t}: gzopen [2] " . $source);
     }
     setup::out();
     if (!file_exists($target) or filesize($target) == 0 or filesize($target) % 10240 != 0) {
         sys_die("{t}Error{/t}: file-check [3] Filesize: " . filesize($target) . " " . $target);
     }
     setup::out(sprintf("{t}Processing %s ...{/t}", basename($target)));
     $tar_object = new Archive_Tar($target);
     $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
     $tar_object->extract(SIMPLE_EXT);
     $file_list = $tar_object->ListContent();
     if (!is_array($file_list) or !isset($file_list[0]["filename"]) or !is_dir(SIMPLE_EXT . $file_list[0]["filename"])) {
         sys_die("{t}Error{/t}: tar [4] " . $target);
     }
     self::update_modules_list();
     $ext_folder = db_select_value("simple_sys_tree", "id", "anchor=@anchor@", array("anchor" => "extensions"));
     foreach ($file_list as $file) {
         sys_chmod(SIMPLE_EXT . $file["filename"]);
         setup::out(sprintf("{t}Processing %s ...{/t}", SIMPLE_EXT . $file["filename"]));
         if (basename($file["filename"]) == "install.php") {
             setup::out("");
             require SIMPLE_EXT . $file["filename"];
             setup::out("");
         }
         if (basename($file["filename"]) == "readme.txt") {
             $data = file_get_contents(SIMPLE_EXT . $file["filename"]);
             setup::out(nl2br("\n" . q($data) . "\n"));
         }
         if (!empty($ext_folder) and basename($file["filename"]) == "folders.xml") {
             setup::out(sprintf("{t}Processing %s ...{/t}", "folder structure"));
             folders::create_default_folders(SIMPLE_EXT . $file["filename"], $ext_folder, false);
         }
     }
 }
Example #11
0
 static function extract($target, $folder)
 {
     setup::out(sprintf("{t}Processing %s ...{/t}", basename($target)));
     $tar_object = new Archive_Tar($target);
     $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
     $tar_object->extract($folder);
     $file_list = $tar_object->ListContent();
     if (!is_array($file_list) or !isset($file_list[0]["filename"]) or !is_dir($folder . $file_list[0]["filename"])) {
         sys_die("{t}Error{/t}: tar [3] " . $target);
     }
     foreach ($file_list as $file) {
         sys_chmod($folder . $file["filename"]);
     }
     @unlink($target);
     return $folder . $file_list[0]["filename"];
 }
Example #12
0
 /**
  *  preprocess Index action.
  *
  *  @access    public
  *  @return    string  Forward name (null if no errors.)
  */
 function prepare()
 {
     if ($this->af->validate() == 0) {
         list($package, $version) = explode('@', $this->af->get('target_package'));
         $data_file = $this->backend->ctl->package2dataFile($package, $version);
         require_once 'Archive/Tar.php';
         $tar = new Archive_Tar($data_file, 'gz');
         $status = $tar->extract(dirname($data_file));
         /*			chdir(BASE.'/tmp');
         			exec('which tar', $which, $status);
         			$command = sprintf('%s xzf %s', $which[0], $data_file);
         			exec($command, $result, $status); */
         if ($status == 1) {
             return null;
         }
         $this->ae->add('extract_error', _('file extract error') . sprintf('[STATUS: %s]', $status));
     }
     return 'json_error_reload';
 }
Example #13
0
 /**
  * @param	string	The name of the archive file
  * @param	string	Directory to unpack into
  * @return	boolean	True for success
  */
 function extract($archivename, $extractdir)
 {
     require_once dirname(__FILE__) . '/file.php';
     require_once dirname(__FILE__) . '/folder.php';
     $untar = false;
     $result = false;
     $ext = extFile::getExt(strtolower($archivename));
     // check if a tar is embedded...gzip/bzip2 can just be plain files!
     if (extFile::getExt(extFile::stripExt(strtolower($archivename))) == 'tar') {
         $untar = true;
     }
     switch ($ext) {
         case 'tar':
         case 'tgz':
         case 'gz':
             // This may just be an individual file (e.g. sql script)
         // This may just be an individual file (e.g. sql script)
         case 'gzip':
         case 'tbz':
         case 'tbz2':
         case 'bz2':
             // This may just be an individual file (e.g. sql script)
         // This may just be an individual file (e.g. sql script)
         case 'bzip2':
             require_once dirname(__FILE__) . '/Tar.php';
             $archive = new Archive_Tar($archivename);
             $result = $archive->extract($extractdir);
             break;
             /*
             			default :
             				$adapter = & extArchive::getAdapter( $ext ) ;
             				if( $adapter ) {
             					$result = $adapter->extract( $archivename, $extractdir ) ;
             				} else {
             					return PEAR::raiseError('Unknown Archive Type: '.$ext );
             				}
             			break ;
             */
     }
     return $result;
 }
Example #14
0
function nc_tgz_extract($archive_name, $dst_path)
{
    global $DOCUMENT_ROOT;
    @set_time_limit(0);
    if (SYSTEM_TAR) {
        exec("cd {$DOCUMENT_ROOT}; tar -zxf {$archive_name} -C {$dst_path} 2>&1", $output, $err_code);
        if ($err_code && !strpos($output[0], "time")) {
            // ignore "can't utime, permission denied"
            trigger_error("{$output['0']}", E_USER_WARNING);
            return false;
        }
        return true;
    } else {
        $current_dir = realpath('.');
        chdir($DOCUMENT_ROOT);
        $tar_object = new Archive_Tar($archive_name, "gz");
        $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
        $result = $tar_object->extract($dst_path);
        chdir($current_dir);
        return $result;
    }
}
Example #15
0
 protected function extractTar($extractLocation)
 {
     if (!class_exists('Archive_Tar')) {
         return Result::errorMissingPackage($this, 'Archive_Tar', 'pear/archive_tar');
     }
     $tar_object = new \Archive_Tar($this->filename);
     if (!$tar_object->extract($extractLocation)) {
         return Result::error($this, "Could not extract tar archive {$this->filename}");
     }
     return Result::success($this);
 }
Example #16
0
 /**
  * Decompresses the given content
  *
  * @param  string $content
  * @return boolean
  */
 public function decompress($content)
 {
     $archive = $this->getArchive();
     if (file_exists($content)) {
         $archive = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, realpath($content));
     } elseif (empty($archive) || !file_exists($archive)) {
         require_once 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception('Tar Archive not found');
     }
     $archive = new Archive_Tar($archive, $this->getMode());
     $target = $this->getTarget();
     if (!is_dir($target)) {
         $target = dirname($target);
     }
     $result = $archive->extract($target);
     if ($result === false) {
         require_once 'Zend/Filter/Exception.php';
         throw new Zend_Filter_Exception('Error while extracting the Tar archive');
     }
     return true;
 }
Example #17
0
 /**
  * Page ć®ćƒ—ćƒ­ć‚»ć‚¹.
  *
  * @return void
  */
 public function process($mode)
 {
     $objLog = new LogHelper();
     $objLog->start($mode);
     $objJson = new JsonHelper();
     // ć‚¢ć‚Æć‚»ć‚¹ćƒć‚§ćƒƒć‚Æ
     $objLog->log('* auth start');
     if ($this->isValidAccess($mode) !== true) {
         // TODO
         $objJson->setError(OSTORE_E_C_INVALID_ACCESS);
         $objJson->display();
         $objLog->error(OSTORE_E_C_INVALID_ACCESS);
         return;
     }
     // ćƒ‘ćƒ©ćƒ”ćƒ¼ćƒć‚§ćƒƒć‚Æ
     $this->initParam();
     $objLog->log('* post param check start');
     $arrErr = $this->objForm->checkError();
     if ($arrErr) {
         $objJson->setError(OSTORE_E_C_INVALID_PARAM);
         $objJson->display();
         $objLog->error(OSTORE_E_C_INVALID_PARAM, $_POST);
         $objLog->log('* post param check error ' . print_r($arrErr, true));
         return;
     }
     $objLog->log('* auto update check start');
     if ($mode == 'auto_update' && $this->autoUpdateEnable($this->objForm->getValue('product_id')) !== true) {
         $objJson->setError(OSTORE_E_C_AUTOUP_DISABLE);
         $objJson->display();
         $objLog->error(OSTORE_E_C_AUTOUP_DISABLE, $_POST);
         return;
     }
     // TODO CSRFåƾē­–
     // čŖčØ¼ć‚­ćƒ¼ć®å–å¾—
     $public_key = $this->getPublicKey();
     $sha1_key = $this->createSeed();
     // čŖčØ¼ć‚­ćƒ¼ćƒć‚§ćƒƒć‚Æ
     $objLog->log('* public key check start');
     if (empty($public_key)) {
         $objJson->setError(OSTORE_E_C_NO_KEY);
         $objJson->display();
         $objLog->error(OSTORE_E_C_NO_KEY);
         return;
     }
     // ćƒŖć‚Æć‚Øć‚¹ćƒˆć‚’é–‹å§‹
     $objLog->log('* http request start');
     switch ($mode) {
         case 'patch_download':
             $arrPostData = array('eccube_url' => HTTP_URL, 'public_key' => sha1($public_key . $sha1_key), 'sha1_key' => $sha1_key, 'patch_code' => 'latest');
             break;
         default:
             $arrPostData = array('eccube_url' => HTTP_URL, 'public_key' => sha1($public_key . $sha1_key), 'sha1_key' => $sha1_key, 'product_id' => $this->objForm->getValue('product_id'));
             break;
     }
     $objReq = $this->request($mode, $arrPostData);
     // ćƒŖć‚Æć‚Øć‚¹ćƒˆćƒć‚§ćƒƒć‚Æ
     $objLog->log('* http request check start');
     if (\PEAR::isError($objReq)) {
         $objJson->setError(OSTORE_E_C_HTTP_REQ);
         $objJson->display();
         $objLog->error(OSTORE_E_C_HTTP_REQ, $objReq);
         return;
     }
     // ćƒ¬ć‚¹ćƒćƒ³ć‚¹ćƒć‚§ćƒƒć‚Æ
     $objLog->log('* http response check start');
     if ($objReq->getResponseCode() !== 200) {
         $objJson->setError(OSTORE_E_C_HTTP_RESP);
         $objJson->display();
         $objLog->error(OSTORE_E_C_HTTP_RESP, $objReq);
         return;
     }
     $body = $objReq->getResponseBody();
     $objRet = $objJson->decode($body);
     // JSONćƒ‡ćƒ¼ć‚æć®ćƒć‚§ćƒƒć‚Æ
     $objLog->log('* json data check start');
     if (empty($objRet)) {
         $objJson->setError(OSTORE_E_C_FAILED_JSON_PARSE);
         $objJson->display();
         $objLog->error(OSTORE_E_C_FAILED_JSON_PARSE, $objReq);
         return;
     }
     // ćƒ€ć‚¦ćƒ³ćƒ­ćƒ¼ćƒ‰ćƒ‡ćƒ¼ć‚æ恮äæå­˜
     if ($objRet->status === OSTORE_STATUS_SUCCESS) {
         $objLog->log('* save file start');
         $time = time();
         $dir = DATA_REALDIR . 'downloads/tmp/';
         $filename = $time . '.tar.gz';
         $data = base64_decode($objRet->data->dl_file);
         $objLog->log("* open {$filename} start");
         if ($fp = @fopen($dir . $filename, 'w')) {
             @fwrite($fp, $data);
             @fclose($fp);
         } else {
             $objJson->setError(OSTORE_E_C_PERMISSION);
             $objJson->display();
             $objLog->error(OSTORE_E_C_PERMISSION, $dir . $filename);
             return;
         }
         // ćƒ€ć‚¦ćƒ³ćƒ­ćƒ¼ćƒ‰ć‚¢ćƒ¼ć‚«ć‚¤ćƒ–ć‚’å±•é–‹ć™ć‚‹
         $exract_dir = $dir . $time;
         $objLog->log("* mkdir {$exract_dir} start");
         if (!@mkdir($exract_dir)) {
             $objJson->setError(OSTORE_E_C_PERMISSION);
             $objJson->display();
             $objLog->error(OSTORE_E_C_PERMISSION, $exract_dir);
             return;
         }
         $objLog->log("* extract {$dir}{$filename} start");
         $tar = new Archive_Tar($dir . $filename);
         $tar->extract($exract_dir);
         $objLog->log('* copy batch start');
         $objBatch = new BatchUpdate();
         $arrCopyLog = $objBatch->execute($exract_dir);
         $objLog->log('* copy batch check start');
         if (count($arrCopyLog['err']) > 0) {
             $objJson->setError(OSTORE_E_C_BATCH_ERR);
             $objJson->display();
             $objLog->error(OSTORE_E_C_BATCH_ERR, $arrCopyLog);
             $this->registerUpdateLog($arrCopyLog, $objRet->data);
             $this->updateMdlTable($objRet->data);
             return;
         }
         // dtb_module_update_log恮ꛓꖰ
         $objLog->log('* insert dtb_module_update start');
         $this->registerUpdateLog($arrCopyLog, $objRet->data);
         // dtb_module恮ꛓꖰ
         $objLog->log('* insert/update dtb_module start');
         $this->updateMdlTable($objRet->data);
         // DBę›“ę–°ćƒ•ć‚”ć‚¤ćƒ«ć®čŖ­ćæč¾¼ćæć€å®Ÿč”Œ
         $objLog->log('* file execute start');
         $this->fileExecute($objRet->data->product_code);
         // 配äæ”ć‚µćƒ¼ćƒćƒ¼ćø通ēŸ„
         $objLog->log('* notify to lockon server start');
         $objReq = $this->notifyDownload($mode, $objReq->getResponseCookies());
         $objLog->log('* dl commit result:' . serialize($objReq));
         $productData = $objRet->data;
         $productData->dl_file = '';
         $objJson->setSUCCESS($productData, 'ć‚¤ćƒ³ć‚¹ćƒˆćƒ¼ćƒ«/ć‚¢ćƒƒćƒ—ćƒ‡ćƒ¼ćƒˆć«ęˆåŠŸć—ć¾ć—ćŸć€‚');
         $objJson->display();
         $objLog->end();
         return;
     } else {
         // 配äæ”ć‚µćƒ¼ćƒćƒ¼å“ć§ć‚Øćƒ©ćƒ¼ć‚’č£œč¶³
         echo $body;
         $objLog->error($objRet->errcode, $objReq);
         return;
     }
 }
 /**
  * 惐惃ć‚Æć‚¢ćƒƒćƒ—ćƒ•ć‚”ć‚¤ćƒ«ć‚’ćƒŖć‚¹ćƒˆć‚¢ć™ć‚‹
  *
  * @param string $bkup_name
  * @param string $bkup_dir
  * @param string $bkup_ext
  * @return void
  */
 function lfRestore($bkup_name, $bkup_dir, $bkup_ext, $mode)
 {
     $objQuery =& SC_Query_Ex::getSingletonInstance();
     $bkup_filepath = $bkup_dir . $bkup_name . $bkup_ext;
     $work_dir = $bkup_dir . $bkup_name . '/';
     //圧ēø®ćƒ•ćƒ©ć‚°TRUEćÆgzipč§£å‡ć‚’ćŠć“ćŖ恆
     $tar = new Archive_Tar($bkup_filepath, TRUE);
     //ęŒ‡å®šć•ć‚ŒćŸćƒ•ć‚©ćƒ«ćƒ€å†…ć«č§£å‡ć™ć‚‹
     $success = $tar->extract($work_dir);
     if (!$success) {
         $msg = '惐惃ć‚Æć‚¢ćƒƒćƒ—ćƒ•ć‚”ć‚¤ćƒ«ć®å±•é–‹ć«å¤±ę•—ć—ć¾ć—ćŸć€‚' . "\n";
         $msg .= '展開元: ' . $bkup_filepath . "\n";
         $msg .= '展開先: ' . $work_dir;
         trigger_error($msg, E_USER_ERROR);
     }
     // ćƒˆćƒ©ćƒ³ć‚¶ć‚Æć‚·ćƒ§ćƒ³é–‹å§‹
     $objQuery->begin();
     // INSERTå®Ÿč”Œ
     $success = $this->lfExeInsertSQL($objQuery, $work_dir, $mode);
     // ć‚·ćƒ¼ć‚±ćƒ³ć‚¹ē”Ÿęˆå™Øć‚’å¾©å…ƒć™ć‚‹
     if ($success) {
         $this->restoreSequence($objQuery, $work_dir . 'autoinc_data.csv');
     }
     // ćƒŖć‚¹ćƒˆć‚¢ęˆåŠŸćŖć‚‰ć‚³ćƒŸćƒƒćƒˆå¤±ę•—ćŖć‚‰ćƒ­ćƒ¼ćƒ«ćƒćƒƒć‚Æ
     if ($success) {
         $objQuery->commit();
         $this->tpl_restore_err = true;
     } else {
         $objQuery->rollback();
         $this->tpl_restore_name = $bkup_name;
     }
     // FIXME 恓恮č¾ŗ悊恧态惐惃ć‚Æć‚¢ćƒƒćƒ—ę™‚ćØ同ē­‰ć®äø€ę™‚ćƒ•ć‚”ć‚¤ćƒ«ć®å‰Šé™¤ć‚’å®Ÿč”Œć™ć¹ćć§ćÆ?
     SC_Utils_Ex::extendTimeOut();
     return $success;
 }
 protected function _installLanguages($xml, $install_mode = false)
 {
     $attributes = array();
     if (isset($xml->languages->language)) {
         foreach ($xml->languages->language as $data) {
             $attributes = $data->attributes();
             if (Language::getIdByIso($attributes['iso_code'])) {
                 continue;
             }
             $native_lang = Language::getLanguages();
             $native_iso_code = array();
             foreach ($native_lang as $lang) {
                 $native_iso_code[] = $lang['iso_code'];
             }
             if (in_array((string) $attributes['iso_code'], $native_iso_code) and !$install_mode or !in_array((string) $attributes['iso_code'], $native_iso_code)) {
                 $errno = 0;
             }
             $errstr = '';
             if (@fsockopen('www.prestashop.com', 80, $errno, $errstr, 10)) {
                 if ($lang_pack = Tools::jsonDecode(Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . _PS_VERSION_ . '&iso_lang=' . $attributes['iso_code']))) {
                     if ($content = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/' . $lang_pack->version . '/' . $attributes['iso_code'] . '.gzip')) {
                         $file = _PS_TRANSLATIONS_DIR_ . $attributes['iso_code'] . '.gzip';
                         if (file_put_contents($file, $content)) {
                             $gz = new Archive_Tar($file, true);
                             if (!$gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false)) {
                                 $this->_errors[] = Tools::displayError('Cannot decompress the translation file of the language: ') . (string) $attributes['iso_code'];
                                 return false;
                             }
                             if (!Language::checkAndAddLanguage((string) $attributes['iso_code'])) {
                                 $this->_errors[] = Tools::displayError('An error occurred while creating the language: ') . (string) $attributes['iso_code'];
                                 return false;
                             }
                             @unlink($file);
                         } else {
                             $this->_errors[] = Tools::displayError('Server does not have permissions for writing.');
                         }
                     }
                 } else {
                     $this->_errors[] = Tools::displayError('Error occurred when language was checked according to your Prestashop version.');
                 }
             } else {
                 $this->_errors[] = Tools::displayError('Archive cannot be downloaded from prestashop.com.');
             }
         }
     }
     // change the default language if there is only one language in the localization pack
     if (!sizeof($this->_errors) and $install_mode and isset($attributes['iso_code']) and sizeof($xml->languages->language) == 1) {
         $this->iso_code_lang = $attributes['iso_code'];
     }
     return true;
 }
 protected function extractArchive($file, $redirect = true)
 {
     $zip_folders = array();
     $tmp_folder = _PS_MODULE_DIR_ . md5(time());
     $success = false;
     if (substr($file, -4) == '.zip') {
         if (Tools::ZipExtract($file, $tmp_folder)) {
             $zip_folders = scandir($tmp_folder);
             if (Tools::ZipExtract($file, _PS_MODULE_DIR_)) {
                 $success = true;
             }
         }
     } else {
         require_once _PS_TOOL_DIR_ . 'tar/Archive_Tar.php';
         $archive = new Archive_Tar($file);
         if ($archive->extract($tmp_folder)) {
             $zip_folders = scandir($tmp_folder);
             if ($archive->extract(_PS_MODULE_DIR_)) {
                 $success = true;
             }
         }
     }
     if (!$success) {
         $this->errors[] = Tools::displayError('There was an error while extracting the module (file may be corrupted).');
     } else {
         //check if it's a real module
         foreach ($zip_folders as $folder) {
             if (!in_array($folder, array('.', '..', '.svn', '.git', '__MACOSX')) && !Module::getInstanceByName($folder)) {
                 $this->errors[] = sprintf(Tools::displayError('The module %1$s that you uploaded is not a valid module.'), $folder);
                 $this->recursiveDeleteOnDisk(_PS_MODULE_DIR_ . $folder);
             }
         }
     }
     @unlink($file);
     $this->recursiveDeleteOnDisk($tmp_folder);
     if ($success && $redirect) {
         Tools::redirectAdmin(self::$currentIndex . '&conf=8&anchor=' . ucfirst($folder) . '&token=' . $this->token);
     }
     return $success;
 }
 public function submitAddLang()
 {
     global $currentIndex;
     $arr_import_lang = explode('|', Tools::getValue('params_import_language'));
     /* 0 = Language ISO code, 1 = PS version */
     if (Validate::isLangIsoCode($arr_import_lang[0])) {
         if ($content = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/' . $arr_import_lang[1] . '/' . $arr_import_lang[0] . '.gzip', false, @stream_context_create(array('http' => array('method' => 'GET', 'timeout' => 5))))) {
             $file = _PS_TRANSLATIONS_DIR_ . $arr_import_lang[0] . '.gzip';
             if (file_put_contents($file, $content)) {
                 $gz = new Archive_Tar($file, true);
                 $files_list = $gz->listContent();
                 if ($gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false)) {
                     $this->checkAndAddMailsFiles($arr_import_lang[0], $files_list);
                     if (!Language::checkAndAddLanguage($arr_import_lang[0])) {
                         $conf = 20;
                     }
                     if (!unlink($file)) {
                         $this->_errors[] = Tools::displayError('Cannot delete archive');
                     }
                     Tools::redirectAdmin($currentIndex . '&conf=' . (isset($conf) ? $conf : '15') . '&token=' . $this->token);
                 }
                 $this->_errors[] = Tools::displayError('Archive cannot be extracted.');
                 if (!unlink($file)) {
                     $this->_errors[] = Tools::displayError('Cannot delete archive');
                 }
             } else {
                 $this->_errors[] = Tools::displayError('Server does not have permissions for writing.');
             }
         } else {
             $this->_errors[] = Tools::displayError('Language not found');
         }
     } else {
         $this->_errors[] = Tools::displayError('Invalid parameter');
     }
 }
Example #22
0
function importSkin()
{
    try {
        if (!isset($_FILES['uploadedFile'])) {
            throw new Exception(G::LoadTranslation('ID_SKIN_FILE_REQUIRED'));
        }
        $uploadedInstances = count($_FILES['uploadedFile']['name']);
        $sw_error = false;
        $sw_error_exists = isset($_FILES['uploadedFile']['error']);
        $emptyInstances = 0;
        $quequeUpload = array();
        // upload files & check for errors
        $tmp = $_FILES['uploadedFile']['tmp_name'];
        $items = stripslashes($_FILES['uploadedFile']['name']);
        if ($sw_error_exists) {
            $up_err = $_FILES['uploadedFile']['error'];
        } else {
            $up_err = file_exists($tmp) ? 0 : 4;
        }
        if ($items == "" || $up_err == 4) {
            throw new Exception(G::LoadTranslation('ID_SKIN_FILE_REQUIRED'));
        }
        if ($up_err == 1 || $up_err == 2) {
            throw new Exception(G::LoadTranslation('ID_FILE_TOO_BIG'));
            //$errors[$i]='miscfilesize';
        }
        if ($up_err == 3) {
            throw new Exception(G::LoadTranslation('ID_ERROR_UPLOAD_FILE_CONTACT_ADMINISTRATOR'));
            //$errors[$i]='miscfilepart';
        }
        if (!@is_uploaded_file($tmp)) {
            throw new Exception(G::LoadTranslation('ID_ERROR_UPLOAD_FILE_CONTACT_ADMINISTRATOR'));
            //$errors[$i]='uploadfile';
        }
        $fileInfo = pathinfo($items);
        $validType = array('tar', 'gz');
        if (!in_array($fileInfo['extension'], $validType)) {
            throw new Exception(G::LoadTranslation('ID_FILE_UPLOAD_INCORRECT_EXTENSION'));
            //$errors[$i]='wrongtype';
        }
        $filename = $items;
        $tempPath = PATH_CUSTOM_SKINS . '.tmp' . PATH_SEP;
        G::verifyPath($tempPath, true);
        $tempName = $tmp;
        G::uploadFile($tempName, $tempPath, $filename);
        G::LoadThirdParty('pear/Archive', 'Tar');
        $tar = new Archive_Tar($tempPath . $filename);
        $aFiles = $tar->listContent();
        $swConfigFile = false;
        foreach ($aFiles as $key => $val) {
            if (basename($val['filename']) == 'config.xml') {
                $skinName = dirname($val['filename']);
                $skinArray = explode("/", $skinName);
                if (count($skinArray) == 1) {
                    $swConfigFile = true;
                }
            }
        }
        if (!$swConfigFile) {
            @unlink(PATH_CUSTOM_SKINS . '.tmp' . PATH_SEP . $filename);
            throw new Exception(G::LoadTranslation('ID_SKIN_CONFIGURATION_MISSING'));
        }
        if (is_dir(PATH_CUSTOM_SKINS . $skinName)) {
            if (isset($_REQUEST['overwrite_files']) && $_REQUEST['overwrite_files'] == 'on') {
                G::rm_dir(PATH_CUSTOM_SKINS . $skinName, false);
            } else {
                throw new Exception(G::LoadTranslation('ID_SKIN_ALREADY_EXISTS'));
            }
        }
        $res = $tar->extract(PATH_CUSTOM_SKINS);
        if (!$res) {
            throw new Exception(G::LoadTranslation('ID_SKIN_ERROR_EXTRACTING'));
        }
        $configFileOriginal = PATH_CUSTOM_SKINS . $skinName . PATH_SEP . 'config.xml';
        $configFileFinal = PATH_CUSTOM_SKINS . $skinName . PATH_SEP . 'config.xml';
        $xmlConfiguration = file_get_contents($configFileOriginal);
        $workspace = $_REQUEST['workspace'] == 'global' ? '' : SYS_SYS;
        $xmlConfigurationObj = G::xmlParser($xmlConfiguration);
        $skinInformationArray = $xmlConfigurationObj->result["skinConfiguration"]["__CONTENT__"]["information"]["__CONTENT__"];
        if (isset($skinInformationArray["workspace"]["__VALUE__"])) {
            $workspace = $workspace != "" && !empty($skinInformationArray["workspace"]["__VALUE__"]) ? $skinInformationArray["workspace"]["__VALUE__"] . "|" . $workspace : $workspace;
            $xmlConfiguration = preg_replace("/(<workspace>)(.*)(<\\/workspace>)/i", "<workspace>" . $workspace . "</workspace><!-- \$2 -->", $xmlConfiguration);
        } else {
            $xmlConfiguration = preg_replace("/(<name>)(.*)(<\\/name>)/i", "<name>" . $skinName . "</name><!-- \$2 -->\n<workspace>" . $workspace . "</workspace>", $xmlConfiguration);
        }
        file_put_contents($configFileFinal, $xmlConfiguration);
        //Delete Temporal
        @unlink(PATH_CUSTOM_SKINS . '.tmp' . PATH_SEP . $filename);
        $response['success'] = true;
        $response['message'] = G::LoadTranslation('ID_SKIN_SUCCESSFUL_IMPORTED');
        G::auditLog("ImportSkin", "Skin Name: " . $skinName);
        print_r(G::json_encode($response));
    } catch (Exception $e) {
        $response['success'] = false;
        $response['message'] = $e->getMessage();
        $response['error'] = $e->getMessage();
        print_r(G::json_encode($response));
    }
}
Example #23
0
 /**
  * Extract the archive into a specific directory
  *
  * @param string $path The directory in which to extract the file
  * @param string|array $files The file(s) to extract from the archive. If empty, it will extract the entire archive content
  *
  * @return boolean If the operation was successful
  */
 public function extract($path, $files = array())
 {
     return empty($files) ? $this->tar->extract($path) : $this->tar->extractList($files, $path);
 }
        if (!JArchive::extract($filename, JPATH_SITE)) {
            HTML_jupgrader::showError('Failed to extract archive!');
            return false;
        }
        break;
    case JUPDATEMAN_EXTRACTOR_15:
        jimport('joomla.filesystem.archive');
        if (!JArchive::extract($filename, JPATH_SITE)) {
            HTML_jupgrader::showError('Failed to extract archive!');
            return false;
        }
        break;
    case JUPDATEMAN_EXTRACTOR_PEAR:
        jimport('pear.archive_tar.Archive_Tar');
        $extractor = new Archive_Tar($filename);
        if (!$extractor->extract(JPATH_SITE)) {
            HTML_jupgrader::showError('Failed to extract archive!');
            return false;
        }
        break;
}
$installation = JPATH_SITE . DS . 'installation';
if (is_dir($installation)) {
    JFolder::delete($installation);
}
$cached_update = $params->get('cached_update', 0);
// delete the left overs unless cached update
if (!$cached_update) {
    if (is_file($filename)) {
        JFile::delete($filename);
    }
 /**
  * Install a plugin archive. If pluginName is specified, the archive will
  * only be installed if it contains this plugin.
  *
  * @return bool true if enabled, false otherwise
  */
 function installPluginArchive($filename, $pluginName)
 {
     G::LoadThirdParty("pear/Archive", "Tar");
     $tar = new Archive_Tar($filename);
     $files = $tar->listContent();
     $plugins = array();
     $namePlugin = array();
     foreach ($files as $f) {
         //if (preg_match("/^([\w\.]*).ini$/", $f["filename"], $matches)) {
         if (preg_match("/^(.*pluginConfig)\\.ini\$/", $f["filename"], $matches)) {
             $plugins[] = $matches[1];
         }
         if (preg_match("/^.*({$pluginName})\\.php\$/", $f["filename"], $matches)) {
             $namePlugin[] = $matches[1];
         }
     }
     if (count($plugins) > 1) {
         throw new Exception("Multiple plugins in one archive are not supported currently");
     }
     //if (isset($pluginName) && !in_array($pluginName, $plugins)) {
     if (isset($pluginName) && !in_array($pluginName, $namePlugin)) {
         throw new Exception("Plugin '{$pluginName}' not found in archive");
     }
     //$pluginName = $plugins[0];
     $pluginFile = "{$pluginName}.php";
     /*
     $oldPluginStatus = $this->getStatusPlugin($pluginFile);
     
     if ($pluginStatus != 0) {
       $oldDetails = $this->getPluginDetails($pluginFile);
       $oldVersion = $oldDetails->iVersion;
     } else {
       $oldDetails = NULL;
       $oldVersion = NULL;
     }
     */
     //$pluginIni = $tar->extractInString("$pluginName.ini");
     //$pluginConfig = parse_ini_string($pluginIni);
     /*
     if (!empty($oClass->aDependences)) {
       foreach ($oClass->aDependences as $aDependence) {
         if (file_exists(PATH_PLUGINS . $aDependence['sClassName'] . '.php')) {
           require_once PATH_PLUGINS . $aDependence['sClassName'] . '.php';
           if (!$oPluginRegistry->getPluginDetails($aDependence['sClassName'] . '.php')) {
             throw new Exception('This plugin needs "' . $aDependence['sClassName'] . '" plugin');
           }
         }
         else {
           throw new Exception('This plugin needs "' . $aDependence['sClassName'] . '" plugin');
         }
       }
     }
     unset($oClass);
     if ($fVersionOld > $fVersionNew) {
       throw new Exception('A recent version of this plugin was already installed.');
     }
     */
     $res = $tar->extract(PATH_PLUGINS);
     if (!file_exists(PATH_PLUGINS . $pluginFile)) {
         throw new Exception("File \"{$pluginFile}\" doesn't exist");
     }
     require_once PATH_PLUGINS . $pluginFile;
     $details = $this->getPluginDetails($pluginFile);
     $this->installPlugin($details->sNamespace);
     $this->setupPlugins();
     $this->enablePlugin($details->sNamespace);
     $this->save();
 }
Example #26
0
 /**
  * Installs the files within the package file specified.
  *
  * @param string|PEAR_Downloader_Package $pkgfile path to the package file,
  *        or a pre-initialized packagefile object
  * @param array $options
  * recognized options:
  * - installroot   : optional prefix directory for installation
  * - force         : force installation
  * - register-only : update registry but don't install files
  * - upgrade       : upgrade existing install
  * - soft          : fail silently
  * - nodeps        : ignore dependency conflicts/missing dependencies
  * - alldeps       : install all dependencies
  * - onlyreqdeps   : install only required dependencies
  *
  * @return array|PEAR_Error package info if successful
  */
 function install($pkgfile, $options = array())
 {
     $this->_options = $options;
     $this->_registry =& $this->config->getRegistry();
     if (is_object($pkgfile)) {
         $dlpkg =& $pkgfile;
         $pkg = $pkgfile->getPackageFile();
         $pkgfile = $pkg->getArchiveFile();
         $descfile = $pkg->getPackageFile();
         $tmpdir = dirname($descfile);
     } else {
         $descfile = $pkgfile;
         $tmpdir = '';
         if (PEAR::isError($pkg =& $this->_parsePackageXml($descfile, $tmpdir))) {
             return $pkg;
         }
     }
     if (realpath($descfile) != realpath($pkgfile)) {
         $tar = new Archive_Tar($pkgfile);
         if (!@$tar->extract($tmpdir)) {
             return $this->raiseError("unable to unpack {$pkgfile}");
         }
     }
     $pkgname = $pkg->getName();
     $channel = $pkg->getChannel();
     if (isset($this->_options['packagingroot'])) {
         $packrootphp_dir = $this->_prependPath($this->config->get('php_dir', null, $channel), $this->_options['packagingroot']);
     }
     if (isset($options['installroot'])) {
         $this->config->setInstallRoot($options['installroot']);
         $this->_registry =& $this->config->getRegistry();
         $installregistry =& $this->_registry;
         $this->installroot = '';
         // all done automagically now
         $php_dir = $this->config->get('php_dir', null, $channel);
     } else {
         $this->config->setInstallRoot(false);
         $this->_registry =& $this->config->getRegistry();
         if (isset($this->_options['packagingroot'])) {
             $installregistry =& new PEAR_Registry($packrootphp_dir);
             $php_dir = $packrootphp_dir;
         } else {
             $installregistry =& $this->_registry;
             $php_dir = $this->config->get('php_dir', null, $channel);
         }
         $this->installroot = '';
     }
     // {{{ checks to do when not in "force" mode
     if (empty($options['force']) && @is_dir($this->config->get('php_dir'))) {
         $testp = $channel == 'pear.php.net' ? $pkgname : array($channel, $pkgname);
         $instfilelist = $pkg->getInstallationFileList(true);
         if (PEAR::isError($instfilelist)) {
             return $instfilelist;
         }
         $test = $installregistry->checkFileMap($instfilelist, $testp, '1.1');
         if (PEAR::isError($test)) {
             return $test;
         }
         if (sizeof($test)) {
             $pkgs = $this->getInstallPackages();
             $found = false;
             foreach ($pkgs as $param) {
                 if ($pkg->isSubpackageOf($param)) {
                     $found = true;
                     break;
                 }
             }
             if ($found) {
                 // subpackages can conflict with earlier versions of parent packages
                 $parentreg = $installregistry->packageInfo($param->getPackage(), null, $param->getChannel());
                 $tmp = $test;
                 foreach ($tmp as $file => $info) {
                     if (is_array($info)) {
                         if (strtolower($info[1]) == strtolower($param->getPackage()) && strtolower($info[0]) == strtolower($param->getChannel())) {
                             unset($test[$file]);
                             unset($parentreg['filelist'][$file]);
                         }
                     } else {
                         if (strtolower($param->getChannel()) != 'pear.php.net') {
                             continue;
                         }
                         if (strtolower($info) == strtolower($param->getPackage())) {
                             unset($test[$file]);
                             unset($parentreg['filelist'][$file]);
                         }
                     }
                 }
                 $pfk =& new PEAR_PackageFile($this->config);
                 $parentpkg =& $pfk->fromArray($parentreg);
                 $installregistry->updatePackage2($parentpkg);
             }
             if ($param->getChannel() == 'pecl.php.net' && isset($options['upgrade'])) {
                 $tmp = $test;
                 foreach ($tmp as $file => $info) {
                     if (is_string($info)) {
                         // pear.php.net packages are always stored as strings
                         if (strtolower($info) == strtolower($param->getPackage())) {
                             // upgrading existing package
                             unset($test[$file]);
                         }
                     }
                 }
             }
             if (sizeof($test)) {
                 $msg = "{$channel}/{$pkgname}: conflicting files found:\n";
                 $longest = max(array_map("strlen", array_keys($test)));
                 $fmt = "%{$longest}s (%s)\n";
                 foreach ($test as $file => $info) {
                     if (!is_array($info)) {
                         $info = array('pear.php.net', $info);
                     }
                     $info = $info[0] . '/' . $info[1];
                     $msg .= sprintf($fmt, $file, $info);
                 }
                 if (!isset($options['ignore-errors'])) {
                     return $this->raiseError($msg);
                 } else {
                     if (!isset($options['soft'])) {
                         $this->log(0, "WARNING: {$msg}");
                     }
                 }
             }
         }
     }
     // }}}
     $this->startFileTransaction();
     if (empty($options['upgrade']) && empty($options['soft'])) {
         // checks to do only when installing new packages
         if ($channel == 'pecl.php.net') {
             $test = $installregistry->packageExists($pkgname, $channel);
             if (!$test) {
                 $test = $installregistry->packageExists($pkgname, 'pear.php.net');
             }
         } else {
             $test = $installregistry->packageExists($pkgname, $channel);
         }
         if (empty($options['force']) && $test) {
             return $this->raiseError("{$channel}/{$pkgname} is already installed");
         }
     } else {
         $usechannel = $channel;
         if ($channel == 'pecl.php.net') {
             $test = $installregistry->packageExists($pkgname, $channel);
             if (!$test) {
                 $test = $installregistry->packageExists($pkgname, 'pear.php.net');
                 $usechannel = 'pear.php.net';
             }
         } else {
             $test = $installregistry->packageExists($pkgname, $channel);
         }
         if ($test) {
             $v1 = $installregistry->packageInfo($pkgname, 'version', $usechannel);
             $v2 = $pkg->getVersion();
             $cmp = version_compare("{$v1}", "{$v2}", 'gt');
             if (empty($options['force']) && !version_compare("{$v2}", "{$v1}", 'gt')) {
                 return $this->raiseError("upgrade to a newer version ({$v2} is not newer than {$v1})");
             }
             if (empty($options['register-only'])) {
                 // when upgrading, remove old release's files first:
                 if (PEAR::isError($err = $this->_deletePackageFiles($pkgname, $usechannel, true))) {
                     if (!isset($options['ignore-errors'])) {
                         return $this->raiseError($err);
                     } else {
                         if (!isset($options['soft'])) {
                             $this->log(0, 'WARNING: ' . $err->getMessage());
                         }
                     }
                 } else {
                     $backedup = $err;
                 }
             }
         }
     }
     // {{{ Copy files to dest dir ---------------------------------------
     // info from the package it self we want to access from _installFile
     $this->pkginfo =& $pkg;
     // used to determine whether we should build any C code
     $this->source_files = 0;
     $savechannel = $this->config->get('default_channel');
     if (empty($options['register-only']) && !is_dir($php_dir)) {
         if (PEAR::isError(System::mkdir(array('-p'), $php_dir))) {
             return $this->raiseError("no installation destination directory '{$php_dir}'\n");
         }
     }
     $tmp_path = dirname($descfile);
     if (substr($pkgfile, -4) != '.xml') {
         $tmp_path .= DIRECTORY_SEPARATOR . $pkgname . '-' . $pkg->getVersion();
     }
     $this->configSet('default_channel', $channel);
     // {{{ install files
     if ($pkg->getPackagexmlVersion() == '2.0') {
         $filelist = $pkg->getInstallationFilelist();
     } else {
         $filelist = $pkg->getFileList();
     }
     if (PEAR::isError($filelist)) {
         return $filelist;
     }
     $pkg->resetFilelist();
     $pkg->setLastInstalledVersion($installregistry->packageInfo($pkg->getPackage(), 'version', $pkg->getChannel()));
     foreach ($filelist as $file => $atts) {
         if ($pkg->getPackagexmlVersion() == '1.0') {
             $this->expectError(PEAR_INSTALLER_FAILED);
             $res = $this->_installFile($file, $atts, $tmp_path, $options);
             $this->popExpect();
         } else {
             $this->expectError(PEAR_INSTALLER_FAILED);
             $res = $this->_installFile2($pkg, $file, $atts, $tmp_path, $options);
             $this->popExpect();
         }
         if (PEAR::isError($res)) {
             if (empty($options['ignore-errors'])) {
                 $this->rollbackFileTransaction();
                 if ($res->getMessage() == "file does not exist") {
                     $this->raiseError("file {$file} in package.xml does not exist");
                 }
                 return $this->raiseError($res);
             } else {
                 if (!isset($options['soft'])) {
                     $this->log(0, "Warning: " . $res->getMessage());
                 }
             }
         }
         if ($res == PEAR_INSTALLER_OK) {
             // Register files that were installed
             $pkg->installedFile($file, $atts);
         }
     }
     // }}}
     // {{{ compile and install source files
     if ($this->source_files > 0 && empty($options['nobuild'])) {
         if (PEAR::isError($err = $this->_compileSourceFiles($savechannel, $pkg))) {
             return $err;
         }
     }
     // }}}
     if (isset($backedup)) {
         $this->_removeBackups($backedup);
     }
     if (!$this->commitFileTransaction()) {
         $this->rollbackFileTransaction();
         $this->configSet('default_channel', $savechannel);
         return $this->raiseError("commit failed", PEAR_INSTALLER_FAILED);
     }
     // }}}
     $ret = false;
     $installphase = 'install';
     $oldversion = false;
     // {{{ Register that the package is installed -----------------------
     if (empty($options['upgrade'])) {
         // if 'force' is used, replace the info in registry
         $usechannel = $channel;
         if ($channel == 'pecl.php.net') {
             $test = $installregistry->packageExists($pkgname, $channel);
             if (!$test) {
                 $test = $installregistry->packageExists($pkgname, 'pear.php.net');
                 $usechannel = 'pear.php.net';
             }
         } else {
             $test = $installregistry->packageExists($pkgname, $channel);
         }
         if (!empty($options['force']) && $test) {
             $oldversion = $installregistry->packageInfo($pkgname, 'version', $usechannel);
             $installregistry->deletePackage($pkgname, $usechannel);
         }
         $ret = $installregistry->addPackage2($pkg);
     } else {
         $usechannel = $channel;
         if ($channel == 'pecl.php.net') {
             $test = $installregistry->packageExists($pkgname, $channel);
             if (!$test) {
                 $test = $installregistry->packageExists($pkgname, 'pear.php.net');
                 $usechannel = 'pear.php.net';
             }
         } else {
             $test = $installregistry->packageExists($pkgname, $channel);
         }
         // new: upgrade installs a package if it isn't installed
         if (!$test) {
             $ret = $installregistry->addPackage2($pkg);
         } else {
             if ($usechannel != $channel) {
                 $installregistry->deletePackage($pkgname, $usechannel);
                 $ret = $installregistry->addPackage2($pkg);
             } else {
                 $ret = $installregistry->updatePackage2($pkg);
             }
             $installphase = 'upgrade';
         }
     }
     if (!$ret) {
         $this->configSet('default_channel', $savechannel);
         return $this->raiseError("Adding package {$channel}/{$pkgname} to registry failed");
     }
     // }}}
     $this->configSet('default_channel', $savechannel);
     if (class_exists('PEAR_Task_Common')) {
         // this is auto-included if any tasks exist
         if (PEAR_Task_Common::hasPostinstallTasks()) {
             PEAR_Task_Common::runPostinstallTasks($installphase);
         }
     }
     return $pkg->toArray(true);
 }
Example #27
0
    public function checkAndAddLang($languages, $add = true)
    {
        $errors = '';
        $moduleName = Tools::getValue('moduleName');
        $this->alterTable('language');
        foreach ($languages as $language) {
            $iso = $language['iso_code'];
            if (!Language::isInstalled($iso)) {
                if ($add) {
                    if (@fsockopen('www.prestashop.com', 80)) {
                        if ($lang_pack = Tools::jsonDecode(Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version=' . _PS_VERSION_ . '&iso_lang=' . $iso))) {
                            if ($content = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/' . $lang_pack->version . '/' . $iso . '.gzip')) {
                                $file = _PS_TRANSLATIONS_DIR_ . $iso . '.gzip';
                                if (file_put_contents($file, $content)) {
                                    require_once '../../tools/tar/Archive_Tar.php';
                                    $gz = new Archive_Tar($file, true);
                                    if ($gz->extract(_PS_TRANSLATIONS_DIR_ . '../', false)) {
                                        if (!Language::checkAndAddLanguage($iso)) {
                                            $errors[] = $this->l('Archive cannot be extracted.');
                                        } else {
                                            $newId = Language::getIdByIso($iso);
                                            Db::getInstance()->execute('UPDATE  `' . _DB_PREFIX_ . 'lang`
																		SET  `id_lang_' . bqSQL($moduleName) . '` =  ' . (int) $language['id_lang'] . '
																		WHERE  `id_lang` = ' . (int) $newId);
                                        }
                                    }
                                    $errors[] = $this->l('Archive cannot be extracted.');
                                } else {
                                    $errors[] = $this->l('Server does not have permissions for writing.');
                                }
                            } else {
                                $errors[] = $this->l('Language not found');
                            }
                        } else {
                            $errors[] = $this->l('archive cannot be downloaded from prestashop.com.');
                        }
                    } else {
                        $errors[] = $this->l('archive cannot be downloaded from prestashop.com.');
                    }
                }
            } else {
                $newId = Language::getIdByIso($iso);
                Db::getInstance()->execute('UPDATE  `' . _DB_PREFIX_ . 'lang`
											SET  `id_lang_' . bqSQL($moduleName) . '` =  ' . (int) $language['id_lang'] . '
											WHERE  `id_lang` = ' . (int) $newId);
            }
        }
    }
Example #28
0
File: upload.php Project: rair/yacs
     include_once '../shared/zipfile.php';
     $zipfile = new zipfile();
     // extract archive components and save them in mentioned directory
     if ($count = $zipfile->explode($id, 'skins')) {
         $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.'), $name));
     }
     // 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->extract($context['path_to_root'] . 'skins')) {
         $success = TRUE;
     } else {
         Logger::error(sprintf(i18n::s('Error while processing %s.'), isset($name) ? $name : basename($id)));
     }
 }
 // everything went fine
 if ($success) {
     $context['text'] .= '<p>' . i18n::s('Congratulations, themes have been updated.') . '</p>' . '<p>' . i18n::s('You can now visit the index of themes, and select the one you prefer.') . '</p>';
     // display follow-up commands
     $menu = array('skins/' => i18n::s('Themes'));
     $context['text'] .= Skin::build_list($menu, 'menu_bar');
 }
 // clear the cache, to avoid side effects of complex updates
 $context['text'] .= Cache::clear();
 // ask for something to process, except on error
Example #29
0
 function stepUnpack(Am_BatchProcessor $batch)
 {
     foreach ($this->getSession()->upgrades as $k => $upgrade) {
         $upgrade->dir = null;
         if (!empty($upgrade->dir)) {
             continue;
         }
         // already unpacked?
         $record = $this->getDi()->uploadTable->load($upgrade->upload_id);
         $tar = new Archive_Tar($fn = $record->getFullPath());
         $upgrade->dir = DATA_DIR . DIRECTORY_SEPARATOR . $record->getFilename() . '-unpack';
         if (!mkdir($upgrade->dir)) {
             throw new Am_Exception_InputError("Could not create folder to unpack downloaded archive: [{$upgrade->dir}]");
             unset($upgrade->dir);
         }
         $tar->setErrorHandling(PEAR_ERROR_CALLBACK, array($this, '_tarError'));
         try {
             if (!$tar->extract($upgrade->dir)) {
                 throw new Am_Exception_InputError("Could not unpack downloaded archive: [{$fn}] to [{$upgrade->dir}]");
             }
         } catch (Exception $e) {
             $this->getDi()->errorLogTable->logException($e);
             unset($upgrade->dir);
             @rmdir($upgrade->dir);
         }
         // normally we delete uploaded archive
         $record->delete();
         unset($upgrade->upload_id);
     }
     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;
 }