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; }
/** * 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; }
public function run() { $this->printTaskInfo("Creating <info>{$this->filename}</info>"); $this->phar->setSignatureAlgorithm(\Phar::SHA1); $this->phar->startBuffering(); $this->printTaskInfo('Packing ' . count($this->files) . ' files into phar'); $progress = new ProgressBar($this->getOutput()); $progress->start(count($this->files)); $this->startTimer(); foreach ($this->files as $path => $content) { $this->phar->addFromString($path, $content); $progress->advance(); } $this->phar->stopBuffering(); $progress->finish(); $this->getOutput()->writeln(''); if ($this->compress and in_array('GZ', \Phar::getSupportedCompression())) { if (count($this->files) > 1000) { $this->printTaskInfo("Too many files. Compression DISABLED"); } else { $this->printTaskInfo($this->filename . " compressed"); $this->phar = $this->phar->compressFiles(\Phar::GZ); } } $this->stopTimer(); $this->printTaskSuccess("<info>{$this->filename}</info> produced"); return Result::success($this, '', ['time' => $this->getExecutionTime()]); }
public function run() { $this->printTaskInfo('Creating {filename}', ['filename' => $this->filename]); $this->phar->setSignatureAlgorithm(\Phar::SHA1); $this->phar->startBuffering(); $this->printTaskInfo('Packing {file-count} files into phar', ['file-count' => count($this->files)]); $this->startProgressIndicator(); foreach ($this->files as $path => $content) { $this->phar->addFromString($path, $content); $this->advanceProgressIndicator(); } $this->phar->stopBuffering(); $this->advanceProgressIndicator(); if ($this->compress and in_array('GZ', \Phar::getSupportedCompression())) { if (count($this->files) > 1000) { $this->printTaskInfo('Too many files. Compression DISABLED'); } else { $this->printTaskInfo('{filename} compressed', ['filename' => $this->filename]); $this->phar = $this->phar->compressFiles(\Phar::GZ); } } $this->advanceProgressIndicator(); $this->stopProgressIndicator(); $this->printTaskSuccess('{filename} produced', ['filename' => $this->filename]); return Result::success($this, '', ['time' => $this->getExecutionTime()]); }
/** * Test that the reading is successful. * * @return void * * @dataProvider testReadingFlagsProvider */ public function testReading($compression, $signatureName, $signatureFlag) { $pharfile = $this->getTempFile('temp.phar'); $phar = new \Phar($pharfile, 0, 'temp.phar'); $phar->startBuffering(); $phar->addFromString('/bin/script', $fileData = <<<EOF #!/usr/bin/php <?php echo 'hello world'; EOF ); $phar->setDefaultStub('/bin/script', '/web/index'); $phar->stopBuffering(); $phar->setSignatureAlgorithm($signatureFlag); if ($compression !== \Phar::NONE) { $phar->compressFiles($compression); } unset($phar); $reader = new PharReader(); $phar = $reader->load($pharfile); $this->assertEquals('temp.phar', $phar->getAlias()); $this->assertTrue($phar->isSigned()); $this->assertEquals($signatureName, $phar->getSignatureAlgorithm()); $files = $phar->getFiles(); $this->assertEquals('bin/script', $files[0]->getFilename()); $this->assertEquals($fileData, $files[0]->getContent()); }
/** * Finish saving the package */ function close() { if ($this->phar->isFileFormat(Phar::ZIP) && $this->compression !== Phar::NONE) { $this->phar->compressFiles($this->compression); } $this->phar->stopBuffering(); $newphar = $this->phar; $ext = str_replace(array('.tar', '.zip', '.tgz', '.phar'), array('', '', '', ''), basename($this->path)) . '.'; $ext = substr($ext, strpos($ext, '.')); if (count($this->others)) { foreach ($this->others as $pathinfo) { // remove the old file $newpath = str_replace(array('.tar', '.zip', '.tgz', '.phar'), array('', '', '', ''), $this->path); $newpath .= '.' . $pathinfo[0]; if (file_exists($newpath)) { unlink($newpath); } $extension = $ext . $pathinfo[0]; $fileformat = $pathinfo[1]; $compression = $pathinfo[2]; if ($fileformat != Phar::PHAR) { $newphar = $newphar->convertToData($fileformat, $compression, $extension); } else { $newphar = $newphar->convertToExecutable($fileformat, $compression, $extension); } } } }
public static function convertVendorsToPhar(Event $event) { $vendorDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'vendor'; $phars = []; echo "Converting vendor package dirs to phar...\n"; foreach (new \DirectoryIterator($vendorDir) as $dir) { if (in_array($dir->getFilename(), ['..', '.', 'composer']) || !$dir->isDir()) { continue; } foreach (new \DirectoryIterator($dir->getRealPath()) as $subDir) { if (in_array($subDir->getFilename(), ['..', '.']) || !$subDir->isDir()) { continue; } echo "... " . $dir->getFilename() . '/' . $subDir->getFilename() . "\n"; $fName = $subDir->getRealPath() . '.phar'; $fNameTmp = $fName . '.tmp'; $phar = new \Phar($fNameTmp); $phar->buildFromDirectory($subDir->getRealPath(), '#\\.(?!git)#'); if (\Phar::canCompress(\Phar::GZ)) { $phar->compressFiles(\Phar::GZ); } else { if (\Phar::canCompress(\Phar::BZ2)) { $phar->compressFiles(\Phar::BZ2); } } if (file_exists($fName)) { unlink($fName); } unset($phar); rename($fNameTmp, $fName); //delDirTree($subDir->getRealPath()); $phars[$dir->getFilename() . '/' . $subDir->getFilename()] = str_replace(DIRECTORY_SEPARATOR, '/', str_replace($vendorDir, '', $fName)); } } echo "\nConverting autoload files: \n"; $autoloadFiles = ['composer/autoload_classmap.php', 'composer/autoload_files.php', 'composer/autoload_namespaces.php', 'composer/autoload_psr4.php']; foreach ($autoloadFiles as $file) { echo $file . "\n"; $filePath = $vendorDir . DIRECTORY_SEPARATOR . $file; $content = file_get_contents($filePath); $content = preg_replace('#(?<!\'phar://\' . )\\$vendorDir\\s+.\\s+\'(/[-\\w\\d_]+/[-\\w\\d_]+)#', '\'phar://\' . $vendorDir . \'$1.phar', $content); if ($content) { file_put_contents($filePath, $content); } } echo "\nComplete!\n"; }
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 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; }
/** * Finalize the project. * * @return void */ public function finalize() { // disabled for interoperability with systems without gzip ext $this->phar->compressFiles(\Phar::GZ); $filename = $this->configuration->get('phar'); $this->phar->getPharchive()->setAlias(basename($filename)); $writer = new PharWriter(); $writer->save($this->phar->getPharchive(), $filename); unset($this->phar); chmod($filename, 0755); }
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()); } }
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; }
/** * Finish saving the package */ function close() { if ($this->phar->isFileFormat(\Phar::ZIP) && $this->compression !== \Phar::NONE) { $this->phar->compressFiles($this->compression); } if (null !== $this->pkcs12) { $certpath = str_replace(array('.tar', '.zip', '.tgz', '.phar'), array('', '', '', ''), $this->path); $this->phar->setSignatureAlgorithm(\Phar::OPENSSL, $this->privatekey); file_put_contents($certpath . '.pem', $this->x509cert); file_put_contents($this->path . '.pubkey', $this->publickey); } elseif (!$this->phar->isFileFormat(\Phar::ZIP)) { $this->phar->setSignatureAlgorithm(\Phar::SHA1); } $this->phar->stopBuffering(); $ext = str_replace(array('.tar', '.zip', '.tgz', '.phar'), array('', '', '', ''), basename($this->path)) . '.'; $ext = substr($ext, strpos($ext, '.')); $newphar = $this->phar; if (count($this->others)) { foreach ($this->others as $pathinfo) { // remove the old file $pubkeypath = $newpath = str_replace(array('.tar', '.zip', '.tgz', '.phar'), array('', '', '', ''), $this->path); $newpath .= '.' . $pathinfo[0]; if (file_exists($newpath)) { unlink($newpath); } $extension = $ext . $pathinfo[0]; $fileformat = $pathinfo[1]; $compression = $pathinfo[2]; if ($fileformat != \Phar::PHAR) { $newphar = $newphar->convertToData($fileformat, $compression, $extension); } else { $newphar = $newphar->convertToExecutable($fileformat, $compression, $extension); } if (isset($pkey)) { $newphar->setSignatureAlgorithm(\Phar::OPENSSL, $this->privatekey); file_put_contents($pubkeypath . '.' . $pathinfo[0] . '.pubkey', $this->publickey); } else { $newphar->setSignatureAlgorithm(\Phar::SHA1); } } } }
public function run() { $this->printTaskInfo("creating <info>{$this->filename}</info>"); $this->phar->setSignatureAlgorithm(\Phar::SHA1); $this->phar->startBuffering(); $this->printTaskInfo('packing ' . count($this->files) . ' files into phar'); $progress = new ProgressHelper(); $progress->start($this->getOutput(), count($this->files)); foreach ($this->files as $path => $content) { $this->phar->addFromString($path, $content); $progress->advance(); } $this->phar->stopBuffering(); $progress->finish(); if ($this->compress and in_array('GZ', \Phar::getSupportedCompression())) { $this->printTaskInfo($this->filename . " compressed"); $this->phar = $this->phar->compressFiles(\Phar::GZ); } $this->printTaskInfo($this->filename . " produced"); return Result::success($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 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(); }
public function build($stub, $filename) { if (file_exists($filename)) { unlink($filename); } $phar = new \Phar($filename, 0, 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']); } $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(); }
/** * Creates a PHAR (PHP Archive) file from an entire directory. * * @param string $dir The directory we want to create a PHAR file for. * * @param string $to The new PHAR file location; with a `.phar` extension. * * @param string $stub_file Stub file path. The contents of this stub file will be used as * the stub for the resulting PHAR file. Required for all PHARs created by this routine. * A final call to `__HALT_COMPILER();` is automatically appended by this routine. * * @param boolean $strip_ws Optional. Defaults to a TRUE value (highly recommended). * If this is TRUE; any PHP files in the archive will be further reduced in filesize by this routine. * This is made possible by the `php_strip_whitespace()` function. * * @param boolean $compress Optional. Defaults to a TRUE value (highly recommended). * If this is TRUE; any compressable files in the archive will be further reduced in filesize. * * @param string|array $compressable_extensions Optional. An array of GZIP-compressable extensions. * This will default to only those which are 100% webPhar-compatible: `array('php', 'phps')`. * Or, you can provide your own array of compressable extensions. * * @param string $is_phar_var_suffix Optional. Defaults to `stub`. * A global variable at the top of your PHAR stub file will be declared as follows. * `$GLOBALS['is_phar_'.$is_phar_var_suffix] = 'phar://'.__FILE__;` (just a helpful identifier). * * @return string The new PHAR file path; else an exception is thrown on any type of failure. * * @throws exception If invalid types are passed through arguments list. * @throws exception If `$dir` is empty, does NOT exist; or is NOT readable for any reason. * @throws exception If `$to` is empty, or is NOT specified with a `.phar` extension. * @throws exception If `$to` parent directory does NOT exist; or is not writable. * @throws exception If `$stub_file` is empty, does NOT exist; or is NOT readable for any reason. * @throws exception If `$compressable_extensions` or `$is_phar_var_suffix` is empty. * @throws \exception If any Phar class failures occur. The Phar class may throw exceptions. * @throws exception On any type of failure (e.g. NOT successful). * * @WARNING This routine can become resource intensive on large directories. * Mostly because of the compression routines applied here intuitively. It takes some time. * See: {@link env::maximize_time_memory_limits()} */ public function phar_to($dir, $to, $stub_file, $strip_ws = TRUE, $compress = TRUE, $compressable_extensions = array('php', 'phps'), $is_phar_var_suffix = 'stub') { $this->check_arg_types('string:!empty', 'string:!empty', 'string:!empty', 'boolean', 'boolean', 'array:!empty', 'string:!empty', func_get_args()); $dir = $this->n_seps($dir); $to = $this->n_seps($to); $to_dir = $this->n_seps_up($to); if (!is_dir($dir)) { throw $this->©exception($this->method(__FUNCTION__) . '#source_dir_missing', get_defined_vars(), $this->__('Unable to PHAR a directory (source `dir` missing).') . sprintf($this->__('Non-existent source directory: `%1$s`.'), $dir)); } if (!is_readable($dir)) { throw $this->©exception($this->method(__FUNCTION__) . '#read_write_issues', get_defined_vars(), $this->__('Unable to PHAR a directory; not readable, due to permission issues.') . ' ' . sprintf($this->__('Need this directory to be readable please: `%1$s`.'), $dir)); } if (file_exists($to)) { throw $this->©exception($this->method(__FUNCTION__) . '#existing_phar', get_defined_vars(), $this->__('Unable to PHAR a directory; destination PHAR file already exists.') . ' ' . sprintf($this->__('Please delete this file first: `%1$s`.'), $to)); } if ($this->extension($to) !== 'phar') { throw $this->©exception($this->method(__FUNCTION__) . '#invalid_phar_file', get_defined_vars(), $this->__('Unable to PHAR a directory; invalid destination PHAR file.') . ' ' . sprintf($this->__('Please use a `.phar` extension instead of: `%1$s`.'), $to)); } if (!is_dir($to_dir)) { throw $this->©exception($this->method(__FUNCTION__) . '#phar_to_dir_missing', get_defined_vars(), $this->__('Destination PHAR directory does NOT exist yet.') . ' ' . sprintf($this->__('Please check this directory: `%1$s`.'), $to_dir)); } if (!is_writable($to_dir)) { throw $this->©exception($this->method(__FUNCTION__) . '#read_write_issues', get_defined_vars(), $this->__('Unable to PHAR a directory; destination not writable due to permission issues.') . ' ' . sprintf($this->__('Need this directory to be writable please: `%1$s`.'), $to_dir)); } if (!\Phar::canWrite()) { throw $this->©exception($this->method(__FUNCTION__) . '#read_write_issues', get_defined_vars(), $this->__('Unable to PHAR a directory; PHP configuration does NOT allow write access.') . ' ' . $this->__('Need this INI setting please: `phar.readonly = 0`.')); } if (!is_file($stub_file)) { throw $this->©exception($this->method(__FUNCTION__) . '#missing_stub_file', get_defined_vars(), $this->__('Unable to PHAR a directory; missing stub file.') . ' ' . sprintf($this->__('File does NOT exist: `%1$s`.'), $stub_file)); } if (!is_readable($stub_file)) { throw $this->©exception($this->method(__FUNCTION__) . '#stub_file_issues', get_defined_vars(), $this->__('Unable to PHAR a directory; permission issues with stub file.') . ' ' . sprintf($this->__('Need this file to be writable please: `%1$s`.'), $stub_file)); } // Phar class throws exceptions on failure. $_stub_file_is_phar_var = '$GLOBALS[\'is_phar_' . $this->©string->esc_sq($is_phar_var_suffix) . '\'] = \'phar://\'.__FILE__;'; $_stub_file_contents = $strip_ws ? $this->©php->strip_whitespace($stub_file) : file_get_contents($stub_file); $_stub_file_contents = trim(preg_replace('/\\W\\?\\>\\s*$/', '', $_stub_file_contents, 1)); // No close tag & trim. $_stub_file_contents = preg_replace('/\\<\\?php|\\<\\?/i', '<?php ' . $_stub_file_is_phar_var, $_stub_file_contents, 1); $_stub_file_contents = preg_replace('/\\W__HALT_COMPILER\\s*\\(\\s*\\)\\s*;/i', '', $_stub_file_contents, 1) . ' __HALT_COMPILER();'; $_phar = new \Phar($to, $this->iteration_flags()); $_phar->startBuffering(); // Don't create file yet (wait until we're done here). $_phar->setStub($_stub_file_contents); // Defines the stub for this PHAR file. if (!$strip_ws && !$compress) { $_phar->buildFromDirectory($dir); } else { $_strippable_extensions = array('php'); $_regex_compressable_extensions = $this->©string->preg_quote_deep($compressable_extensions, '/'); $_regex_compressable_extensions = '/\\.(?:' . implode('|', $_regex_compressable_extensions) . ')$/i'; $_temp_dir = $this->temp() . '/' . $this->©string->unique_id() . '-' . basename($dir); $this->copy_to($dir, $_temp_dir); $_temp_dir_iteration = $this->iteration($_temp_dir); if ($strip_ws) { foreach ($_temp_dir_iteration as $_dir_file) { if (!$_dir_file->isFile()) { continue; } $_path = $_dir_file->getPathname(); $_phar_path = $_dir_file->getSubPathName(); $_extension = $this->©file->extension($_path); if (in_array($_extension, $_strippable_extensions, TRUE)) { file_put_contents($_path, $this->©php->strip_whitespace($_path, TRUE)); } } } $_phar->buildFromDirectory($_temp_dir, $_regex_compressable_extensions); if ($compress && $_phar->count()) { // Compressing files? $_phar->compressFiles(\Phar::GZ); } foreach ($_temp_dir_iteration as $_dir_file) { if (!$_dir_file->isFile()) { continue; } $_path = $_dir_file->getPathname(); $_phar_path = $_dir_file->getSubPathName(); $_extension = $this->©file->extension($_path); if (!in_array($_extension, $compressable_extensions, TRUE)) { $_phar->addFile($_path, $_phar_path); } } } $_phar->stopBuffering(); // Write to disk now. unset($_phar, $_stub_file_is_phar_var, $_stub_file_contents, $_strippable_extensions, $_regex_compressable_extensions); unset($_temp_dir_iteration, $_dir_file, $_path, $_phar_path, $_extension); if (isset($_temp_dir)) { // A little more housekeeping now. $this->delete($_temp_dir); } unset($_temp_dir); return $to; // It's a good day in Eureka! }
/** * Generates a new phar archive. * * @param array $args The command line arguments. * * @return void */ public function run(array $args) { $this->parseArguments($args); $tempName = $this->copySource(); $phar = new Phar($this->getTargetPathname(), 0, $this->getAlias()); $phar->startBuffering(); $phar->buildFromDirectory($tempName); $phar->compressFiles(Phar::GZ); $phar->setStub($this->getStub()); $phar->stopBuffering(); chmod($this->getTargetPathname(), 0775); }
/** * Build and configure Phar object. * * @return Phar */ private function buildPhar() { $phar = new Phar($this->destinationFile); $phar->setSignatureAlgorithm($this->signatureAlgorithm); /* * File compression, if needed. */ if (Phar::NONE != $this->compression) { $phar->compressFiles($this->compression); } $phar->setDefaultStub($this->cliStubFile, $this->webStubFile); if ($metadata = $this->metadata->toArray()) { $phar->setMetadata($metadata); } return $phar; }
function phar_module($module, $key_path) { @mkdir(dirname(dirname(__FILE__)) . "/tmp/"); $phar = new \Phar(dirname(dirname(__FILE__)) . "/tmp/" . $module . '.phar', 0, $module . '.phar'); $phar->buildFromDirectory(dirname(dirname(__FILE__)) . "/app/modules/" . $module); //$phar->setStub($phar->createDefaultStub('__module__.php')); $phar->compressFiles(\Phar::GZ); if ($key_path) { $private = openssl_get_privatekey(file_get_contents($key_path)); $pkey = ''; openssl_pkey_export($private, $pkey); $phar->setSignatureAlgorithm(\Phar::OPENSSL, $pkey); } }
<?php if (!class_exists('Phar')) { die('Class Phar not found.'); } if (is_file('wasp.phar')) { unlink('wasp.phar'); } $arj = new Phar('wasp.phar'); $arj->setStub('<?php define( \'CORE_PATH\', \'phar://\' . __FILE__ ); require( CORE_PATH . \'/bootstrap.php\' ); __HALT_COMPILER(); ?>'); $arj->buildFromDirectory('wasp/'); $arj->setSignatureAlgorithm(PHAR::MD5); if (Phar::canCompress(Phar::GZ)) { $arj->compressFiles(Phar::GZ); } else { if (Phar::canCompress(Phar::BZ2)) { $arj->compressFiles(Phar::BZ2); } } echo 'wasp.phar created!';
$pname = 'phar://' . $fname; $file = '<?php __HALT_COMPILER(); ?>'; $files = array(); $files['a'] = 'a'; $files['b'] = 'b'; $files['c'] = 'c'; include 'files/phar_test.inc'; $phar = new Phar($fname); var_dump(file_get_contents($pname . '/a')); var_dump($phar['a']->isCompressed()); var_dump(file_get_contents($pname . '/b')); var_dump($phar['b']->isCompressed()); var_dump(file_get_contents($pname . '/c')); var_dump($phar['c']->isCompressed()); $phar = new Phar($fname); $phar->compressFiles(Phar::BZ2); var_dump(file_get_contents($pname . '/a')); var_dump($phar['a']->isCompressed(Phar::GZ)); var_dump($phar['a']->isCompressed(Phar::BZ2)); var_dump(file_get_contents($pname . '/b')); var_dump($phar['b']->isCompressed(Phar::GZ)); var_dump($phar['b']->isCompressed(Phar::BZ2)); var_dump(file_get_contents($pname . '/c')); var_dump($phar['c']->isCompressed(Phar::GZ)); var_dump($phar['b']->isCompressed(Phar::BZ2)); ?> ===DONE=== <?php error_reporting(0); unlink(dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.phar'); unlink(dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.phar.php');
public function makePharPlugin($pluginName) { if ($pluginName === "" or !($plugin = $this->getServer()->getPluginManager()->getPlugin($pluginName)) instanceof Plugin) { $this->getLogger()->alert("잘못된 플러그인 이름, 이름을 다시 확인해주세요"); return; } $description = $plugin->getDescription(); if (!$plugin->getPluginLoader() instanceof FolderPluginLoader) { $this->getLogger()->alert("플러그인 " . $description->getName() . " 은 이미 PHAR 상태입니다."); return; } $pharPath = $this->getServer()->getDataPath() . "localhost" . DIRECTORY_SEPARATOR . $pluginName . DIRECTORY_SEPARATOR . $description->getName() . "-release" . ".phar"; if (file_exists($pharPath)) { $this->getLogger()->info("Phar 파일 덮어쓰기중..."); \Phar::unlinkArchive($pharPath); } $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->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(array("\\", $filePath), array("/", ""), $file), "/"); if ($path[0] === "." or strpos($path, "/.") !== false) { continue; } $phar->addFile($file, $path); } $phar->compressFiles(\Phar::GZ); $phar->stopBuffering(); $this->getLogger()->info("PHAR이 해당 플러그인 소스폴더 안에 생성되었습니다. "); $this->getLogger()->info("( " . $pharPath . " )"); }
/** * @param Phar $phar * @param string $baseDirectory */ private function compressAllFiles(Phar $phar, $baseDirectory) { $total = 0; $phar->startBuffering(); foreach ($this->filesets as $fileset) { $dir = $fileset->getDir($this->project); $msg = sprintf("Fileset %s ...", $dir); $this->log($msg, Project::MSG_VERBOSE); $added = $phar->buildFromIterator($fileset, $baseDirectory); $total += count($added); } $phar->stopBuffering(); if (Phar::NONE === $this->compression) { return; } $msg = sprintf("Compressing %d files (compression: %s) ... ", $total, $this->getCompressionLabel()); $this->log($msg, Project::MSG_VERBOSE); // safeguard open files soft limit if (function_exists('posix_getrlimit')) { $rlimit = posix_getrlimit(); if ($rlimit['soft openfiles'] < $total + 5) { $msg = sprintf("Limit of openfiles (%d) is too low.", $rlimit['soft openfiles']); $this->log($msg, Project::MSG_VERBOSE); } } // safeguard compression try { $phar->compressFiles($this->compression); } catch (BadMethodCallException $e) { if ($e->getMessage() === 'unable to create temporary file') { $msg = sprintf("Info: Check openfiles limit it must be %d or higher", $total + 5); throw new BadMethodCallException($msg, 0, $e); } throw $e; } }
$fname = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.phar.zip'; $fname2 = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '2.phar.zip'; $fname3 = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '3.phar.zip'; $phar = new Phar($fname); $phar->setStub('<?php echo "first stub\\n"; __HALT_COMPILER(); ?>'); $phar->setAlias('hio'); $files = array(); $files['a'] = 'a'; $files['b'] = 'b'; $files['c'] = 'c'; foreach ($files as $n => $file) { $phar[$n] = $file; } $phar->stopBuffering(); echo $phar->getAlias() . "\n"; $phar->setAlias('test'); echo $phar->getAlias() . "\n"; // test compression $phar->compressFiles(Phar::GZ); copy($fname, $fname2); $phar->setAlias('unused'); $p2 = new Phar($fname2); echo $p2->getAlias(), "\n"; $p2->compressFiles(Phar::BZ2); copy($fname2, $fname3); $p2->setAlias('unused2'); $p3 = new Phar($fname3); echo $p3->getAlias(), "\n"; ?> ===DONE===
/** * Build and configure Phar object. * * @return Phar */ private function buildPhar() { $phar = new Phar($this->destinationFile, 0, $this->alias); $phar->setSignatureAlgorithm($this->signatureAlgorithm); /* * File compression, if needed. */ if (Phar::NONE != $this->compression) { $phar->compressFiles($this->compression); } if (isset($this->customStubPath)) { $phar->setStub(file_get_contents($this->customStubPath)); } else { $phar->setDefaultStub($this->cliStubFile, $this->webStubFile); } if ($metadata = $this->metadata->toArray()) { $phar->setMetadata($metadata); } if (!empty($this->alias)) { $phar->setAlias($this->alias); } return $phar; }
<?php $fname = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.phar.zip.php'; $pname = 'phar://' . $fname; $phar = new Phar($fname); $phar['a'] = 'a'; $phar['b'] = 'b'; $phar['c'] = 'c'; var_dump(file_get_contents($pname . '/a')); var_dump($phar['a']->isCompressed()); var_dump(file_get_contents($pname . '/b')); var_dump($phar['b']->isCompressed()); var_dump(file_get_contents($pname . '/c')); var_dump($phar['c']->isCompressed()); $phar->compressFiles(Phar::GZ); var_dump(file_get_contents($pname . '/a')); var_dump($phar['a']->isCompressed(Phar::BZ2)); var_dump($phar['a']->isCompressed(Phar::GZ)); var_dump(file_get_contents($pname . '/b')); var_dump($phar['b']->isCompressed(Phar::BZ2)); var_dump($phar['b']->isCompressed(Phar::GZ)); var_dump(file_get_contents($pname . '/c')); var_dump($phar['b']->isCompressed(Phar::BZ2)); var_dump($phar['c']->isCompressed(Phar::GZ)); ?> ===DONE===
$a->setDefaultStub('oops'); } catch (Exception $e) { echo $e->getMessage() . "\n"; } try { $a->setSignatureAlgorithm(Phar::MD5); } catch (Exception $e) { echo $e->getMessage() . "\n"; } $a->compress(array()); try { $a->compress(1); } catch (Exception $e) { echo $e->getMessage() . "\n"; } $a->compressFiles(array()); try { $a->decompressFiles(); } catch (Exception $e) { echo $e->getMessage() . "\n"; } $a->copy(array()); try { $a->copy('a', 'b'); } catch (Exception $e) { echo $e->getMessage() . "\n"; } $a->offsetExists(array()); $a->offsetGet(array()); ini_set('phar.readonly', 0); $a->offsetSet(array());