/**
  * Extract resources to a file system path
  * 
  * @param Phar $phar Phar archive.
  * @param string $path Output path root.
  */
 protected function extractResources(Phar $phar, $path)
 {
     $this->deleteDirectory($path);
     $phar->extractTo($path);
     @unlink($path . '/index.php');
     @unlink($path . '/build.bat');
     $this->copyDirectory($path . '/resources', $path, false);
     $this->deleteDirectory($path . '/resources');
 }
Example #2
0
 /**
  * {@inheritDoc}
  */
 protected function extract($file, $path)
 {
     // Can throw an UnexpectedValueException
     $archive = new \Phar($file);
     $archive->extractTo($path, null, true);
     /* TODO: handle openssl signed phars
      * https://github.com/composer/composer/pull/33#issuecomment-2250768
      * https://github.com/koto/phar-util
      * http://blog.kotowicz.net/2010/08/hardening-php-how-to-securely-include.html
      */
 }
Example #3
0
function install($rootFolder)
{
    out('Installing');
    chdir("{$rootFolder}/");
    $phar = new Phar("{$rootFolder}/dashboard.phar");
    $phar->extractTo("{$rootFolder}/tmp/", null, true);
    system("mv {$rootFolder}/tmp/src/Hoborg/Dashboard/Resources/htdocs/index-phar.php {$rootFolder}/htdocs/index.php");
    system("mv {$rootFolder}/tmp/src/Hoborg/Dashboard/Resources/htdocs/static {$rootFolder}/htdocs/static");
    system("mv {$rootFolder}/tmp/src/Hoborg/Dashboard/Resources/htdocs/images {$rootFolder}/htdocs/images");
    system("rm -rf {$rootFolder}/tmp");
    return true;
}
Example #4
0
 /**
  * {@inheritdoc}
  */
 public function extract($file, $target, Format\FormatInterface $format)
 {
     $this->checkSupport($format);
     try {
         $phar = new \Phar($file);
         $this->getFilesystem()->mkdir($target);
         $phar->extractTo($target, null, true);
         return true;
     } catch (\Exception $e) {
         throw new FileCorruptedException($file);
     }
 }
Example #5
0
function extractComposer()
{
    if (file_exists('composer.phar')) {
        echo 'Extracting composer.phar ...' . PHP_EOL;
        flush();
        $composer = new Phar('composer.phar');
        $composer->extractTo('extracted');
        echo 'Extraction complete.' . PHP_EOL;
    } else {
        echo 'composer.phar does not exist';
    }
}
Example #6
0
 /**
  * Executes the current command.
  *
  * @param InputInterface  $input  An InputInterface instance
  * @param OutputInterface $output An OutputInterface instance
  *
  * @return null|int     null or 0 if everything went fine, or an error code
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('');
     $output->writeln('<comment>Extracting package</comment>');
     $this->validate($input, $output);
     $extractIn = $input->getOption('output');
     $rutaPhar = $input->getOption('phar');
     // $dir = Phar::running(false);
     $p = new \Phar($rutaPhar);
     $p->extractTo($extractIn, null, true);
     $output->writeln('');
     $output->writeln("<info>Phar extracted in </info>" . $extractIn);
 }
Example #7
0
 public static function installComposer()
 {
     if (!file_exists('composer/bin/composer')) {
         Tools::createDir('composer');
         if (!file_exists('composer/composer.phar')) {
             file_put_contents('composer/composerInstall.php', file_get_contents('https://getcomposer.org/installer'));
             $argv = ['install', '--install-dir', 'composer/'];
             header("Location: " . filter_input(INPUT_SERVER, 'REQUEST_URI'));
             include_once 'composer/composerInstall.php';
         }
         $composer = new Phar('composer/composer.phar');
         $composer->extractTo('composer/');
     }
 }
 /**
  * Extract the file from the phar archive to make it accessible for native commands.
  *
  * @param string $filePath  the absolute file path to extract
  * @param bool   $overwrite
  *
  * @return string
  */
 public static function extractFile($filePath, $overwrite = false)
 {
     $pharPath = \Phar::running(false);
     if (empty($pharPath)) {
         return '';
     }
     $relativeFilePath = substr($filePath, strpos($filePath, $pharPath) + strlen($pharPath) + 1);
     $tmpDir = sys_get_temp_dir() . '/jolinotif';
     $extractedFilePath = $tmpDir . '/' . $relativeFilePath;
     if (!file_exists($extractedFilePath) || $overwrite) {
         $phar = new \Phar($pharPath);
         $phar->extractTo($tmpDir, $relativeFilePath, $overwrite);
     }
     return $extractedFilePath;
 }
