/** * Compresses a file or combination of files in the archive * @param array|zibo\library\filesystem\File $source File objects of the files to compress * @param zibo\library\filesystem\File $prefix The path for the files in the archive * @return null * @throws zibo\library\archive\exception\ArchiveException when no source or an invalid source has been provided * @throws zibo\library\archive\exception\ArchiveException when the archive could not be created * @throws zibo\library\archive\exception\ArchiveException when the phars could not be written due to the configuration of PHP */ public function compress($source, File $prefix = null) { if (!PhpPhar::canWrite()) { throw new ArchiveException('Phar library is not allowed to write phars. Check the PHP configuration for the phar.readonly setting.'); } if (empty($source)) { throw new ArchiveException('No files provided'); } $path = $this->file->getAbsolutePath(); $parent = $this->file->getParent(); $parent->create(); if (!is_array($source)) { $source = array($source); } try { $phar = new PhpPhar($path); } catch (UnexpectedValueException $e) { throw new ArchiveException('Could not open ' . $path); } if (!$phar->isWritable()) { throw new ArchiveException('Archive ' . $this->file->getAbsolutePath() . ' is not writable'); } $phar->startBuffering(); foreach ($source as $file) { if (!$file instanceof File) { throw new ArchiveException('Invalid source provided: ' . $file); } $this->compressFile($phar, $file, $prefix); } $phar->stopBuffering(); }
/** * Archive creator for phar, tar, tgz and zip archives. * * @param string path to primary archive * @param string|false stub or false to use default stub of phar archives * @param int one of Phar::TAR, Phar::PHAR, or Phar::ZIP * @param int if the archive can be compressed (phar and tar), one of Phar::GZ, Phar::BZ2 or Phar::NONE * for no compression * @param array an array of arrays containing information on additional archives to create. The indices are: * * 0. extension (tar/tgz/zip) * 1. format (Phar::TAR, Phar::ZIP, Phar::PHAR) * 2. compression (Phar::GZ, Phar::BZ2, Phar::NONE) */ function __construct($path, $stub = false, $fileformat = Phar::TAR, $compression = Phar::GZ, array $others = null) { if (!class_exists('Phar')) { throw new \Pyrus\Developer\Creator\Exception('Phar extension is not available'); } if (!Phar::canWrite() || !Phar::isValidPharFilename($path, true)) { $this->_classname = 'PharData'; } $this->path = $path; $this->compression = $compression; $this->format = $fileformat; $this->others = $others; $this->stub = $stub; }
/** * Archive creator for phar, tar, tgz and zip archives. * * @param string path to primary archive * @param string|false stub or false to use default stub of phar archives * @param int one of Phar::TAR, Phar::PHAR, or Phar::ZIP * @param int if the archive can be compressed (phar and tar), one of Phar::GZ, Phar::BZ2 or Phar::NONE * for no compression * @param array an array of arrays containing information on additional archives to create. The indices are: * * 0. extension (tar/tgz/zip) * 1. format (Phar::TAR, Phar::ZIP, Phar::PHAR) * 2. compression (Phar::GZ, Phar::BZ2, Phar::NONE) * @param string PKCS12 certificate to be used to sign the archive. This must be a certificate issued * by a certificate authority, self-signed certs will not be accepted by Pyrus * @param string passphrase, if any, for the PKCS12 certificate. */ function __construct($path, $stub = false, $fileformat = \Phar::TAR, $compression = \Phar::GZ, array $others = null, $releaser = null, \PEAR2\Pyrus\Package $new = null, $pkcs12 = null, $passphrase = '') { if (!class_exists('Phar')) { throw new \PEAR2\Pyrus\Developer\Creator\Exception('Phar extension is not available'); } if (!\Phar::canWrite() || !\Phar::isValidPharFilename($path, true)) { $this->_classname = 'PharData'; } $this->path = $path; $this->compression = $compression; $this->format = $fileformat; $this->others = $others; $this->stub = $stub; if ($pkcs12 && !extension_loaded('openssl')) { throw new \PEAR2\Pyrus\Developer\Creator\Exception('Unable to use ' . 'OpenSSL signing of phars, enable the openssl PHP extension'); } $this->pkcs12 = $pkcs12; $this->passphrase = $passphrase; if (null !== $this->pkcs12) { $cert = array(); $pkcs = openssl_pkcs12_read(file_get_contents($this->pkcs12), $cert, $this->passphrase); if (!$pkcs) { throw new \PEAR2\Pyrus\Developer\Creator\Exception('Unable to process openssl key'); } $private = openssl_pkey_get_private($cert['pkey']); if (!$private) { throw new \PEAR2\Pyrus\Developer\Creator\Exception('Unable to extract private openssl key'); } $pub = openssl_pkey_get_public($cert['cert']); $info = openssl_x509_parse($cert['cert']); $details = openssl_pkey_get_details($pub); if (true !== openssl_x509_checkpurpose($cert['cert'], X509_PURPOSE_SSL_SERVER, \PEAR2\Pyrus\Channel\RemotePackage::authorities())) { throw new \PEAR2\Pyrus\Developer\Creator\Exception('releasing maintainer\'s certificate is invalid'); } // now verify that this cert is in fact the releasing maintainer's certificate // by verifying that alternate name is the releaser's email address if (!isset($info['subject']) || !isset($info['subject']['emailAddress'])) { throw new \PEAR2\Pyrus\Developer\Creator\Exception('releasing maintainer\'s certificate does not contain' . ' an alternate name corresponding to the releaser\'s email address'); } if ($info['subject']['emailAddress'] != $new->maintainer[$releaser]->email) { throw new \PEAR2\Pyrus\Developer\Creator\Exception('releasing maintainer\'s certificate ' . 'alternate name does not match the releaser\'s email address ' . $new->maintainer[$releaser]->email); } $pkey = ''; openssl_pkey_export($private, $pkey); $this->x509cert = $cert['cert']; $this->publickey = $details['key']; $this->privatekey = $pkey; } }
/** * Fire event * * @return void */ public function __invoke(ConsoleEvent $event) { $output = $event->getOutput(); $output->writeln("<comment>Dependencies validation:</comment>"); $output->write(str_pad("Phar extension is loaded?", 30, '.')); $error = false; if (!extension_loaded('phar')) { $output->writeln('<error>NOK</error>'); $error = true; } else { $output->writeln('<info>OK</info>'); } $output->write(str_pad("phar.readonly is On?", 30, '.')); if (!\Phar::canWrite()) { $output->writeln('<error>NOK</error>'); $error = true; } else { $output->writeln('<info>OK</info>'); } if ($error) { exit(1); } }
/** * 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! }
/** * @expectedException \Symfony\Component\Filesystem\Exception\IOException */ public function testTempnamWithPharSchemeFails() { // Skip test if Phar disabled phar.readonly must be 0 in php.ini if (!\Phar::canWrite()) { $this->markTestSkipped('This test cannot run when phar.readonly is 1.'); } $scheme = 'phar://'; $dirname = $scheme . $this->workspace; $pharname = 'foo.phar'; new \Phar($this->workspace . '/' . $pharname, 0, $pharname); // The phar:// stream does not support mode x: fails to create file, errors "failed to open stream: phar error: "$filename" is not a file in phar "$pharname"" and returns false $this->filesystem->tempnam($dirname, $pharname . '/bar'); }
<?php ## Хранение бинарных файлов. try { $phar = new Phar('./gallery.phar', 0, 'gallery.phar'); // Для записи директив phar.readonly конфигурационного // файла php.ini должна быть установлена в 0 или Off if (Phar::canWrite()) { // Буферизация записи, ничего не записывается, до // тех пор, пока не будет вызван метод stopBuffering() $phar->startBuffering(); // Добавление всех файлов из папки photos foreach (glob('../composer/photos/*') as $jpg) { $phar[basename($jpg)] = file_get_contents($jpg); } // Назначаем файл-заглушку $phar['show.php'] = file_get_contents('show.php'); $phar->setDefaultStub('show.php', 'show.php'); // Сохранение результатов на жесткий диск $phar->stopBuffering(); } else { echo 'PHAR-архив не может быть бы записан'; } } catch (Exception $e) { echo 'Невозможно открыть PHAR-архив: ', $e; }
<?php require __DIR__ . '/../piecrust.php'; piecrust_setup('compiler'); if (!Phar::canWrite()) { die("Can't create Phar file because 'phar.readonly' is enabled in 'php.ini'." . PHP_EOL); } $pharFile = 'piecrust.phar'; if ($argc > 1) { $pharFile = $argv[1]; } $compiler = new PieCrust\Compiler(); $compiler->compile($pharFile);
var_dump(Phar::canWrite()); ini_set('phar.require_hash', 0); ini_set('phar.readonly', 0); ?> on <?php var_dump(ini_set('phar.require_hash', 'on')); var_dump(ini_set('phar.readonly', 'on')); var_dump(ini_get('phar.require_hash')); var_dump(ini_get('phar.readonly')); var_dump(Phar::canWrite()); ini_set('phar.require_hash', 0); ini_set('phar.readonly', 0); ?> true <?php var_dump(ini_set('phar.require_hash', 'true')); var_dump(ini_set('phar.readonly', 'true')); var_dump(Phar::canWrite()); var_dump(ini_get('phar.require_hash')); var_dump(ini_get('phar.readonly')); ?> 0 <?php var_dump(ini_set('phar.require_hash', 0)); var_dump(ini_set('phar.readonly', 0)); var_dump(Phar::canWrite()); var_dump(ini_get('phar.require_hash')); var_dump(ini_get('phar.readonly')); ?> ===DONE===
<?php ## Сжатие архива. try { $phar = new Phar('compress.phar', 0, 'compress.phar'); if (Phar::canWrite() && Phar::canCompress()) { $phar->startBuffering(); foreach (glob('../composer/photos/*') as $jpg) { $phar[basename($jpg)] = file_get_contents($jpg); } // Назначаем файл-заглушку $phar['show.php'] = file_get_contents('show.php'); $phar->setDefaultStub('show.php', 'show.php'); // Сжимаем файл $phar->compress(Phar::GZ); $phar->stopBuffering(); } else { echo 'PHAR-архив не может быть бы записан'; } } catch (Exception $e) { echo 'Невозможно открыть PHAR-архив: ', $e; }
* copy is found, a copy of the license template can be found at: * http://www.opensource.org/licenses/bsd-license.php * * @package Jazz * @subpackage Startup * @author Michael Luster <*****@*****.**> * @copyright Copyright (c) iBayou, Michael Luster * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @link http://phpjazz.sourceforge.net */ set_time_limit(600); $root = dirname(dirname(__FILE__)) . '/library'; set_include_path($root . PATH_SEPARATOR . get_include_path()); require_once 'Jazz/Util.php'; ini_set('phar.readonly', 0); if (Phar::canWrite() === true) { $phar = new Phar(dirname(__FILE__) . '/Jazz.phar', 0); $phar->startBuffering(); $phar->setStub($phar->createDefaultStub('stub.php')); $phar->addFromString('stub.php', '<?php '); $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)); foreach ($dir as $file) { /* @var DirectoryIterator $file */ $name = $file->getFilename(); $contents = formatFileContents($file->getPathname()); $path = str_replace(array($root, '\\'), array('', '/'), $file->getPathname()); $phar->addFromString($path, $contents); \Jazz\Util::test('added ' . $path); } $phar->stopBuffering(); die('complete');
} else { if (isset($argv[$i + 1]) && $argv[$i + 1][0] !== '-' && false === strpos($arg, '=')) { $ret[ltrim($arg, '-')] = $argv[$i + 1]; ++$i; } else { $ret[ltrim($arg, '-')] = true; } } } return $ret; } info("Phar Builder " . PHAR_BUILDER_VERSION); if ('cli' !== PHP_SAPI) { error("Run for command line only."); } if (false === Phar::canWrite()) { error("Phar can not write, Set \"phar.readonly = Off\" in php.ini."); } $self = array_shift($argv); if (empty($argv[0])) { usage($self); } $path = array_shift($argv); $args = args_parse($argv); $stub = empty($args['stub']) ? '' : $args['stub']; $flags = 0; $files = empty($args['files']) ? '' : $args['files']; $alias = empty($args['alias']) ? basename($path) : $args['alias']; $regex = empty($args['filter']) ? null : $args['filter']; $base_dir = empty($args['path']) ? '' : $args['path']; $arg_compress = empty($args['compress']) ? '' : $args['compress'];