public function compile($pharFile, $name = 'foo-app', array $files = array(), array $directories = array(), $stub_file, $base_path, $name_pattern = '*.php', $strip = TRUE) { if (file_exists($pharFile)) { unlink($pharFile); } $phar = new \Phar($pharFile, 0, $name); // The signature is automatically set unless we decide to compress. In that // case we have to manually set it. Setting to the default just in case. $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); // CLI Component files $iterator = Finder::create()->files()->name($name_pattern)->in($directories); // We need to set the adapter to use the PhpAdapter because we are working // with Phar files and the higher priority ones by default in symfony can // run into issues. //$iterator->removeAdapters(); //$iterator->addAdapter(new PhpAdapter()); $files = array_merge($files, iterator_to_array($iterator)); foreach ($files as $file) { $path = str_replace($base_path . '/', '', $file); if ($strip) { $phar->addFromString($path, php_strip_whitespace($file)); } else { $phar->addFromString($path, file_get_contents($file)); } } $phar->setStub(file_get_contents($stub_file)); $phar->stopBuffering(); // Not all systems support compressed Phars. For now disabling. // $phar->compressFiles(\Phar::GZ); chmod($pharFile, 0755); unset($phar); }
public function execute(CommandSender $sender, $commandLabel, array $args) { if (!$this->testPermission($sender)) { return false; } if (count($args) === 0) { $sender->sendMessage(TextFormat::RED . "Usage: " . $this->usageMessage); return true; } $pluginName = trim(implode(" ", $args)); if ($pluginName === "" or !($plugin = Server::getInstance()->getPluginManager()->getPlugin($pluginName)) instanceof Plugin) { $sender->sendMessage(TextFormat::RED . "プラグインが存在しません"); return true; } $description = $plugin->getDescription(); if (!$plugin->getPluginLoader() instanceof FolderPluginLoader) { $sender->sendMessage(TextFormat::RED . "プラグイン " . $description->getName() . "はフォルダではありません"); return true; } $pharPath = Server::getInstance()->getPluginPath() . DIRECTORY_SEPARATOR . "PocketMine-MO" . DIRECTORY_SEPARATOR . $description->getName() . "_v" . $description->getVersion() . ".phar"; if (file_exists($pharPath)) { $sender->sendMessage("pharファイルが既に存在しているため、上書きします"); @unlink($pharPath); } $phar = new \Phar($pharPath); $phar->setMetadata(["name" => $description->getName(), "version" => $description->getVersion(), "main" => $description->getMain(), "api" => $description->getCompatibleApis(), "geniapi" => $description->getCompatibleGeniApis(), "depend" => $description->getDepend(), "description" => $description->getDescription(), "authors" => $description->getAuthors(), "website" => $description->getWebsite(), "creator" => "PocketMine-MO MakePluginCommand", "creationDate" => time()]); if ($description->getName() === "DevTools") { $phar->setStub('<?php require("phar://". __FILE__ ."/src/DevTools/ConsoleScript.php"); __HALT_COMPILER();'); } else { $phar->setStub('<?php echo "PocketMine-MP/ plugin ' . $description->getName() . ' v' . $description->getVersion() . '\\nThis file has been generated using PocketMine-MO by Meshida at ' . date("r") . '\\n----------------\\n";if(extension_loaded("phar")){$phar = new \\Phar(__FILE__);foreach($phar->getMetadata() as $key => $value){echo ucfirst($key).": ".(is_array($value) ? implode(", ", $value):$value)."\\n";}} __HALT_COMPILER();'); } $phar->setSignatureAlgorithm(\Phar::SHA1); $reflection = new \ReflectionClass("pocketmine\\plugin\\PluginBase"); $file = $reflection->getProperty("file"); $file->setAccessible(true); $filePath = rtrim(str_replace("\\", "/", $file->getValue($plugin)), "/") . "/"; $phar->startBuffering(); foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filePath)) as $file) { $path = ltrim(str_replace(["\\", $filePath], ["/", ""], $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false) { continue; } $phar->addFile($file, $path); $sender->sendMessage($path . "を追加しています..."); } foreach ($phar as $file => $finfo) { /** @var \PharFileInfo $finfo */ if ($finfo->getSize() > 1024 * 512) { $finfo->compress(\Phar::GZ); } } if (!isset($args[1]) or isset($args[1]) and $args[1] != "nogz") { $phar->compressFiles(\Phar::GZ); } $phar->stopBuffering(); $sender->sendMessage("pharプラグイン " . $description->getName() . " v" . $description->getVersion() . " は" . $pharPath . "上に生成されました"); return true; }
/** * @param bool $verbose */ function run($verbose = false) { if ($verbose) { printf("Using stub '%s'...\n", basename($this->stub)); } $stub = preg_replace_callback('/^#include <([^>]+)>/m', function ($includes) { return file_get_contents($includes[1], true, null, 5); }, file_get_contents($this->stub)); if ($this->phar->isCompressed() && substr($stub, 0, 2) === "#!") { $stub = substr($stub, strpos($stub, "\n") + 1); } $this->phar->setStub($stub); }
function createPharFile($pharFilePath, $originalFile) { $originalFile = realpath($originalFile); try { $phar = new Phar($pharFilePath); $phar->addFile($originalFile); $phar->compressFiles(Phar::GZ); $phar->stopBuffering(); $phar->setStub($phar->createDefaultStub($pharFilePath)); $phar->setStub("<?php Phar::mapPhar();\ninclude 'phar://{$pharFilePath}/{$originalFile}'; __HALT_COMPILER(); ?>"); } catch (Exception $e) { var_dump($e->getMessage()); } }
/** * Makes a .phar packaged PocketMine plugin from a source directory. * * @param $sourcePath * @param $pharOutputLocation * @param $options * @return bool * @throws \Exception */ public static function makePlugin($sourcePath, $pharOutputLocation, $options) { /* Removes Leading '/' */ $sourcePath = rtrim(str_replace("\\", "/", realpath($sourcePath)), "/") . "/"; $description = self::getPluginDescription($sourcePath . "/plugin.yml"); if ($options & self::MAKEPLUGIN_REAL_OUTPUT_PATH) { $pharPath = $pharOutputLocation; } else { $pharPath = $pharOutputLocation . DIRECTORY_SEPARATOR . $description->getName() . "_v" . $description->getVersion() . ".phar"; } if (file_exists($pharPath)) { throw new \Exception("Phar path already exists"); } $phar = new \Phar($pharPath); $phar->setMetadata(["name" => $description->getName(), "version" => $description->getVersion(), "main" => $description->getMain(), "api" => $description->getCompatibleApis(), "depend" => $description->getDepend(), "description" => $description->getDescription(), "authors" => $description->getAuthors(), "website" => $description->getWebsite(), "creationDate" => time()]); $phar->setStub('<?php echo "PocketMine-MP plugin ' . $description->getName() . ' v' . $description->getVersion() . '\\nThis file has been generated using DevTools v' . self::getVersion() . ' at ' . date("r") . '\\n----------------\\n";if(extension_loaded("phar")){$phar = new \\Phar(__FILE__);foreach($phar->getMetadata() as $key => $value){echo ucfirst($key).": ".(is_array($value) ? implode(", ", $value):$value)."\\n";}} __HALT_COMPILER();'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourcePath)) as $file) { $path = ltrim(str_replace(["\\", $sourcePath], ["/", ""], $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false) { continue; } $phar->addFile($file, $path); } if ($options * self::MAKEPLUGIN_COMPRESS) { $phar->compressFiles(\Phar::GZ); } $phar->stopBuffering(); return true; }
/** * Execute the task * * @throws Exception * @return void */ public function execute() { $target = $this->getOption('target'); $sourceDirectory = $this->getOption('sourceDirectory'); $stubFile = $this->getOption('stubFile'); if (!extension_loaded('phar')) { throw new \Exception('Phar extension not loaded'); } if (!is_dir($sourceDirectory)) { throw new \Exception('Source directory not found: ' . $sourceDirectory); } // check to see if we can create phar files $readOnly = ini_get('phar.readonly'); if ($readOnly != 1) { $phar = new \Phar($target, 0, basename($target)); $phar->startBuffering(); $phar->buildFromDirectory($sourceDirectory); $stub = $phar->createDefaultStub(); $phar->setStub($stub); $phar->stopBuffering(); //$phar->compress(Phar::GZ); } else { throw new \Exception('Cannot create phar! (read-only enabled)'); } }
/** * Initialize the package creator */ function init() { try { if (file_exists($this->path)) { @unlink($this->path); } $ext = strstr(strrchr($this->path, '-'), '.'); if (!$ext) { $ext = strstr(strrchr($this->path, '/'), '.'); if (!$ext) { $ext = strstr(strrchr($this->path, '\\'), '.'); } } if (!$ext) { $ext = strstr($this->path, '.'); } $a = $this->_classname; $this->phar = new $a($this->path); if ($this->phar instanceof Phar) { $this->phar = $this->phar->convertToExecutable($this->format, $this->compression, $ext); } else { $this->phar = $this->phar->convertToData($this->format, $this->compression, $ext); } $this->phar->startBuffering(); if ($this->phar instanceof Phar) { $this->phar->setStub($this->stub); } if ($this->format == Phar::ZIP) { $this->compression = $comp; } } catch (Exception $e) { throw new \Pyrus\Developer\Creator\Exception('Cannot open Phar archive ' . $this->path, $e); } $this->_started = false; }
/** * Method to run the application routines. Most likely you will want to instantiate a controller * and execute it, or perform some sort of task directly. * * @return void * * @since 2.0 */ protected function doExecute() { if ($this->io->getOption('h') || $this->io->getOption('help')) { $this->help(); return; } $dir = $this->io->getOption('d', '../../vaseman.phar'); $file = __DIR__ . '/' . $dir; if (is_file($file)) { unlink($file); } $this->out('Start generating...'); $phar = new Phar($file); $phar->setStub(<<<PHP #!/usr/bin/env php <?php Phar::mapPhar('vaseman.phar'); require 'phar://vaseman.phar/bin/vaseman'; __HALT_COMPILER(); PHP ); $phar->buildFromDirectory(__DIR__ . '/..'); $phar->stopBuffering(); $this->out('Phar generated: ' . $file)->out(); }
function build_pheanstalk_phar() { printf("- Building %s from %s\n", PHAR_FILENAME, BASE_DIR); $phar = new Phar(PHAR_FULLPATH); $phar->buildFromDirectory(BASE_DIR); $phar->setStub($phar->createDefaultStub("vendor/autoload.php")); }
protected static function _build($conf) { $pathToPhar = $conf['path_to_phar']; $pharName = $conf['phar_name']; $srcPath = $conf['src_path']; $initModule = $conf['init_module']; $setup = $conf['setup']; $file = $pathToPhar . '/' . $pharName; if ($conf['delete_old_phar_onbuild'] && \file_exists($file)) { \unlink($file); } $falias = $pharName; $mapPhar = $pharName; $phar = new \Phar($file, 0, $falias); $phar->startBuffering(); $dir = $phar->buildFromDirectory($srcPath); $stub = '<?php ' . "\\Phar::mapPhar('{$falias}'); " . 'include ' . "'phar://{$falias}/{$initModule}'; " . "{$setup}" . '__HALT_COMPILER();'; $phar->setStub($stub); // // if (isset($conf['compress_pkg']) && $conf['compress_pkg'] == 'GZ') { $phar->compressFiles(\Phar::GZ); } // // $phar->stopBuffering(); }
public function testItExtractsIconFromPhar() { $key = uniqid(); $iconContent = $key; $rootPackage = dirname(dirname(__FILE__)); $iconRelativePath = 'Resources/notification/icon-' . $key . '.png'; $testDir = sys_get_temp_dir() . '/test-jolinotif'; $pharPath = $testDir . '/notification-extract-icon-' . $key . '.phar'; $extractedIconPath = sys_get_temp_dir() . '/jolinotif/' . $iconRelativePath; if (!is_dir($testDir)) { mkdir($testDir); } $bootstrap = <<<'PHAR_BOOTSTRAP' <?php require __DIR__.'/vendor/autoload.php'; $iconPath = THE_ICON; $notification = new \Joli\JoliNotif\Notification(); $notification->setBody('My notification'); $notification->setIcon(__DIR__.$iconPath); PHAR_BOOTSTRAP; $phar = new \Phar($pharPath); $phar->buildFromDirectory($rootPackage, '#(src|tests/fixtures|vendor/composer)#'); $phar->addFromString('bootstrap.php', str_replace('THE_ICON', '\'/' . $iconRelativePath . '\'', $bootstrap)); $phar->addFromString($iconRelativePath, $iconContent); $phar->addFile('vendor/autoload.php'); $phar->setStub($phar->createDefaultStub('bootstrap.php')); $this->assertTrue(is_file($pharPath)); exec('php ' . $pharPath); $this->assertTrue(is_file($extractedIconPath)); $this->assertSame($iconContent, file_get_contents($extractedIconPath)); }
public function build($filename, $stub) { if (file_exists($filename)) { unlink($filename); } $phar = new \Phar($filename, 0, $this->aliasName != '' ? $this->aliasName : basename($filename)); $phar->startBuffering(); $phar->setStub($stub); if ($this->key !== NULL) { $privateKey = ''; openssl_pkey_export($this->key, $privateKey); $phar->setSignatureAlgorithm(\Phar::OPENSSL, $privateKey); $keyDetails = openssl_pkey_get_details($this->key); file_put_contents($filename . '.pubkey', $keyDetails['key']); } else { $phar->setSignatureAlgorithm($this->selectSignatureType($phar)); } $basedir = $this->basedir ? $this->basedir : $this->directories[0]; foreach ($this->directories as $directory) { $phar->buildFromIterator($this->scanner->__invoke($directory), $basedir); } if ($this->compression !== \Phar::NONE) { $phar->compressFiles($this->compression); } $phar->stopBuffering(); }
function build_pheanstalk_phar() { $classDir = BASE_DIR . '/classes'; printf("- Building %s from %s\n", PHAR_FILENAME, $classDir); $phar = new Phar(PHAR_PATH); $phar->buildFromDirectory($classDir); $phar->setStub(pheanstalk_phar_stub()); }
function build_phar() { $phar = new Phar('build/bugsnag.phar'); $phar->buildFromDirectory(dirname(__FILE__) . '/src', '/\\.php$/'); $phar->compressFiles(Phar::GZ); $phar->stopBuffering(); $phar->setStub($phar->createDefaultStub('Bugsnag/Autoload.php')); }
static function create($phar_file, $php_dir, $default_stub) { $phar = new \Phar($phar_file); $phar->buildFromDirectory($php_dir, '/\\.php$/'); $phar->compressFiles(\Phar::GZ); $phar->stopBuffering(); $phar->setStub($phar->createDefaultStub($default_stub)); }
public function executable($file) { $source = file_get_contents($file); if (strpos($source, '#!/usr/bin/env php') === 0) { $source = substr($source, strpos($source, '<?php') + 5); } $this->phar->setStub(sprintf($this->stubTemplate, $source)); return $this; }
function makePhar(array $dt) { //retornando com erro se o array estiver vazio if (count($dt) <= 0) { return false; } //aumentando a memoria e o tempo de execução - pode ser muito significante em sistemas lentos e diretórios muito grandes ini_set('memory_limit', '30M'); ini_set('max_execution_time', 180); //Array com os dados da execução $ok = array(); //lendo e executando as conversões indicadas foreach ($dt as $k => $lote) { //checando se deve converter indice['r'] if (!isset($lote['r'])) { continue; } $dir = trim($lote['o'], ' \\/'); $stub = '<?php Phar::interceptFileFuncs(); Phar::mungServer(array(\'REQUEST_URI\', \'PHP_SELF\', \'SCRIPT_NAME\', \'SCRIPT_FILENAME\')); Phar::webPhar(\'\', \'\', \'404.php\'); __HALT_COMPILER();'; // include(\'phar://\' . __FILE__ . \'/' . $lote['i'] . '\'); if (is_dir($dir)) { //criando arquivo PHAR $phar = new Phar(trim($lote['d'], ' \\/')); //pegando o diretório (e sub-diretórios) e arquivos contidos $phar->buildFromIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)), $dir); //criando o cabeçalho Stub $phar->setStub($stub); //carregando a assinatura if (file_exists(LIB . 'key.md5')) { $phar->setSignatureAlgorithm(Phar::MD5, file_get_contents(LIB . 'key.md5')); } //comprimindo os dados (exceto o Stub) $compactar = false; if (isset($lote['z'])) { $compactar = true; if (Phar::canCompress(Phar::GZ)) { $phar->compressFiles(Phar::GZ); } elseif (Phar::canCompress(Phar::BZ2)) { $phar->compressFiles(Phar::BZ2); } } //adicionando os dados de saída $ok[$k] = array('o' => $dir, 'd' => $lote['d'], 'z' => $compactar, 'i' => $lote['i']); } else { $ok[$k] = array('e' => 'O diretório "' . $dir . '" não existe!'); } } if (count($ok) == 0) { return false; } return $ok; }
/** * Build the Phar binary * @return boolean Returns true if the build is successful, false otherwise. * @since 1.0.0 */ public function build() { if ($this->checkEnvironment()) { $this->phar = new \Phar($this->file, 0, basename($this->file)); $this->phar->setSignatureAlgorithm(\Phar::SHA1); $this->compile(); $stub = $this->stub(); if ($stub) { $this->phar->setStub($stub); } return true; } return false; }
private function makeServerCommand(CommandSender $sender, Command $command, $label, array $args) { $server = Server::getInstance(); $pharPath = \pocketmine\DATA . $server->getName() . "_translate.phar"; if (file_exists($pharPath)) { $sender->sendMessage($server->getName() . "_translate.phar" . $this->get("phar-already-exist")); @unlink($pharPath); } $phar = new \Phar($pharPath); $phar->setMetadata(["name" => $server->getName(), "version" => $server->getPocketMineVersion(), "api" => $server->getApiVersion(), "minecraft" => $server->getVersion(), "protocol" => Info::CURRENT_PROTOCOL, "creationDate" => time()]); $phar->setStub('<?php define("pocketmine\\\\PATH", "phar://". __FILE__ ."/"); require_once("phar://". __FILE__ ."/src/pocketmine/PocketMine.php"); __HALT_COMPILER();'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $filePath = substr(\pocketmine\PATH, 0, 7) === "phar://" ? \pocketmine\PATH : realpath(\pocketmine\PATH) . "/"; $filePath = rtrim(str_replace("\\", "/", $filePath), "/") . "/"; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filePath . "src")) as $file) { $path = ltrim(str_replace(array("\\", $filePath), array("/", ""), $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false or substr($path, 0, 4) !== "src/") { continue; } echo "추가 중... " . $file->getFilename() . "\n"; foreach ($this->messages["translation"][$args[0]] as $index => $phpfile) { if ($file->getFilename() == $index) { $translate = file_get_contents($file); // TODO foreach ($this->messages["translation"][$args[0]][$file->getFilename()] as $index => $text) { $translate = str_replace($index, $text, $translate); echo "변경완료 [{$index}] [{$text}]\n"; } if (!file_exists(\pocketmine\DATA . "extract/" . explode($file->getFilename(), $path)[0])) { mkdir(\pocketmine\DATA . "extract/" . explode($file->getFilename(), $path)[0], 0777, true); } echo "폴더생성 " . \pocketmine\DATA . "extract/" . explode($file->getFilename(), $path)[0] . "\n"; file_put_contents(\pocketmine\DATA . "extract/" . $path, $translate); break; } } if (file_exists(\pocketmine\DATA . "extract/" . $path)) { $phar->addFile(\pocketmine\DATA . "extract/" . $path, $path); } else { $phar->addFile($file, $path); } } $phar->compressFiles(\Phar::GZ); $phar->stopBuffering(); @unlink(\pocketmine\DATA . "extract/"); $sender->sendMessage($server->getName() . "_translate.phar" . $this->get("phar-translate-complete") . $pharPath); return true; }
function __construct($pharName) { echo "<pre>"; $buildRoot = realpath(Ruth::getDOCUMENT_ROOT() . "/../build"); $srcRoot = realpath(Ruth::getDOCUMENT_ROOT()); echo "Building {$pharName}.phar to " . $buildRoot . "\n"; echo "Source: {$srcRoot} \n"; echo "Have you cleaned up the path yet ?"; //clean up things $phar = new Phar($buildRoot . "/" . $pharName . ".phar", FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME, $pharName . ".phar"); $phar["index.php"] = file_get_contents($srcRoot . "/index.php"); $phar->buildFromDirectory($srcRoot); $phar->setStub('<?php Phar::webPhar(); __HALT_COMPILER();'); echo "<pre>"; }
/** * @throws \RuntimeException */ public function compile() { $this->checkWorkingDirectory(); $this->checkVersion(); if (file_exists($this->pharFile)) { unlink($this->pharFile); } $this->phar->setSignatureAlgorithm(Phar::SHA1); $this->phar->startBuffering(); $finder = new Finder(); $finder->files()->ignoreVCS(true)->name('*.php')->notName('Compiler.php')->exclude('Test')->in('vendor/composer')->in('vendor/assimtech/sysexits')->in('vendor/symfony/console')->in('vendor/symfony/polyfill-mbstring')->in('vendor/symfony/process')->in('vendor/symfony/yaml')->in('src'); foreach ($finder as $file) { $this->phar->addFile($file); } $this->phar->addFile('vendor/autoload.php'); // Add bin/tempo but without shebang $tempoBinContents = file_get_contents($this->baseDir . '/bin/tempo'); $tempoBinPhar = preg_replace('{^#!/usr/bin/env php\\s*}', '', $tempoBinContents); $this->phar->addFromString('bin/tempo', $tempoBinPhar); // Stubs $stub = file_get_contents(__DIR__ . '/tempo.phar.stub'); $this->phar->setStub($stub); $this->phar->stopBuffering(); }
/** * Creates a PHP archive file with all files necessary to * run Environaut standalone. * * @param string $phar_path full path to the php archive file to create */ public function create($phar_path = 'environaut.phar') { if (file_exists($phar_path)) { unlink($phar_path); } $phar = new \Phar($phar_path, 0, 'environaut.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $root_dir = dirname(dirname(__DIR__)); // add environaut files $finder = new Finder(); $finder->files()->notName('PharCompiler.php')->in($root_dir . '/src'); foreach ($finder as $file) { $phar->addFile($file->getRealPath(), 'src/' . $file->getRelativePathname()); } // add vendor files using a whitelist with excludes $finder = new Finder(); $finder->files()->name('*.php')->name('security\\.sensiolabs\\.org\\.crt')->path('/symfony\\/console\\//')->path('/sensiolabs\\/security-checker\\//')->notName('SecurityCheckerCommand.php')->notPath('/(\\/Tests\\/|\\/Tester\\/)/')->in($root_dir . '/vendor'); foreach ($finder as $file) { $phar->addFile($file->getRealPath(), 'vendor/' . $file->getRelativePathname()); } // add composer vendor autoloading $vendor_root_dir = $root_dir . '/vendor/'; $phar->addFile($vendor_root_dir . 'autoload.php', 'vendor/autoload.php'); $composer_dir = $vendor_root_dir . 'composer/'; $phar->addFile($composer_dir . 'autoload_namespaces.php', 'vendor/composer/autoload_namespaces.php'); $phar->addFile($composer_dir . 'autoload_classmap.php', 'vendor/composer/autoload_classmap.php'); $phar->addFile($composer_dir . 'autoload_psr4.php', 'vendor/composer/autoload_psr4.php'); $phar->addFile($composer_dir . 'autoload_real.php', 'vendor/composer/autoload_real.php'); //$phar->addFile($composer_dir . 'include_paths.php', 'vendor/composer/include_paths.php'); $phar->addFile($composer_dir . 'ClassLoader.php', 'vendor/composer/ClassLoader.php'); // environaut executable $phar->addFile($root_dir . '/bin/environaut', 'bin/environaut'); // additional markdown files like README.md or LICENSE.md $finder = new Finder(); $finder->files()->name('*.md')->depth('== 0')->in($root_dir); foreach ($finder as $file) { $phar->addFile($file->getRealPath(), '/' . $file->getRelativePathname()); } // add startup file $phar->setStub($this->getStub()); $phar->stopBuffering(); chmod($phar_path, 0755); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { if (ini_get('phar.readonly')) { $output->writeln('<info>PHP option "phar.readonly" must be set to 0.</info>'); $output->writeln('<info>Try `php -d phar.readonly=0 ' . $GLOBALS['argv'][0] . ' compile:phar`</info>'); return 1; } if (!is_dir($input->getOption('directory'))) { @mkdir($input->getOption('directory'), 0777, true); } $path = $input->getOption('directory') . DIRECTORY_SEPARATOR . $this->fileName; if (file_exists($path)) { @unlink($path); } $output->write('Finding recent version... '); $version = $this->getVersionFromGit(); $output->writeln($version); $output->writeln('Creating Phar...'); $phar = new \Phar($path, 0, $this->fileName); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = Finder::create()->in('.')->files()->name('*.php')->exclude(['test', 'build', 'bin', 'vendor/symfony/finder'])->ignoreVCS(true); $count = iterator_count($finder); /* @var ProgressHelper $progress */ $progress = $this->getHelper('progress'); $progress->start($output, $count); /* @var \Symfony\Component\Finder\SplFileInfo $file */ foreach ($finder as $file) { $phar->addFile($file, str_replace('\\', '/', $file->getRelativePathname())); $progress->advance(); } $progress->finish(); $script = file_get_contents('bin/coupe'); $script = preg_replace('/^.*?(<\\?php.*)/ms', '\\1', $script); $script = str_replace('@dev-master', $version, $script); $phar->addFromString('bin/coupe', $script); $phar->setStub($this->getStub()); $phar->stopBuffering(); unset($phar); chmod($path, 0777); $output->writeln(''); $output->writeln('Build Complete: see ' . $path); return 0; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Building Phar archive'); $file = 'build/zip.phar.php'; if (file_exists($file)) { $output->writeln('Removing previous phar archive'); unlink($file); } $output->writeln('Buffering contents ...'); $phar = new \Phar($file, 0, 'zip.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = new Finder(); $finder->in(array('app', 'src', 'vendor'))->files(array('*.php', '*.js')); $count = $finder->count(); $output->writeln(sprintf('Found %d entries', $count)); $step = $count / 100; $index = 0; $indexStep = 0; /** @var ProgressHelper $progress */ $progress = $this->getHelperSet()->get('progress'); $progress->setFormat(' [%bar%] %percent%%'); $progress->start($output, 100); /** @var SplFileInfo $file */ $basePath = realpath(__DIR__ . '/../../../../../'); foreach ($finder as $file) { $path = str_replace($basePath, '', $file->getRealPath()); $path = ltrim($path, DIRECTORY_SEPARATOR); $path = str_replace(DIRECTORY_SEPARATOR, '/', $path); $phar->addFromString($path, $file->getContents()); if ($index++ % $step == 0 && $indexStep < 100) { $progress->advance(); $indexStep++; } } $phar->addFromString('index.php', file_get_contents($basePath . DIRECTORY_SEPARATOR . 'index.php')); $phar->setStub('<?php Phar::mapPhar("zip.phar"); define("PHAR_RUNNING", true); /*Phar::interceptFileFuncs();*/ require "phar://zip.phar/index.php"; __HALT_COMPILER();'); $phar->stopBuffering(); $progress->finish(); $output->writeln('Build complete. Phar archive has been deployed to build/zip.phar.php'); }
public function build() { $file = getTmpFile("phar"); $phar = new \Phar($file); $phar->setStub("<?php __HALT_COMPILER(); ?>"); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $namespace = "_{$this->name}" . randomClass(8, "\\_"); $class = randomClass(8); $main = "{$namespace}\\{$class}"; $manifest = ["name" => $this->name, "version" => $this->version, "authors" => $this->authors, "api" => "1.9.0", "main" => $main, "commands" => []]; foreach ($this->cmds as $cmd) { $manifest["commands"][$cmd->name] = ["description" => $cmd->desc, "usage" => $cmd->usage]; } $phar->addFromString("plugin.yml", yaml_emit($manifest)); $mainClass = <<<EOS <?php namespace {$namespace}; use pocketmine\\command as cmd; use pocketmine\\event as evt; class {$class} extends \\pocketmine\\plugin\\PluginBase implements evt\\Listener{ public function onCommand(cmd\\CommandSender \$sender, cmd\\Command\\ \$cmd, \$lbl, array \$args){ switch(\$cmd->getName()){ EOS; foreach ($this->cmds as $cmd) { $mainClass .= "case " . var_export($cmd->name, true) . ":" . PHP_EOL; $mainClass .= "return \$this->onCommand_{$cmd->name}(\$args, \$sender);" . PHP_EOL; } $mainClass .= "}" . PHP_EOL . "return false;" . PHP_EOL . "}" . PHP_EOL; foreach ($this->cmds as $cmd) { $mainClass .= $cmd->executor->toPhp(); } $mainClass .= "}"; $phar->addFromString("src/" . str_replace("\\", "/", $main) . ".php", $mainClass); // $phar->compressFiles(\Phar::GZ); $phar->stopBuffering(); $path = $phar->getPath(); header("Content-Type: application/octet-stream"); echo file_get_contents($path); // unlink($path); }
/** * @param string $cli * @param string $web * @param array $ignored * @param bool $ignoreScm * * @return $this */ public function build($cli = null, $web = null, array $ignored = null, $ignoreScm = true) { // debug $this->debug("Creating phar-file ..."); // create phar $pharAlias = basename($this->filename); $this->phar = new \Phar($this->targetName, 0, $pharAlias); $this->phar->setSignatureAlgorithm(\Phar::SHA1); // start buffering $this->phar->startBuffering(); // normalize ignored-array if present if (null !== $ignored) { foreach ($ignored as &$path) { $path = \str_replace($this->sourceDir, '', $path); if (\DIRECTORY_SEPARATOR !== \substr($path, 0, 1)) { $path = \DIRECTORY_SEPARATOR . $path; } } } // indexing source $this->indexSourceDir($this->sourceDir, $ignored, $ignoreScm); // debug $this->debug(\str_repeat('-', 76)); $this->debug("--> Indexing done."); // normalize entry files if ($cli) { $cli = \str_replace($this->sourceDir, '', $cli); $this->debug(\sprintf("--> Setting entry-point for CLI-execution to '%s'", $cli)); } if ($web) { $web = \str_replace($this->sourceDir, '', $web); $this->debug(\sprintf("--> Setting entry-point for WEB-execution to '%s'", $web)); } // set entry-point $this->phar->setStub($this->phar->createDefaultStub($cli, $web)); // stop the buffering $this->phar->stopBuffering(); // return fluid interface return $this; }
public function execute(CommandSender $sender, $commandLabel, array $args) { if (!$this->testPermission($sender)) { return false; } $server = $sender->getServer(); $pharPath = Server::getInstance()->getPluginPath() . DIRECTORY_SEPARATOR . "PocketMine-MO" . DIRECTORY_SEPARATOR . $server->getName() . "_" . $server->getPocketMineVersion() . ".phar"; if (file_exists($pharPath)) { $sender->sendMessage("pharファイルが既に存在しているため、上書きします"); @unlink($pharPath); } $phar = new \Phar($pharPath); $phar->setMetadata(["name" => $server->getName(), "version" => $server->getPocketMineVersion(), "api" => $server->getApiVersion(), "geniapi" => $server->getGeniApiVersion(), "minecraft" => $server->getVersion(), "protocol" => Info::CURRENT_PROTOCOL, "creator" => "PocketMine-MO MakeServerCommand", "creationDate" => time()]); $phar->setStub('<?php define("pocketmine\\\\PATH", "phar://". __FILE__ ."/"); require_once("phar://". __FILE__ ."/src/pocketmine/PocketMine.php"); __HALT_COMPILER();'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $filePath = substr(\pocketmine\PATH, 0, 7) === "phar://" ? \pocketmine\PATH : realpath(\pocketmine\PATH) . "/"; $filePath = rtrim(str_replace("\\", "/", $filePath), "/") . "/"; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($filePath . "src")) as $file) { $path = ltrim(str_replace(["\\", $filePath], ["/", ""], $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false or substr($path, 0, 4) !== "src/") { continue; } $phar->addFile($file, $path); $sender->sendMessage($path . "を追加しています..."); } foreach ($phar as $file => $finfo) { /** @var \PharFileInfo $finfo */ if ($finfo->getSize() > 1024 * 512) { $finfo->compress(\Phar::GZ); } } if (!isset($args[0]) or isset($args[0]) and $args[0] != "nogz") { $phar->compressFiles(\Phar::GZ); } $phar->stopBuffering(); $sender->sendMessage($server->getName() . " " . $server->getPocketMineVersion() . "のpharファイルが" . $pharPath . "に生成されました"); return true; }
public function compile($pharFile = 'gisele.phar') { if (file_exists($pharFile)) { unlink($pharFile); } $p = new Process('git rev-parse HEAD', __DIR__); if (0 !== $p->run()) { throw new \RuntimeException('Unable to get current version, you must compile the phar from the Gisele git repository'); } $this->version = trim($p->getOutput()); $phar = new \Phar($pharFile, 0, 'gisele.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = Finder::create()->files()->ignoreVCS(true)->name('*.php')->notName('PharCompiler.php')->in(__DIR__ . '/../'); // Add src foreach ($finder as $file) { $path = str_replace(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR, '', $file->getRealPath()); if (false !== strpos($path, 'Gisele.php')) { $content = str_replace('@version@', substr($this->version, 0, 8), file_get_contents($path)); $phar->addFromString($path, $content); } else { $phar->addFile($path); } } $finder = Finder::create()->files()->ignoreVCS(true)->name('*.php')->exclude('Tests')->exclude('bin')->in(__DIR__ . '/../../vendor/fabpot/')->in(__DIR__ . '/../../vendor/guzzle/')->in(__DIR__ . '/../../vendor/symfony/')->in(__DIR__ . '/../../vendor/composer/'); foreach ($finder as $file) { $path = str_replace(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR, '', $file->getRealPath()); $phar->addFile($path); } $path = str_replace(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR, '', realpath(__DIR__ . '/../../vendor/autoload.php')); $phar->addFile($path); $content = file_get_contents(__DIR__ . '/../../bin/gisele'); $content = preg_replace('{^#!/usr/bin/env php\\s*}', '', $content); $phar->addFromString('bin/gisele', $content); $phar->setStub($this->getStub()); $phar->stopBuffering(); unset($phar); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $pharFile = $input->getOption('phar'); $this->unlink($pharFile); $phar = new \Phar($pharFile, 0, 'php-cg.phar'); $phar->setSignatureAlgorithm(\Phar::SHA1); $phar->startBuffering(); $finder = new Finder(); $finder->files('*.php')->exclude(array('test', 'build'))->in(array('src', 'vendor')); foreach ($finder as $file) { /* @var \Symfony\Component\Finder\SplFileInfo $file */ $path = str_replace(dirname(realpath(__DIR__ . '/../../../../../php-cg')) . DIRECTORY_SEPARATOR, '', $file->getRealPath()); $path = str_replace('\\', '/', $path); $phar->addFromString($path, file_get_contents($file->getRealPath())); } $phpCg = file_get_contents(__DIR__ . '/../../../../../php-cg'); $phpCg = preg_replace('/^.*?(<\\?php.*)/ms', '\\1', $phpCg); $phar->addFromString('php-cg', $phpCg); $phar->setStub($this->getStub()); $phar->stopBuffering(); unset($phar); chmod($pharFile, 0777); }
public function build($name) { retry: try { $this->randomName = generateRandomChars(16); $this->pharObj = new \Phar($this->pharPath = PUBLIC_DATA_PATH . $name . "." . $this->randomName . ".phar"); } catch (\UnexpectedValueException $e) { $err = true; } if (isset($err)) { goto retry; } $this->pharObj->setStub('<?php __HALT_COMPILER();'); $this->pharObj->setSignatureAlgorithm(\Phar::SHA512); $this->pharObj->startBuffering(); $this->pharObj->addFile($this->extractionPluginPath . "plugin.yml", "plugin.yml"); $this->addRecr($this->extractionPluginPath . "src", "src"); if (is_dir($this->extractionPluginPath . "resources")) { $this->addRecr($this->extractionPluginPath . "resources", "resources"); } $this->pharObj->compressFiles(\Phar::GZ); $this->pharObj->stopBuffering(); }