Example #9
0
 /**
  * Install an updated version of a cabin
  *
  * If we get to this point:
  *
  * 1. We know the signature is signed by the supplier.
  * 2. The hash was checked into Keyggdrasil, which
  *    was independently vouched for by our peers.
  *
  * @param UpdateInfo $info
  * @param UpdateFile $file
  * @throws CouldNotUpdate
  */
 protected function install(UpdateInfo $info, UpdateFile $file)
 {
     if (!$file->hashMatches($info->getChecksum())) {
         throw new CouldNotUpdate(\__('Checksum mismatched'));
     }
     $path = $file->getPath();
     $this->log('Begin Cabin updater', LogLevel::DEBUG, ['path' => $path, 'supplier' => $info->getSupplierName(), 'name' => $info->getPackageName()]);
     $updater = new \Phar($path, \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME);
     $updater->setAlias($this->pharAlias);
     $ns = $this->makeNamespace($info->getSupplierName(), $info->getPackageName());
     // We need to do this while we're replacing files.
     $this->bringCabinDown($ns);
     $oldMetadata = \Airship\loadJSON(ROOT . '/Cabin/' . $ns . '/manifest.json');
     // Overwrite files
     $updater->extractTo(ROOT . '/Cabin/' . $ns, null, true);
     // Run the update trigger.
     Sandbox::safeInclude('phar://' . $this->pharAlias . '/update_trigger.php', $oldMetadata);
     // Free up the updater alias
     $garbageAlias = Base64UrlSafe::encode(\random_bytes(33)) . '.phar';
     $updater->setAlias($garbageAlias);
     unset($updater);
     // Now bring it back up.
     $this->bringCabinBackUp($ns);
     // Make sure we update the version info. in the DB cache:
     $this->updateDBRecord('Cabin', $info);
     $this->log('Conclude Cabin updater', LogLevel::DEBUG, ['path' => $path, 'supplier' => $info->getSupplierName(), 'name' => $info->getPackageName()]);
     self::$continuumLogger->store(LogLevel::INFO, 'Cabin update installed', $this->getLogContext($info, $file));
 }
Example #10
0
#!/usr/bin/env php
<?php 
$phar = new Phar($argv[1]);
$phar->extractTo($argv[2]);
Example #11
0
 public function extractPharFile()
 {
     $phar = new \Phar(\Yii::getAlias('@tests/_runtime/yii2-phar/app.phar'));
     $phar->extractTo(\Yii::getAlias('@tests/_runtime/yii2-phar/extract'));
 }
Example #12
0
<?php

define('EXTRACT_DIRECTORY', realpath("../../"));
if (file_exists(EXTRACT_DIRECTORY . '/vendor/autoload.php') == true) {
    echo "Extracted autoload already exists. Skipping phar extraction as presumably it's already extracted.";
} else {
    $composerPhar = new Phar("composer.phar");
    //php.ini setting phar.readonly must be set to 0
    $composerPhar->extractTo(EXTRACT_DIRECTORY . '/vendor/');
}
//This requires the phar to have been extracted successfully.
require_once EXTRACT_DIRECTORY . '/vendor/vendor/autoload.php';
//Use the Composer classes
use Composer\Console\Application;
use Composer\Command\UpdateCommand;
use Symfony\Component\Console\Input\ArrayInput;
// change out of the webroot so that the vendors file is not created in
// a place that will be visible to the intahwebz
chdir('../');
//Create the commands
$input = new ArrayInput(array('command' => 'install'));
//Create the application and run it with the commands
$application = new Application();
$application->run($input);
Example #13
0
<?php

$fname = dirname(__FILE__) . '/tempmanifest2.phar.php';
$pname = 'phar://' . $fname;
$phar = new Phar($fname);
$phar->setDefaultStub();
$phar->setAlias('fred');
$phar['file1.txt'] = 'hi';
$phar['file2.txt'] = 'hi2';
$phar['subdir/ectory/file.txt'] = 'hi3';
$phar->mount($pname . '/mount2', __FILE__);
$phar->addEmptyDir('one/level');
$phar->extractTo(dirname(__FILE__) . '/extract2', 'mount2');
$phar->extractTo(dirname(__FILE__) . '/extract2');
$out = array();
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname(__FILE__) . '/extract2', 0x3000), RecursiveIteratorIterator::CHILD_FIRST) as $path => $file) {
    $extracted[] = $path;
}
sort($extracted);
foreach ($extracted as $out) {
    echo "{$out}\n";
}
?>
===DONE===
<?php 
@unlink(dirname(__FILE__) . '/tempmanifest2.phar.php');
$dir = dirname(__FILE__) . '/extract2/';
@unlink($dir . 'file1.txt');
@unlink($dir . 'file2.txt');
@unlink($dir . 'subdir/ectory/file.txt');
@rmdir($dir . 'subdir/ectory');
Example #14
0
             echo -2;
         }
         // Suppression du fichier
         unlink($lNomFichier);
     } else {
         echo 0;
     }
     break;
 case 4:
     // Déploiement du zeybux
     // vider le dossier d'extraction
     viderDossier(DOSSIER_EXTRACT, 1);
     // Création du phar
     $p = new Phar("./" . DOSSIER_UPLOAD . "/" . $_POST["phar"]);
     // Extraction de l'archive
     $p->extractTo(DOSSIER_EXTRACT);
     // Supression de l'ancien site excepté dossier maintenance, index.php, dossier configuration et Maintenance.php du dossier configuration
     // Pas de suppression des logs
     function supprimerDossier($pPath)
     {
         $d = dir($pPath);
         while (false !== ($entry = $d->read())) {
             if ($entry != '.' && $entry != '..' && $d->path . '/' . $entry != '../index.html' && $entry != "DB.php" && $entry != "LogLevel.php" && $entry != "Mail.php" && $entry != 'Maintenance.php' && $entry != "Proprietaire.php" && $entry != 'SOAP.php' && $entry != 'Titre.php' && $entry != 'Maintenance' && $entry != 'logs' && $entry != ".htaccess") {
                 if (is_dir($d->path . '/' . $entry)) {
                     supprimerDossier($d->path . '/' . $entry);
                     if ($entry != 'configuration' && $entry != 'classes' && $entry != 'html' && $entry != 'vues') {
                         rmdir($d->path . '/' . $entry);
                     }
                 } else {
                     $filename = $d->path . '/' . $entry;
                     unlink($filename);
<?php

$fname = dirname(__FILE__) . '/tempmanifest1.phar.php';
$pname = 'phar://' . $fname;
$a = new Phar($fname);
$a['file1.txt'] = 'hi';
$a['file2.txt'] = 'hi2';
$a['subdir/ectory/file.txt'] = 'hi3';
$a->mount($pname . '/mount', __FILE__);
$a->addEmptyDir('one/level');
$a->extractTo(dirname(__FILE__) . '/extract', 'mount');
$a->extractTo(dirname(__FILE__) . '/extract');
$out = array();
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname(__FILE__) . '/extract', 0x3000), RecursiveIteratorIterator::CHILD_FIRST) as $p => $b) {
    $out[] = $p;
}
sort($out);
foreach ($out as $b) {
    echo "{$b}\n";
}
$a->extractTo(dirname(__FILE__) . '/extract1', 'file1.txt');
var_dump(file_get_contents(dirname(__FILE__) . '/extract1/file1.txt'));
$a->extractTo(dirname(__FILE__) . '/extract1', 'subdir/ectory/file.txt');
var_dump(file_get_contents(dirname(__FILE__) . '/extract1/subdir/ectory/file.txt'));
$a->extractTo(dirname(__FILE__) . '/extract1-2', array('file2.txt', 'one/level'));
var_dump(file_get_contents(dirname(__FILE__) . '/extract1-2/file2.txt'));
var_dump(is_dir(dirname(__FILE__) . '/extract1-2/one/level'));
try {
    $a->extractTo(dirname(__FILE__) . '/whatever', 134);
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
Example #16
0
        return $this;
    });
    return function () use($header) {
        if (is_array($this->response->debug)) {
            $this->response->header($header, json_encode($this->response->debug));
        }
    };
}, 'phar' => function () {
    if (!$this->request->isCli) {
        return;
    }
    if ('.phar' == substr($_SERVER['SCRIPT_FILENAME'], -5) && $this->config->extract) {
        $this->cmd('extract <path>', function () {
            try {
                $phar = new \Phar($_SERVER['SCRIPT_FILENAME']);
                $phar->extractTo($this->params->path, null, true);
            } catch (Exception $e) {
                echo $e->getMessage();
                exit(1);
            }
        });
    } elseif ($this->config->dist) {
        $this->cmd('dist <name>', function () {
            $entryScript = basename($_SERVER['SCRIPT_FILENAME']);
            $phar = new \Phar($this->params->name, FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME, $this->params->name);
            $phar->buildFromDirectory($this->config->basedir, '/\\.php$/');
            $phar->setStub($phar->createDefaultStub($entryScript));
        });
    }
}, 'bodyParser' => function () {
    $this->body = function () {
    if (empty($params['clean'])) {
        echo " - directory already exists {$install_dir}, use clean=1 parameter to override\n";
        exit;
    } else {
        // cleaning
        shell_exec("rm -r {$install_dir}");
        echo " - cleaning installation directory {$install_dir}\n";
    }
}
// create temporary directory
$temp_dir = rtrim(sys_get_temp_dir(), '/') . '/numbers_installer_' . rand(100000, 999999);
mkdir($temp_dir, 0777);
echo " - created temporary directory {$temp_dir}\n";
// extract skeleton to it
$phar = new Phar(rtrim(getcwd(), '/') . '/numbers.phar');
$phar->extractTo($temp_dir);
echo " - extracted all files from numbers.phar\n";
// now we need to compare
mkdir($install_dir, 0777);
echo " - created installation directory {$install_dir}\n";
// copy files
shell_exec("cp -r {$temp_dir}/skeleton/application/. {$install_dir}");
echo " - copied files to {$install_dir}\n";
// making replaces
$params['domain'] = trim($params['domain']);
$params['version'] = trim($params['version']);
// updating composer file
$file = file_get_contents($install_dir . '/code/libraries/composer.json');
$file = str_replace('[numbers_framework_version]', $params['version'], $file);
file_put_contents($install_dir . '/code/libraries/composer.json', $file);
// generating application.ini file
Example #18
0
 } elseif (strtolower($argv[1]) == "-e") {
     //PharTools Extract command
     if (isset($argv[2])) {
         //Get fixed filename
         if (strtolower(substr($argv[2], -5)) == ".phar" || strpos($argv[2], '.') !== false) {
             $file = $argv[2];
         } else {
             $file = $argv[2] . ".phar";
         }
         if (file_exists($file)) {
             try {
                 $phar = new Phar($file, 0);
                 if (isset($argv[3])) {
                     if (is_dir($argv[3])) {
                         echo "Extracting...";
                         $phar->extractTo($argv[3], null, true);
                         echo "\nExtracted in " . $argv[3] . "!\n";
                     } else {
                         $dir = @mkdir($argv[3]);
                         //Check directory
                         if ($dir) {
                             echo "Extracting...";
                             $phar->extractTo($argv[3], null, true);
                             echo "\nExtracted in " . $argv[3] . "!\n";
                         } else {
                             echo "I/O Error\n";
                         }
                     }
                 } else {
                     echo "Extracting...";
                     $phar->extractTo(getcwd(), null, true);
Example #19
0
            $p = new Phar("./" . $lNouvelleVersion[CANAL]["phar"]);
            if (empty($_POST['rep'])) {
                $p_path = "./";
            } else {
                $p_path = $_POST['rep'];
            }
            //$p_remove_path = '';
            //$p_mode = '';
            // Création du répertoire
            if (!is_dir($p_path)) {
                mkdir($p_path, 0755, true);
            }
            // Extraction et installation des fichiers
            //$lExtract =  PclTarExtract($p_tarname, $p_path, $p_remove_path, $p_mode);
            // Extraction et installation des fichiers
            $p->extractTo($p_path);
            // Supprime l'archive
            @unlink("./" . $lNouvelleVersion[CANAL]["phar"]);
        } else {
            if (!isset($_GET['rep'])) {
                // Retour à la Page 1
                header('location:./install.php');
            }
        }
        echo $lEntete;
        if (isset($_GET['rep'])) {
            $p_path = $_GET['rep'];
            ?>

<div class="ui-state-highlight">Echec de la connexion à la Base</div>
                 }
             }
         }
         $d->close();
     }
 }
 viderDossier(".");
 @unlink("./conf/.htaccess");
 @unlink("./ancien/.htaccess");
 // 2/ Télécharger le phar
 copy("http://" . ADRESSE_DEPOT_ZEYBUX . "/maintenance/" . $lNouvelleVersion["maintenance"]["phar"], "./" . $lNouvelleVersion["maintenance"]["phar"]);
 // 3/ Extraire le phar
 // Création du phar
 $p = new Phar("./" . $lNouvelleVersion["maintenance"]["phar"]);
 // Extraction de l'archive
 $p->extractTo(".");
 // 4/ Lancement des scripts
 // Version actuelle
 require_once "./version.php";
 // Fonction qui permet de décomposer le numéro de version et de mettre 0 si il n'y a rien
 function decomposerVersion($pVersion)
 {
     $lVersion = explode("\\.", $pVersion);
     $lVersionRetour = array(0, 0, 0);
     if (isset($lVersion[0])) {
         $lVersionRetour[0] = $lVersion[0];
     }
     if (isset($lVersion[1])) {
         $lVersionRetour[1] = $lVersion[1];
     }
     if (isset($lVersion[2])) {
Example #21
0
function runComposer()
{
    $composerPhar = new Phar("composer.phar");
    $composerPhar->extractTo('./composer/');
    require_once './composer/vendor/autoload.php';
    $input = new \Symfony\Component\Console\Input\ArrayInput(array('command' => 'update'));
    $app = new \Composer\Console\Application();
    $app->run($input);
}
Example #22
0
<?php

/**
 * Some composer packages require git installed before it can clone.
 * Ensure git is installed and properly configured to be run as 'git' from CLI
 */
ini_set('memory_limit', '512M');
ini_set('max_execution_time', 300);
define('EXTRACT_DIRECTORY', SYSTEM_PATH . "/composer");
if (file_exists(EXTRACT_DIRECTORY . '/tmp/vendor/autoload.php') !== true) {
    ini_set("phar.readonly", 0);
    $composerPhar = new Phar(SYSTEM_PATH . "/composer.phar");
    //php.ini setting phar.readonly must be set to 0
    $composerPhar->extractTo(EXTRACT_DIRECTORY . "/tmp");
}
//This requires the phar to have been extracted successfully.
require_once EXTRACT_DIRECTORY . '/tmp/vendor/autoload.php';
//Use the Composer classes
use Composer\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Composer\Command\UpdateCommand;
use Symfony\Component\Console\Output\StreamOutput;
function composer_ALL(Web $w)
{
    echo "<pre>" . file_get_contents(ROOT_PATH . '/log/composer.log') . "</pre>";
    // Collect dependencies
    $dependencies_array = array();
    foreach ($w->modules() as $module) {
        $dependencies = Config::get("{$module}.dependencies");
        if (!empty($dependencies)) {
            $dependencies_array = array_merge($dependencies, $dependencies_array);
Example #23
0
 protected function extract($file, $path)
 {
     $archive = new \Phar($file);
     $archive->extractTo($path, null, true);
 }
 public function process($id, $args)
 {
     $this->load->model('mediastore');
     if (MediaStore::ORGIN_PKG !== $this->mediastore->isValidVideoPackage($args['full_path'])) {
         return $this->fail($id, "file `{$args['full_path']}` is not a valid video package");
     }
     if (!($work_dir = $this->config->item('video_frags_path'))) {
         $work_dir = '/tmp';
     }
     if (is_dir($work_dir)) {
         if (!is_writable($work_dir)) {
             return $this->revert($id, "can not extract video file from the package to `{$work_dir}`");
         }
     } else {
         if (!@mkdir($work_dir, 0777, true)) {
             return $this->revert($id, "failed to mkdir `{$work_dir}`");
         }
     }
     $meta = $this->mediastore->getVideoMetaFromPackage($args['full_path']);
     $fn = $work_dir . '/' . $meta['video_file'];
     try {
         $phar = new Phar($args['full_path']);
         if (!is_file($fn)) {
             $this->log("extract video file into `{$work_dir}`");
             if (!$phar->extractTo($work_dir, [$meta['video_file']])) {
                 throw new Exception("can not extract video file from the package to `{$fn}`");
             }
         }
     } catch (Exception $ex) {
         return $this->revert($id, $ex->getMessage());
     }
     $this->log("determine available resolutions");
     $resolutions = $this->determineResolutions($fn);
     if (false === $resolutions) {
         return $this->fail($id, "file `{$fn}` is not a valid video file");
     }
     $option = ['playlist' => 'playlist', 'work_dir' => $work_dir, 'segtime' => $this->config->item('video_segment_time')];
     if ($option['segtime'] < 2) {
         $option['segtime'] = 2;
     }
     $meta['resolutions'] = [];
     $file_list = [];
     foreach ($resolutions as $width => $def) {
         $option['height'] = $def['height'];
         $option['width'] = $def['width'];
         $option['ab'] = $def['ab'];
         $option['vb'] = $def['vb'];
         if ($list = $this->convert($fn, $option)) {
             $meta['resolutions'][] = $width;
             $file_list = array_merge($file_list, $list);
         } else {
             return false;
         }
     }
     $this->log("build video package into `{$work_dir}`");
     $pkg = $this->mediastore->buildVideoPackage($file_list, $meta, $work_dir);
     if ($pkg) {
         $this->log("save video package as `{$pkg}`");
         $ret = $this->mediastore->saveVideoPackage(['full_path' => $pkg]);
         if ($ret === 'OK') {
             return true;
         } else {
             return $this->fail($id, $ret);
         }
     }
     return $this->fail($id, "build video package fails");
 }
Example #25
0
<?php

$phar = new Phar('dbsync.phar');
$phar->buildFromDirectory('phar');
$phar->setDefaultStub('index.php');
$signatures = Phar::getSupportedSignatures();
$phar->setSignatureAlgorithm(PHAR::SHA512);
$phar->extractTo('pharTest');
Example #26
0
 /**
  * Apply the update
  *  
  * @access public      
  * @return boolean
  */
 public static function applyPackage($pharWithPath = null, $pharType = 'addon')
 {
     $phar_can_open = true;
     $meta = array();
     $pro_hart = array();
     try {
         if ($pharWithPath == null) {
             $pharFile = 'update.phar';
             $phar = new Phar(DIR_FS_WORK . 'updates/' . $pharFile);
             $meta = $phar->getMetadata();
             self::$_to_version = $meta['version_to'];
             // reset the log
             if (file_exists(DIR_FS_WORK . 'logs/update-' . self::$_to_version . '.txt') && is_writable(DIR_FS_WORK . 'logs/update-' . self::$_to_version . '.txt')) {
                 unlink(DIR_FS_WORK . 'logs/update-' . self::$_to_version . '.txt');
             }
             $pharCode = 'update';
             if (defined('ADDONS_SYSTEM_LOADED_7_PRO_STATUS') && is_dir(DIR_FS_CATALOG . 'addons/Loaded_7_Pro')) {
                 self::rmdir_r(DIR_FS_CATALOG . 'addons/Loaded_7_Pro');
             }
             if (defined('ADDONS_SYSTEM_LOADED_7_B2B_STATUS') && is_dir(DIR_FS_CATALOG . 'addons/Loaded_7_B2B')) {
                 self::rmdir_r(DIR_FS_CATALOG . 'addons/Loaded_7_B2B');
             }
             self::log('##### UPDATE TO ' . self::$_to_version . ' STARTED', $pharCode);
         } else {
             $pharFile = end(explode('/', $pharWithPath));
             $phar = new Phar(DIR_FS_WORK . 'addons/' . $pharFile);
             $meta = $phar->getMetadata();
             $pharCode = str_replace('.phar', '', $pharFile);
             if ($meta['type'] != '') {
                 $pharType = $meta['type'];
             }
             // reset the log
             if (file_exists(DIR_FS_WORK . 'logs/addon-' . $pharCode . '.txt') && is_writable(DIR_FS_WORK . 'logs/addon-' . $pharCode . '.txt')) {
                 unlink(DIR_FS_WORK . 'logs/addon-' . $pharCode . '.txt');
             }
             self::log('##### ADDON INSTALL ' . $pharCode . ' STARTED', $pharCode);
         }
         // first delete files before extracting new files
         if (is_array($meta['delete']) && count($meta['delete']) > 0) {
             foreach ($meta['delete'] as $file) {
                 $directory = realpath(DIR_FS_CATALOG) . '/';
                 if (file_exists($directory . $file)) {
                     if (is_dir($directory . $file)) {
                         if (rename($directory . $file, $directory . dirname($file) . '/.CU_' . basename($file))) {
                             $pro_hart[] = array('type' => 'directory', 'where' => $directory, 'path' => dirname($file) . '/.CU_' . basename($file), 'log' => true);
                         }
                     } else {
                         if (rename($directory . $file, $directory . dirname($file) . '/.CU_' . basename($file))) {
                             $pro_hart[] = array('type' => 'file', 'where' => $directory, 'path' => dirname($file) . '/.CU_' . basename($file), 'log' => true);
                         }
                     }
                 }
             }
         }
         // loop through each file individually as extractTo() does not work with
         // directories (see http://bugs.php.net/bug.php?id=54289)
         foreach (new RecursiveIteratorIterator($phar) as $iteration) {
             if (($pos = strpos($iteration->getPathName(), '.phar')) !== false) {
                 $file = substr($iteration->getPathName(), $pos + 6);
                 if (version_compare($meta['compatibility'], '7.002.0.0') != -1 || $pharType == 'template' || $pharType == 'language' || $pharWithPath == null) {
                     $directory = realpath(DIR_FS_CATALOG) . '/';
                 } else {
                     $directory = realpath(DIR_FS_CATALOG) . '/addons/' . $pharCode . '/';
                 }
                 if (file_exists($directory . $file)) {
                     if (rename($directory . $file, $directory . dirname($file) . '/.CU_' . basename($file))) {
                         $pro_hart[] = array('type' => 'file', 'where' => $directory, 'path' => dirname($file) . '/.CU_' . basename($file), 'log' => false);
                     }
                 }
                 if ($phar->extractTo($directory, $file, true)) {
                     self::log('Extracted: ' . $file, $pharCode);
                 } else {
                     self::log('*** Could Not Extract: ' . $file, $pharCode);
                 }
             }
         }
         self::log('##### CLEANUP', $pharCode);
         foreach (array_reverse($pro_hart, true) as $mess) {
             if ($mess['type'] == 'directory') {
                 if (self::rmdir_r($mess['where'] . $mess['path'])) {
                     if ($mess['log'] === true) {
                         self::log('Deleted: ' . str_replace('/.CU_', '/', $mess['path']), $pharCode);
                     }
                 } else {
                     if ($mess['log'] === true) {
                         self::log('*** Could Not Delete: ' . str_replace('/.CU_', '/', $mess['path']), $pharCode);
                     }
                 }
             } else {
                 if (unlink($mess['where'] . $mess['path'])) {
                     if ($mess['log'] === true) {
                         self::log('Deleted: ' . str_replace('/.CU_', '/', $mess['path']), $pharCode);
                     }
                 } else {
                     if ($mess['log'] === true) {
                         self::log('*** Could Not Delete: ' . str_replace('/.CU_', '/', $mess['path']), $pharCode);
                     }
                 }
             }
         }
     } catch (Exception $e) {
         $phar_can_open = false;
         self::log('##### ERROR: ' . $e->getMessage(), $pharCode);
         self::log('##### REVERTING STARTED', $pharCode);
         foreach (array_reverse($pro_hart, true) as $mess) {
             if ($mess['type'] == 'directory') {
                 if (file_exists($mess['where'] . str_replace('/.CU_', '/', $mess['path']))) {
                     self::rmdir_r($mess['where'] . str_replace('/.CU_', '/', $mess['path']));
                 }
             } else {
                 if (file_exists($mess['where'] . str_replace('/.CU_', '/', $mess['path']))) {
                     unlink($mess['where'] . str_replace('/.CU_', '/', $mess['path']));
                 }
             }
             if (file_exists($mess['where'] . $mess['path'])) {
                 rename($mess['where'] . $mess['path'], $mess['where'] . str_replace('/.CU_', '/', $mess['path']));
             }
             self::log('Reverted: ' . str_replace('/.CU_', '/', $mess['path']), $pharCode);
         }
         self::log('##### REVERTING COMPLETE', $pharCode);
         self::log('##### UPDATE TO ' . self::$_to_version . ' FAILED', $pharCode);
         trigger_error($e->getMessage());
         trigger_error('Please review the update log at: ' . DIR_FS_WORK . 'logs/update-' . self::$_to_version . '.txt');
     }
     if ($pharWithPath == null) {
         // execute run after process
         self::doRunAfter();
         // verify 644 permissions on PHP files on Linux systems
         if (utility::execEnabled() === true && utility::isLinux() === true) {
             try {
                 exec('\\find ' . DIR_FS_CATALOG . ' \\( -type f -exec chmod 644 {} \\; \\);');
                 self::log('##### UPDATED Permissions on PHP files/directories', $pharCode);
             } catch (Exception $e) {
                 self::log('*** Could NOT Set Permissions on PHP files/directories', $pharCode);
             }
             self::log('##### UPDATE TO ' . self::$_to_version . ' COMPLETE', $pharCode);
         } else {
             try {
                 self::chmod_r(DIR_FS_CATALOG);
                 self::log('##### UPDATED Permissions on PHP files/directories', $pharCode);
             } catch (Exception $e) {
                 self::log('*** Could NOT Set Permissions on PHP files/directories', $pharCode);
             }
             // remove the update phar
             if (file_exists(DIR_FS_WORK . 'updates/update.phar')) {
                 unlink(DIR_FS_WORK . 'updates/update.phar');
             }
             self::log('##### UPDATE TO ' . self::$_to_version . ' COMPLETE', $pharCode);
         }
     } else {
         // remove the addon phar & pubkey
         if (file_exists(DIR_FS_WORK . 'addons/' . $pharCode . '.phar')) {
             unlink(DIR_FS_WORK . 'addons/' . $pharCode . '.phar');
         }
         if (file_exists(DIR_FS_WORK . 'addons/' . $pharCode . '.phar.pubkey')) {
             unlink(DIR_FS_WORK . 'addons/' . $pharCode . '.phar.pubkey');
         }
         self::log('##### ADDON INSTALL ' . $code . ' COMPLETE', $pharCode);
     }
     return $phar_can_open;
 }
Example #27
0
 /**
  * Cabin install process.
  *
  * 1. Extract files to proper directory.
  * 2. Run the update triggers (install hooks and incremental upgrades)
  * 3. Create/update relevant configuration files.
  * 4. Create symbolic links.
  * 5. Clear the cache files.
  *
  * @param InstallFile $fileInfo
  * @return bool
  */
 public function install(InstallFile $fileInfo) : bool
 {
     $ns = $this->makeNamespace($this->supplier->getName(), $this->package);
     $alias = 'cabin.' . $this->supplier->getName() . '.' . $this->package . '.phar';
     $updater = new \Phar($fileInfo->getPath(), \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME);
     $updater->setAlias($alias);
     $metadata = $updater->getMetadata();
     // Overwrite files
     $updater->extractTo(ROOT . '/Cabin/' . $ns);
     // Run the update trigger.
     $updateTrigger = ROOT . '/Cabin/' . $ns . '/update_trigger.php';
     if (\file_exists($updateTrigger)) {
         /**
          * @security Make sure arbitrary RCE isn't possible here.
          */
         \shell_exec('php -dphar.readonly=0 ' . \escapeshellarg($updateTrigger) . ' >/dev/null 2>&1 &');
     }
     // Free up the updater alias
     $garbageAlias = Base64UrlSafe::encode(\random_bytes(33)) . '.phar';
     $updater->setAlias($garbageAlias);
     unset($updater);
     self::$continuumLogger->store(LogLevel::INFO, 'Cabin install successful', $this->getLogContext($fileInfo));
     return $this->configure($ns, $metadata);
 }
Example #28
0
<?php

define('EXTRACT_DIRECTORY', __DIR__ . "/extractedComposer");
ini_set('max_execution_time', 600);
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
print "<pre>Installing GitSync dependencies for the first time ...\n\n";
flush();
if (!file_exists(EXTRACT_DIRECTORY . '/vendor/autoload.php') == true) {
    if (ini_get('phar.readonly')) {
        print "Error: unable to proceed. Please set phar.readonly = 0 in php.ini and then reload this page.</pre>";
        exit;
    }
    $composerPhar = new Phar(__DIR__ . "/composer.phar");
    $composerPhar->extractTo(EXTRACT_DIRECTORY);
}
//This requires the phar to have been extracted successfully.
require_once EXTRACT_DIRECTORY . '/vendor/autoload.php';
//Use the Composer classes
use Composer\Console\Application;
//Create the commands
$input = new Symfony\Component\Console\Input\StringInput('install');
$output = new Symfony\Component\Console\Output\StreamOutput(fopen('php://output', 'w'));
//Create the application and run it with the commands
$application = new Application();
$application->add(new Composer\Command\InstallCommand());
$application->setAutoExit(false);
$application->run($input, $output);
print "Cleaning up ...\n\n";
flush();
Example #29
0
File: 1.php Project: VicDeo/poc
<?php

$composerPhar = new Phar("composer.phar");
//php.ini setting phar.readonly must be set to 0
$composerPhar->extractTo(__DIR__);
 /**
  * (non-PHPdoc)
  *
  * @param \SplFileInfo $archive The archive file to be deployed
  *
  * @return void
  * @see \TechDivision\ApplicationServer\AbstractExtractor::deployArchive()
  */
 public function deployArchive(\SplFileInfo $archive)
 {
     try {
         // create folder names based on the archive's basename
         $tmpFolderName = new \SplFileInfo($this->getTmpDir() . DIRECTORY_SEPARATOR . $archive->getFilename());
         $webappFolderName = new \SplFileInfo($this->getWebappsDir() . DIRECTORY_SEPARATOR . basename($archive->getFilename(), $this->getExtensionSuffix()));
         // check if archive has not been deployed yet or failed sometime
         if ($this->isDeployable($archive)) {
             // flag webapp as deploying
             $this->flagArchive($archive, ExtractorInterface::FLAG_DEPLOYING);
             // backup actual webapp folder, if available
             if ($webappFolderName->isDir()) {
                 // backup files that are NOT part of the archive
                 $this->backupArchive($archive);
                 // delete directories previously backed up
                 $this->removeDir($webappFolderName);
             }
             // remove old temporary directory
             $this->removeDir($tmpFolderName);
             // extract phar to tmp directory
             $p = new \Phar($archive);
             $p->extractTo($tmpFolderName);
             // move extracted content to webapps folder
             rename($tmpFolderName->getPathname(), $webappFolderName->getPathname());
             // restore backup if available
             $this->restoreBackup($archive);
             // We have to set the user rights to the user:group configured within the system configuration
             $this->setUserRights($webappFolderName);
             // flag webapp as deployed
             $this->flagArchive($archive, ExtractorInterface::FLAG_DEPLOYED);
         }
     } catch (\Exception $e) {
         // log error
         $this->getInitialContext()->getSystemLogger()->error($e->__toString());
         // flag webapp as failed
         $this->flagArchive($archive, ExtractorInterface::FLAG_FAILED);
     }
 }