From: Michael Wallner Date: Fri, 4 Dec 2015 14:34:05 +0000 (+0100) Subject: Mergeed back phpng into master X-Git-Tag: v2.0.0RC1~3 X-Git-Url: https://git.m6w6.name/?a=commitdiff_plain;h=167906a41f36f3cd3d16cd56af2f649b11574969;p=m6w6%2Fext-pq Mergeed back phpng into master --- diff --git a/.travis.yml b/.travis.yml index 1ed1390..151ff43 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,7 +23,7 @@ env: before_script: - make -f travis/pecl/Makefile php - - make -f travis/pecl/Makefile pharext/raphf-phpng + - make -f travis/pecl/Makefile pharext/raphf-master - make -f travis/pecl/Makefile ext PECL=pq - psql -U postgres -c "CREATE DATABASE test" diff --git a/EXPERIMENTAL b/EXPERIMENTAL deleted file mode 100644 index e69de29..0000000 diff --git a/gen_travis_yml.php b/gen_travis_yml.php index 19240be..d6a6842 100755 --- a/gen_travis_yml.php +++ b/gen_travis_yml.php @@ -33,7 +33,7 @@ foreach ($env as $e) { before_script: - make -f travis/pecl/Makefile php - - make -f travis/pecl/Makefile pharext/raphf-phpng + - make -f travis/pecl/Makefile pharext/raphf-master - make -f travis/pecl/Makefile ext PECL=pq - psql -U postgres -c "CREATE DATABASE test" diff --git a/package.xml b/package.xml index 4a97e8e..bcd0453 100644 --- a/package.xml +++ b/package.xml @@ -37,27 +37,18 @@ http://pear.php.net/dtd/package-2.0.xsd"> daverandom@php.net yes - 2015-09-05 + 2015-12-04 - 0.6.0 - 0.6.0 + 2.0.0RC1 + 2.0.0 beta - beta + stable BSD, revised @@ -160,9 +151,7 @@ Changes from RC1: - 5.4.0 - 7.0.0 - 7.0.0 + 7.0.0 1.4.0 @@ -170,7 +159,7 @@ Changes from RC1: raphf pecl.php.net - 1.1.0 + 2.0.0dev raphf diff --git a/raphf-1.1.0.ext.phar b/raphf-1.1.0.ext.phar deleted file mode 100755 index 7152acb..0000000 --- a/raphf-1.1.0.ext.phar +++ /dev/null @@ -1,6240 +0,0 @@ -#!/usr/bin/env php -getUser(); - if (!is_dir($temp) && !mkdir($temp, 0700, true)) { - throw new Exception; - } - $this->name = $temp ."/". uniqid($prefix) . $suffix; - } - - private function getUser() { - if (extension_loaded("posix") && function_exists("posix_getpwuid")) { - return posix_getpwuid(posix_getuid())["name"]; - } - return trim(`whoami 2>/dev/null`) - ?: trim(`id -nu 2>/dev/null`) - ?: getenv("USER") - ?: get_current_user(); - } - - /** - * @return string - */ - public function __toString() { - return (string) $this->name; - } -} - - - -namespace pharext; - -/** - * Create a new temporary file - */ -class Tempfile extends \SplFileInfo -{ - /** - * @var resource - */ - private $handle; - - /** - * @param string $prefix uniqid() prefix - * @param string $suffix e.g. file extension - * @throws \pharext\Exception - */ - public function __construct($prefix, $suffix = ".tmp") { - $tries = 0; - $omask = umask(077); - do { - $path = new Tempname($prefix, $suffix); - $this->handle = fopen($path, "x"); - } while (!is_resource($this->handle) && $tries++ < 10); - umask($omask); - - if (!is_resource($this->handle)) { - throw new Exception("Could not create temporary file"); - } - - parent::__construct($path); - } - - /** - * Unlink the file - */ - public function __destruct() { - if (is_file($this->getPathname())) { - @unlink($this->getPathname()); - } - } - - /** - * Close the stream - */ - public function closeStream() { - fclose($this->handle); - } - - /** - * Retrieve the stream resource - * @return resource - */ - public function getStream() { - return $this->handle; - } -} - - - -namespace pharext; - -/** - * Create a temporary directory - */ -class Tempdir extends \SplFileInfo -{ - /** - * @param string $prefix prefix to uniqid() - * @throws \pharext\Exception - */ - public function __construct($prefix) { - $temp = new Tempname($prefix); - if (!is_dir($temp) && !mkdir($temp, 0700, true)) { - throw new Exception("Could not create tempdir: ".error_get_last()["message"]); - } - parent::__construct($temp); - } -} - - - -namespace pharext; - -use ArrayAccess; -use IteratorAggregate; -use RecursiveDirectoryIterator; -use SplFileInfo; - -use pharext\Exception; - -class Archive implements ArrayAccess, IteratorAggregate -{ - const HALT_COMPILER = "\137\137\150\141\154\164\137\143\157\155\160\151\154\145\162\50\51\73"; - const SIGNED = 0x10000; - const SIG_MD5 = 0x0001; - const SIG_SHA1 = 0x0002; - const SIG_SHA256 = 0x0003; - const SIG_SHA512 = 0x0004; - const SIG_OPENSSL= 0x0010; - - private static $siglen = [ - self::SIG_MD5 => 16, - self::SIG_SHA1 => 20, - self::SIG_SHA256 => 32, - self::SIG_SHA512 => 64, - self::SIG_OPENSSL=> 0 - ]; - - private static $sigalg = [ - self::SIG_MD5 => "md5", - self::SIG_SHA1 => "sha1", - self::SIG_SHA256 => "sha256", - self::SIG_SHA512 => "sha512", - self::SIG_OPENSSL=> "openssl" - ]; - - private static $sigtyp = [ - self::SIG_MD5 => "MD5", - self::SIG_SHA1 => "SHA-1", - self::SIG_SHA256 => "SHA-256", - self::SIG_SHA512 => "SHA-512", - self::SIG_OPENSSL=> "OpenSSL", - ]; - - const PERM_FILE_MASK = 0x01ff; - const COMP_FILE_MASK = 0xf000; - const COMP_GZ_FILE = 0x1000; - const COMP_BZ2_FILE = 0x2000; - - const COMP_PHAR_MASK= 0xf000; - const COMP_PHAR_GZ = 0x1000; - const COMP_PHAR_BZ2 = 0x2000; - - private $file; - private $fd; - private $stub; - private $manifest; - private $signature; - private $extracted; - - function __construct($file = null) { - if (strlen($file)) { - $this->open($file); - } - } - - function open($file) { - if (!$this->fd = @fopen($file, "r")) { - throw new Exception; - } - $this->file = $file; - $this->stub = $this->readStub(); - $this->manifest = $this->readManifest(); - $this->signature = $this->readSignature(); - } - - function getIterator() { - return new RecursiveDirectoryIterator($this->extract()); - } - - function extract() { - return $this->extracted ?: $this->extractTo(new Tempdir("archive")); - } - - function extractTo($dir) { - if ((string) $this->extracted == (string) $dir) { - return $this->extracted; - } - foreach ($this->manifest["entries"] as $file => $entry) { - fseek($this->fd, $this->manifest["offset"]+$entry["offset"]); - $path = "$dir/$file"; - $copy = stream_copy_to_stream($this->fd, $this->outFd($path, $entry["flags"]), $entry["csize"]); - if ($entry["osize"] != $copy) { - throw new Exception("Copied '$copy' of '$file', expected '{$entry["osize"]}' from '{$entry["csize"]}"); - } - - $crc = hexdec(hash_file("crc32b", $path)); - if ($crc !== $entry["crc32"]) { - throw new Exception("CRC mismatch of '$file': '$crc' != '{$entry["crc32"]}"); - } - - chmod($path, $entry["flags"] & self::PERM_FILE_MASK); - touch($path, $entry["stamp"]); - } - return $this->extracted = $dir; - } - - function offsetExists($o) { - return isset($this->entries[$o]); - } - - function offsetGet($o) { - $this->extract(); - return new SplFileInfo($this->extracted."/$o"); - } - - function offsetSet($o, $v) { - throw new Exception("Archive is read-only"); - } - - function offsetUnset($o) { - throw new Exception("Archive is read-only"); - } - - function getSignature() { - /* compatible with Phar::getSignature() */ - return [ - "hash_type" => self::$sigtyp[$this->signature["flags"]], - "hash" => strtoupper(bin2hex($this->signature["hash"])), - ]; - } - - function getPath() { - /* compatible with Phar::getPath() */ - return new SplFileInfo($this->file); - } - - function getMetadata($key = null) { - if (isset($key)) { - return $this->manifest["meta"][$key]; - } - return $this->manifest["meta"]; - } - - private function outFd($path, $flags) { - $dirn = dirname($path); - if (!is_dir($dirn) && !@mkdir($dirn, 0777, true)) { - throw new Exception; - } - if (!$fd = @fopen($path, "w")) { - throw new Exception; - } - switch ($flags & self::COMP_FILE_MASK) { - case self::COMP_GZ_FILE: - if (!@stream_filter_append($fd, "zlib.inflate")) { - throw new Exception; - } - break; - case self::COMP_BZ2_FILE: - if (!@stream_filter_append($fd, "bz2.decompress")) { - throw new Exception; - } - break; - } - - } - private function readVerified($fd, $len) { - if ($len != strlen($data = fread($fd, $len))) { - throw new Exception("Unexpected EOF"); - } - return $data; - } - - private function readFormat($format, $fd, $len) { - if (false === ($data = @unpack($format, $this->readVerified($fd, $len)))) { - throw new Exception; - } - return $data; - } - - private function readSingleFormat($format, $fd, $len) { - return current($this->readFormat($format, $fd, $len)); - } - - private function readStringBinary($fd) { - if (($length = $this->readSingleFormat("V", $fd, 4))) { - return $this->readVerified($this->fd, $length); - } - return null; - } - - private function readSerializedBinary($fd) { - if (($length = $this->readSingleFormat("V", $fd, 4))) { - if (false === ($data = unserialize($this->readVerified($fd, $length)))) { - throw new Exception; - } - return $data; - } - return null; - } - - private function readStub() { - $stub = ""; - while (!feof($this->fd)) { - $line = fgets($this->fd); - $stub .= $line; - if (false !== stripos($line, self::HALT_COMPILER)) { - /* check for '?>' on a separate line */ - if ('?>' === $this->readVerified($this->fd, 2)) { - $stub .= '?>' . fgets($this->fd); - } else { - fseek($this->fd, -2, SEEK_CUR); - } - break; - } - } - return $stub; - } - - private function readManifest() { - $current = ftell($this->fd); - $header = $this->readFormat("Vlen/Vnum/napi/Vflags", $this->fd, 14); - $alias = $this->readStringBinary($this->fd); - $meta = $this->readSerializedBinary($this->fd); - $entries = []; - for ($i = 0; $i < $header["num"]; ++$i) { - $this->readEntry($entries); - } - $offset = ftell($this->fd); - if (($length = $offset - $current - 4) != $header["len"]) { - throw new Exception("Manifest length read was '$length', expected '{$header["len"]}'"); - } - return $header + compact("alias", "meta", "entries", "offset"); - } - - private function readEntry(array &$entries) { - if (!count($entries)) { - $offset = 0; - } else { - $last = end($entries); - $offset = $last["offset"] + $last["csize"]; - } - $file = $this->readStringBinary($this->fd); - if (!strlen($file)) { - throw new Exception("Empty file name encountered at offset '$offset'"); - } - $header = $this->readFormat("Vosize/Vstamp/Vcsize/Vcrc32/Vflags", $this->fd, 20); - $meta = $this->readSerializedBinary($this->fd); - $entries[$file] = $header + compact("meta", "offset"); - } - - private function readSignature() { - fseek($this->fd, -8, SEEK_END); - $sig = $this->readFormat("Vflags/Z4magic", $this->fd, 8); - $end = ftell($this->fd); - - if ($sig["magic"] !== "GBMB") { - throw new Exception("Invalid signature magic value '{$sig["magic"]}"); - } - - switch ($sig["flags"]) { - case self::SIG_OPENSSL: - fseek($this->fd, -12, SEEK_END); - if (($hash = $this->readSingleFormat("V", $this->fd, 4))) { - $offset = 4 + $hash; - fseek($this->fd, -$offset, SEEK_CUR); - $hash = $this->readVerified($this->fd, $hash); - fseek($this->fd, 0, SEEK_SET); - $valid = openssl_verify($this->readVerified($this->fd, $end - $offset - 8), - $hash, @file_get_contents($this->file.".pubkey")) === 1; - } - break; - - case self::SIG_MD5: - case self::SIG_SHA1: - case self::SIG_SHA256: - case self::SIG_SHA512: - $offset = 8 + self::$siglen[$sig["flags"]]; - fseek($this->fd, -$offset, SEEK_END); - $hash = $this->readVerified($this->fd, self::$siglen[$sig["flags"]]); - $algo = hash_init(self::$sigalg[$sig["flags"]]); - fseek($this->fd, 0, SEEK_SET); - hash_update_stream($algo, $this->fd, $end - $offset); - $valid = hash_final($algo, true) === $hash; - break; - - default: - throw new Exception("Invalid signature type '{$sig["flags"]}"); - } - - return $sig + compact("hash", "valid"); - } -} - - -namespace pharext; - -if (extension_loaded("Phar")) { - \Phar::interceptFileFuncs(); - \Phar::mapPhar(); - $phardir = "phar://".__FILE__; -} else { - $archive = new Archive(__FILE__); - $phardir = $archive->extract(); -} - -set_include_path("$phardir:". get_include_path()); - -$installer = new Installer(); -$installer->run($argc, $argv); - -__HALT_COMPILER(); ?> -¢7(a:7:{s:7:"version";s:5:"4.1.1";s:6:"header";s:49:"pharext v4.1.1 (c) Michael Wallner ";s:4:"date";s:10:"2015-09-05";s:4:"name";s:5:"raphf";s:7:"release";s:5:"1.1.0";s:7:"license";s:1345:"Copyright (c) 2013, Michael Wallner . -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -";s:4:"type";s:9:"extension";}pharext/Archive.phpËéêU4-ÔI¶pharext/Cli/Args/Help.phpÉ ËéêUÉ gX'¶pharext/Cli/Args.phpËéêU?nö¶pharext/Cli/Command.phpk ËéêUk d„aê¶pharext/Command.phpËéêUÔm`Ͷpharext/Exception.phpcËéêUcU†Ï{¶pharext/ExecCmd.phpËéêU¹l”ʶpharext/Installer.php&ËéêU&ød&À¶pharext/License.php“ËéêU“îòE¶pharext/Metadata.php•ËéêU•¿Úž¶pharext/Openssl/PrivateKey.phpÁËéêUÁ&æP¶pharext/Packager.phpÌ!ËéêUÌ!0<¶pharext/SourceDir/Basic.phpzËéêUz÷+Ôâ¶pharext/SourceDir/Git.phpZËéêUZÉÎ\¶pharext/SourceDir/Pecl.phpøËéêUøãùжpharext/SourceDir.php½ËéêU½3·#¶pharext/Task/Activate.phpÜ ËéêUÜ I“¶pharext/Task/Askpass.phpUËéêUU‡*¶ pharext/Task/BundleGenerator.php}ËéêU} ï`Y¶pharext/Task/Cleanup.phpËéêUÉI€B¶pharext/Task/Configure.phpTËéêUT}Ëì¶pharext/Task/Extract.phppËéêUp[¨Û̶pharext/Task/GitClone.phpmËéêUmóyµ@¶pharext/Task/Make.phpªËéêUªœç6 ¶pharext/Task/PaxFixup.php¬ËéêU¬y⯶pharext/Task/PeclFixup.phpœËéêUœeùtš¶pharext/Task/PharBuild.phpâËéêUâζ0ɶpharext/Task/PharCompress.phpcËéêUc½³Ï¶pharext/Task/PharRename.phpäËéêUäŠ[Þ˶pharext/Task/PharSign.php¨ËéêU¨Ûº¦i¶pharext/Task/PharStub.phpæËéêUæY|­›¶pharext/Task/Phpize.phpËéêUù 2Ѷpharext/Task/StreamFetch.phpËéêUˆîs\¶pharext/Task.phpwËéêUw ÄIǶpharext/Tempdir.phpµËéêUµë–,¶pharext/Tempfile.phpËéêU®ô¶pharext/Tempname.phptËéêUtžn<¶pharext/Updater.phpËéêUžÏv¶pharext_installer.phpÝËéêUÝŒÞq¶pharext_packager.phpbËéêUbîVÓ϶pharext_updater.phphËéêUh Êúj¶pharext_package.php2ËéêU2vSTÒ¶ package.xmlÄËéêUÄ?z,e¶CREDITSËéêUCµ]²¶LICENSEAËéêUA¾¬Jþ¶DoxyfileW,ËéêUW,Zΰ¶ config.m4$ËéêU$Åê@›¶ -config.w32ÐËéêUÐýÍŽ¶ php_raphf.hËéêUZ1€ž¶php_raphf_api.hz5ËéêUz5{¯>¶ php_raphf.cHËéêUH™Çꀶtests/http001.phptËéêU *®¶tests/http002.phptLËéêUL€ÔïS¶tests/http003.phpt^ËéêU^ˆp¶tests/http004.phpt[ËéêU[Y諶 16, - self::SIG_SHA1 => 20, - self::SIG_SHA256 => 32, - self::SIG_SHA512 => 64, - self::SIG_OPENSSL=> 0 - ]; - - private static $sigalg = [ - self::SIG_MD5 => "md5", - self::SIG_SHA1 => "sha1", - self::SIG_SHA256 => "sha256", - self::SIG_SHA512 => "sha512", - self::SIG_OPENSSL=> "openssl" - ]; - - private static $sigtyp = [ - self::SIG_MD5 => "MD5", - self::SIG_SHA1 => "SHA-1", - self::SIG_SHA256 => "SHA-256", - self::SIG_SHA512 => "SHA-512", - self::SIG_OPENSSL=> "OpenSSL", - ]; - - const PERM_FILE_MASK = 0x01ff; - const COMP_FILE_MASK = 0xf000; - const COMP_GZ_FILE = 0x1000; - const COMP_BZ2_FILE = 0x2000; - - const COMP_PHAR_MASK= 0xf000; - const COMP_PHAR_GZ = 0x1000; - const COMP_PHAR_BZ2 = 0x2000; - - private $file; - private $fd; - private $stub; - private $manifest; - private $signature; - private $extracted; - - function __construct($file = null) { - if (strlen($file)) { - $this->open($file); - } - } - - function open($file) { - if (!$this->fd = @fopen($file, "r")) { - throw new Exception; - } - $this->file = $file; - $this->stub = $this->readStub(); - $this->manifest = $this->readManifest(); - $this->signature = $this->readSignature(); - } - - function getIterator() { - return new RecursiveDirectoryIterator($this->extract()); - } - - function extract() { - return $this->extracted ?: $this->extractTo(new Tempdir("archive")); - } - - function extractTo($dir) { - if ((string) $this->extracted == (string) $dir) { - return $this->extracted; - } - foreach ($this->manifest["entries"] as $file => $entry) { - fseek($this->fd, $this->manifest["offset"]+$entry["offset"]); - $path = "$dir/$file"; - $copy = stream_copy_to_stream($this->fd, $this->outFd($path, $entry["flags"]), $entry["csize"]); - if ($entry["osize"] != $copy) { - throw new Exception("Copied '$copy' of '$file', expected '{$entry["osize"]}' from '{$entry["csize"]}"); - } - - $crc = hexdec(hash_file("crc32b", $path)); - if ($crc !== $entry["crc32"]) { - throw new Exception("CRC mismatch of '$file': '$crc' != '{$entry["crc32"]}"); - } - - chmod($path, $entry["flags"] & self::PERM_FILE_MASK); - touch($path, $entry["stamp"]); - } - return $this->extracted = $dir; - } - - function offsetExists($o) { - return isset($this->entries[$o]); - } - - function offsetGet($o) { - $this->extract(); - return new SplFileInfo($this->extracted."/$o"); - } - - function offsetSet($o, $v) { - throw new Exception("Archive is read-only"); - } - - function offsetUnset($o) { - throw new Exception("Archive is read-only"); - } - - function getSignature() { - /* compatible with Phar::getSignature() */ - return [ - "hash_type" => self::$sigtyp[$this->signature["flags"]], - "hash" => strtoupper(bin2hex($this->signature["hash"])), - ]; - } - - function getPath() { - /* compatible with Phar::getPath() */ - return new SplFileInfo($this->file); - } - - function getMetadata($key = null) { - if (isset($key)) { - return $this->manifest["meta"][$key]; - } - return $this->manifest["meta"]; - } - - private function outFd($path, $flags) { - $dirn = dirname($path); - if (!is_dir($dirn) && !@mkdir($dirn, 0777, true)) { - throw new Exception; - } - if (!$fd = @fopen($path, "w")) { - throw new Exception; - } - switch ($flags & self::COMP_FILE_MASK) { - case self::COMP_GZ_FILE: - if (!@stream_filter_append($fd, "zlib.inflate")) { - throw new Exception; - } - break; - case self::COMP_BZ2_FILE: - if (!@stream_filter_append($fd, "bz2.decompress")) { - throw new Exception; - } - break; - } - - } - private function readVerified($fd, $len) { - if ($len != strlen($data = fread($fd, $len))) { - throw new Exception("Unexpected EOF"); - } - return $data; - } - - private function readFormat($format, $fd, $len) { - if (false === ($data = @unpack($format, $this->readVerified($fd, $len)))) { - throw new Exception; - } - return $data; - } - - private function readSingleFormat($format, $fd, $len) { - return current($this->readFormat($format, $fd, $len)); - } - - private function readStringBinary($fd) { - if (($length = $this->readSingleFormat("V", $fd, 4))) { - return $this->readVerified($this->fd, $length); - } - return null; - } - - private function readSerializedBinary($fd) { - if (($length = $this->readSingleFormat("V", $fd, 4))) { - if (false === ($data = unserialize($this->readVerified($fd, $length)))) { - throw new Exception; - } - return $data; - } - return null; - } - - private function readStub() { - $stub = ""; - while (!feof($this->fd)) { - $line = fgets($this->fd); - $stub .= $line; - if (false !== stripos($line, self::HALT_COMPILER)) { - /* check for '?>' on a separate line */ - if ('?>' === $this->readVerified($this->fd, 2)) { - $stub .= '?>' . fgets($this->fd); - } else { - fseek($this->fd, -2, SEEK_CUR); - } - break; - } - } - return $stub; - } - - private function readManifest() { - $current = ftell($this->fd); - $header = $this->readFormat("Vlen/Vnum/napi/Vflags", $this->fd, 14); - $alias = $this->readStringBinary($this->fd); - $meta = $this->readSerializedBinary($this->fd); - $entries = []; - for ($i = 0; $i < $header["num"]; ++$i) { - $this->readEntry($entries); - } - $offset = ftell($this->fd); - if (($length = $offset - $current - 4) != $header["len"]) { - throw new Exception("Manifest length read was '$length', expected '{$header["len"]}'"); - } - return $header + compact("alias", "meta", "entries", "offset"); - } - - private function readEntry(array &$entries) { - if (!count($entries)) { - $offset = 0; - } else { - $last = end($entries); - $offset = $last["offset"] + $last["csize"]; - } - $file = $this->readStringBinary($this->fd); - if (!strlen($file)) { - throw new Exception("Empty file name encountered at offset '$offset'"); - } - $header = $this->readFormat("Vosize/Vstamp/Vcsize/Vcrc32/Vflags", $this->fd, 20); - $meta = $this->readSerializedBinary($this->fd); - $entries[$file] = $header + compact("meta", "offset"); - } - - private function readSignature() { - fseek($this->fd, -8, SEEK_END); - $sig = $this->readFormat("Vflags/Z4magic", $this->fd, 8); - $end = ftell($this->fd); - - if ($sig["magic"] !== "GBMB") { - throw new Exception("Invalid signature magic value '{$sig["magic"]}"); - } - - switch ($sig["flags"]) { - case self::SIG_OPENSSL: - fseek($this->fd, -12, SEEK_END); - if (($hash = $this->readSingleFormat("V", $this->fd, 4))) { - $offset = 4 + $hash; - fseek($this->fd, -$offset, SEEK_CUR); - $hash = $this->readVerified($this->fd, $hash); - fseek($this->fd, 0, SEEK_SET); - $valid = openssl_verify($this->readVerified($this->fd, $end - $offset - 8), - $hash, @file_get_contents($this->file.".pubkey")) === 1; - } - break; - - case self::SIG_MD5: - case self::SIG_SHA1: - case self::SIG_SHA256: - case self::SIG_SHA512: - $offset = 8 + self::$siglen[$sig["flags"]]; - fseek($this->fd, -$offset, SEEK_END); - $hash = $this->readVerified($this->fd, self::$siglen[$sig["flags"]]); - $algo = hash_init(self::$sigalg[$sig["flags"]]); - fseek($this->fd, 0, SEEK_SET); - hash_update_stream($algo, $this->fd, $end - $offset); - $valid = hash_final($algo, true) === $hash; - break; - - default: - throw new Exception("Invalid signature type '{$sig["flags"]}"); - } - - return $sig + compact("hash", "valid"); - } -} -prog = $prog; - $this->args = $args; - } - - function __toString() { - $usage = "Usage:\n\n \$ "; - $usage .= $this->prog; - - list($flags, $required, $optional, $positional) = $this->listSpec(); - if ($flags) { - $usage .= $this->dumpFlags($flags); - } - if ($required) { - $usage .= $this->dumpRequired($required); - } - if ($optional) { - $usage .= $this->dumpOptional($optional); - } - if ($positional) { - $usage .= $this->dumpPositional($positional); - } - - $help = $this->dumpHelp($positional); - - return $usage . "\n\n" . $help . "\n"; - } - - function listSpec() { - $flags = []; - $required = []; - $optional = []; - $positional = []; - foreach ($this->args->getSpec() as $spec) { - if (is_numeric($spec[0])) { - $positional[] = $spec; - } elseif ($spec[3] & Args::REQUIRED) { - $required[] = $spec; - } elseif ($spec[3] & (Args::OPTARG|Args::REQARG)) { - $optional[] = $spec; - } else { - $flags[] = $spec; - } - } - - return [$flags, $required, $optional, $positional] - + compact("flags", "required", "optional", "positional"); - } - - function dumpFlags(array $flags) { - return sprintf(" [-%s]", implode("", array_column($flags, 0))); - } - - function dumpRequired(array $required) { - $dump = ""; - foreach ($required as $req) { - $dump .= sprintf(" -%s <%s>", $req[0], $req[1]); - } - return $dump; - } - - function dumpOptional(array $optional) { - $req = array_filter($optional, function($a) { - return $a[3] & Args::REQARG; - }); - $opt = array_filter($optional, function($a) { - return $a[3] & Args::OPTARG; - }); - - $dump = ""; - if ($req) { - $dump .= sprintf(" [-%s ]", implode("|-", array_column($req, 0))); - } - if ($opt) { - $dump .= sprintf(" [-%s []]", implode("|-", array_column($opt, 0))); - } - return $dump; - } - - function dumpPositional(array $positional) { - $dump = " [--]"; - foreach ($positional as $pos) { - if ($pos[3] & Args::REQUIRED) { - $dump .= sprintf(" <%s>", $pos[1]); - } else { - $dump .= sprintf(" [<%s>]", $pos[1]); - } - if ($pos[3] & Args::MULTI) { - $dump .= sprintf(" [<%s>]...", $pos[1]); - } - } - return $dump; - } - - function calcMaxLen() { - $spc = $this->args->getSpec(); - $max = max(array_map("strlen", array_column($spc, 1))); - $max += $max % 8 + 2; - return $max; - } - - function dumpHelp() { - $max = $this->calcMaxLen(); - $dump = ""; - foreach ($this->args->getSpec() as $spec) { - $dump .= " "; - if (is_numeric($spec[0])) { - $dump .= sprintf("-- %s ", $spec[1]); - } elseif (isset($spec[0])) { - $dump .= sprintf("-%s|", $spec[0]); - } - if (!is_numeric($spec[0])) { - $dump .= sprintf("--%s ", $spec[1]); - } - if ($spec[3] & Args::REQARG) { - $dump .= " "; - } elseif ($spec[3] & Args::OPTARG) { - $dump .= "[]"; - } else { - $dump .= " "; - } - - $dump .= str_repeat(" ", $max-strlen($spec[1])+3*!isset($spec[0])); - $dump .= $spec[2]; - - if ($spec[3] & Args::REQUIRED) { - $dump .= " (REQUIRED)"; - } - if ($spec[3] & Args::MULTI) { - $dump .= " (MULTIPLE)"; - } - if (isset($spec[4])) { - $dump .= sprintf(" [%s]", $spec[4]); - } - $dump .= "\n"; - } - return $dump; - } -} -compile($spec); - } - - } - - /** - * Compile the original spec - * @param array|Traversable $spec - * @return pharext\Cli\Args self - */ - public function compile($spec) { - foreach ($spec as $arg) { - if (isset($arg[0]) && is_numeric($arg[0])) { - $arg[3] &= ~0xf00; - $this->spec["--".$arg[0]] = $arg; - } elseif (isset($arg[0])) { - $this->spec["-".$arg[0]] = $arg; - $this->spec["--".$arg[1]] = $arg; - } else { - $this->spec["--".$arg[1]] = $arg; - } - $this->orig[] = $arg; - } - return $this; - } - - /** - * Get original spec - * @return array - */ - public function getSpec() { - return $this->orig; - } - - /** - * Get compiled spec - * @return array - */ - public function getCompiledSpec() { - return $this->spec; - } - - /** - * Parse command line arguments according to the compiled spec. - * - * The Generator yields any parsing errors. - * Parsing will stop when all arguments are processed or the first option - * flagged Cli\Args::HALT was encountered. - * - * @param int $argc - * @param array $argv - * @return Generator - */ - public function parse($argc, array $argv) { - for ($f = false, $p = 0, $i = 0; $i < $argc; ++$i) { - $o = $argv[$i]; - - if ($o{0} === "-" && strlen($o) > 2 && $o{1} !== "-") { - // multiple short opts, e.g. -vps - $argc += strlen($o) - 2; - array_splice($argv, $i, 1, array_map(function($s) { - return "-$s"; - }, str_split(substr($o, 1)))); - $o = $argv[$i]; - } elseif ($o{0} === "-" && strlen($o) > 2 && $o{1} === "-" && 0 < ($eq = strpos($o, "="))) { - // long opt with argument, e.g. --foo=bar - $argc++; - array_splice($argv, $i, 1, [ - substr($o, 0, $eq++), - substr($o, $eq) - ]); - $o = $argv[$i]; - } elseif ($o === "--") { - // only positional args following - $f = true; - continue; - } - - if ($f || !isset($this->spec[$o])) { - if ($o{0} !== "-" && isset($this->spec["--$p"])) { - $this[$p] = $o; - if (!$this->optIsMulti($p)) { - ++$p; - } - } else { - yield sprintf("Unknown option %s", $o); - } - } elseif (!$this->optAcceptsArg($o)) { - $this[$o] = true; - } elseif ($i+1 < $argc && !isset($this->spec[$argv[$i+1]])) { - $this[$o] = $argv[++$i]; - } elseif ($this->optRequiresArg($o)) { - yield sprintf("Option --%s requires an argument", $this->optLongName($o)); - } else { - // OPTARG - $this[$o] = $this->optDefaultArg($o); - } - - if ($this->optHalts($o)) { - return; - } - } - } - - /** - * Validate that all required options were given. - * - * The Generator yields any validation errors. - * - * @return Generator - */ - public function validate() { - $required = array_filter($this->orig, function($spec) { - return $spec[3] & self::REQUIRED; - }); - foreach ($required as $req) { - if ($req[3] & self::MULTI) { - if (is_array($this[$req[0]])) { - continue; - } - } elseif (strlen($this[$req[0]])) { - continue; - } - if (is_numeric($req[0])) { - yield sprintf("Argument <%s> is required", $req[1]); - } else { - yield sprintf("Option --%s is required", $req[1]); - } - } - } - - - public function toArray() { - $args = []; - foreach ($this->spec as $spec) { - $opt = $this->opt($spec[1]); - $args[$opt] = $this[$opt]; - } - return $args; - } - - /** - * Retreive the default argument of an option - * @param string $o - * @return mixed - */ - private function optDefaultArg($o) { - $o = $this->opt($o); - if (isset($this->spec[$o][4])) { - return $this->spec[$o][4]; - } - return null; - } - - /** - * Retrieve the help message of an option - * @param string $o - * @return string - */ - private function optHelp($o) { - $o = $this->opt($o); - if (isset($this->spec[$o][2])) { - return $this->spec[$o][2]; - } - return ""; - } - - /** - * Retrieve option's flags - * @param string $o - * @return int - */ - private function optFlags($o) { - $o = $this->opt($o); - if (isset($this->spec[$o])) { - return $this->spec[$o][3]; - } - return null; - } - - /** - * Check whether an option is flagged for halting argument processing - * @param string $o - * @return boolean - */ - private function optHalts($o) { - return $this->optFlags($o) & self::HALT; - } - - /** - * Check whether an option needs an argument - * @param string $o - * @return boolean - */ - private function optRequiresArg($o) { - return $this->optFlags($o) & self::REQARG; - } - - /** - * Check wether an option accepts any argument - * @param string $o - * @return boolean - */ - private function optAcceptsArg($o) { - return $this->optFlags($o) & 0xf00; - } - - /** - * Check whether an option can be used more than once - * @param string $o - * @return boolean - */ - private function optIsMulti($o) { - return $this->optFlags($o) & self::MULTI; - } - - /** - * Retreive the long name of an option - * @param string $o - * @return string - */ - private function optLongName($o) { - $o = $this->opt($o); - return is_numeric($this->spec[$o][0]) ? $this->spec[$o][0] : $this->spec[$o][1]; - } - - /** - * Retreive the short name of an option - * @param string $o - * @return string - */ - private function optShortName($o) { - $o = $this->opt($o); - return is_numeric($this->spec[$o][0]) ? null : $this->spec[$o][0]; - } - - /** - * Retreive the canonical name (--long-name) of an option - * @param string $o - * @return string - */ - private function opt($o) { - if (is_numeric($o)) { - return "--$o"; - } - if ($o{0} !== '-') { - if (strlen($o) > 1) { - $o = "-$o"; - } - $o = "-$o"; - } - return $o; - } - - /**@+ - * Implements ArrayAccess and virtual properties - */ - function offsetExists($o) { - $o = $this->opt($o); - return isset($this->args[$o]); - } - function __isset($o) { - return $this->offsetExists($o); - } - function offsetGet($o) { - $o = $this->opt($o); - if (isset($this->args[$o])) { - return $this->args[$o]; - } - return $this->optDefaultArg($o); - } - function __get($o) { - return $this->offsetGet($o); - } - function offsetSet($o, $v) { - $osn = $this->optShortName($o); - $oln = $this->optLongName($o); - if ($this->optIsMulti($o)) { - if (isset($osn)) { - $this->args["-$osn"][] = $v; - } - $this->args["--$oln"][] = $v; - } else { - if (isset($osn)) { - $this->args["-$osn"] = $v; - } - $this->args["--$oln"] = $v; - } - } - function __set($o, $v) { - $this->offsetSet($o, $v); - } - function offsetUnset($o) { - unset($this->args["-".$this->optShortName($o)]); - unset($this->args["--".$this->optLongName($o)]); - } - function __unset($o) { - $this->offsetUnset($o); - } - /**@-*/ -} -args; - } - - /** - * Retrieve metadata of the currently running phar - * @param string $key - * @return mixed - */ - public function metadata($key = null) { - if (extension_loaded("Phar")) { - $running = new Phar(Phar::running(false)); - } else { - $running = new Archive(PHAREXT_PHAR); - } - - if ($key === "signature") { - $sig = $running->getSignature(); - return sprintf("%s signature of %s\n%s", - $sig["hash_type"], - $this->metadata("name"), - chunk_split($sig["hash"], 64, "\n")); - } - - $metadata = $running->getMetadata(); - if (isset($key)) { - return $metadata[$key]; - } - return $metadata; - } - - /** - * Output pharext vX.Y.Z header - */ - public function header() { - if (!headers_sent()) { - /* only display header, if we didn't generate any output yet */ - printf("%s\n\n", $this->metadata("header")); - } - } - - /** - * @inheritdoc - * @see \pharext\Command::debug() - */ - public function debug($fmt) { - if ($this->args->verbose) { - vprintf($fmt, array_slice(func_get_args(), 1)); - } - } - - /** - * @inheritdoc - * @see \pharext\Command::info() - */ - public function info($fmt) { - if (!$this->args->quiet) { - vprintf($fmt, array_slice(func_get_args(), 1)); - } - } - - /** - * @inheritdoc - * @see \pharext\Command::warn() - */ - public function warn($fmt) { - if (!$this->args->quiet) { - if (!isset($fmt)) { - $fmt = "%s\n"; - $arg = error_get_last()["message"]; - } else { - $arg = array_slice(func_get_args(), 1); - } - vfprintf(STDERR, "Warning: $fmt", $arg); - } - } - - /** - * @inheritdoc - * @see \pharext\Command::error() - */ - public function error($fmt) { - if (!isset($fmt)) { - $fmt = "%s\n"; - $arg = error_get_last()["message"]; - } else { - $arg = array_slice(func_get_args(), 1); - } - vfprintf(STDERR, "ERROR: $fmt", $arg); - } - - /** - * Output command line help message - * @param string $prog - */ - public function help($prog) { - print new Args\Help($prog, $this->args); - } - - /** - * Verbosity - * @return boolean - */ - public function verbosity() { - if ($this->args->verbose) { - return true; - } elseif ($this->args->quiet) { - return false; - } else { - return null; - } - } -} -command = $command; - $this->verbose = $verbose; - } - - /** - * (Re-)set sudo command - * @param string $sudo - */ - public function setSu($sudo = false) { - $this->sudo = $sudo; - } - - /** - * Execute a program with escalated privileges handling interactive password prompt - * @param string $command - * @param bool $verbose - * @return int exit status - */ - private function suExec($command, $verbose = null) { - if (!($proc = proc_open($command, [STDIN,["pipe","w"],["pipe","w"]], $pipes))) { - $this->status = -1; - throw new Exception("Failed to run {$command}"); - } - - $stdout = $pipes[1]; - $passwd = 0; - $checks = 10; - - while (!feof($stdout)) { - $R = [$stdout]; $W = []; $E = []; - if (!stream_select($R, $W, $E, null)) { - continue; - } - $data = fread($stdout, 0x1000); - /* only check a few times */ - if ($passwd < $checks) { - $passwd++; - if (stristr($data, "password")) { - $passwd = $checks + 1; - printf("\n%s", $data); - continue; - } - } elseif ($passwd > $checks) { - /* new line after pw entry */ - printf("\n"); - $passwd = $checks; - } - - if ($verbose === null) { - print $this->progress($data, 0); - } else { - if ($verbose) { - printf("%s", $data); - } - $this->output .= $data; - } - } - if ($verbose === null) { - $this->progress("", PHP_OUTPUT_HANDLER_FINAL); - } - return $this->status = proc_close($proc); - } - - /** - * Output handler that displays some progress while soaking output - * @param string $string - * @param int $flags - * @return string - */ - private function progress($string, $flags) { - static $counter = 0; - static $symbols = ["\\","|","/","-"]; - - $this->output .= $string; - - if (false !== strpos($string, "\n")) { - ++$counter; - } - - return $flags & PHP_OUTPUT_HANDLER_FINAL - ? " \r" - : sprintf(" %s\r", $symbols[$counter % 4]); - } - - /** - * Run the command - * @param array $args - * @return \pharext\ExecCmd self - * @throws \pharext\Exception - */ - public function run(array $args = null) { - $exec = escapeshellcmd($this->command); - if ($args) { - $exec .= " ". implode(" ", array_map("escapeshellarg", (array) $args)); - } - - if ($this->sudo) { - $this->suExec(sprintf($this->sudo." 2>&1", $exec), $this->verbose); - } elseif ($this->verbose) { - ob_start(function($s) { - $this->output .= $s; - return $s; - }, 1); - passthru($exec, $this->status); - ob_end_flush(); - } elseif ($this->verbose !== false /* !quiet */) { - ob_start([$this, "progress"], 1); - passthru($exec . " 2>&1", $this->status); - ob_end_flush(); - } else { - exec($exec ." 2>&1", $output, $this->status); - $this->output = implode("\n", $output); - } - - if ($this->status) { - throw new Exception("Command {$exec} failed ({$this->status})"); - } - - return $this; - } - - /** - * Retrieve exit code of cmd run - * @return int - */ - public function getStatus() { - return $this->status; - } - - /** - * Retrieve output of cmd run - * @return string - */ - public function getOutput() { - return $this->output; - } -} -args = new Cli\Args([ - ["h", "help", "Display help", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - ["v", "verbose", "More output", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["q", "quiet", "Less output", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["p", "prefix", "PHP installation prefix if phpize is not in \$PATH, e.g. /opt/php7", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG], - ["n", "common-name", "PHP common program name, e.g. php5 or zts-php", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG, - "php"], - ["c", "configure", "Additional extension configure flags, e.g. -c --with-flag", - Cli\Args::OPTIONAL|Cli\Args::MULTI|Cli\Args::REQARG], - ["s", "sudo", "Installation might need increased privileges", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::OPTARG, - "sudo -S %s"], - ["i", "ini", "Activate in this php.ini instead of loaded default php.ini", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG], - [null, "signature", "Show package signature", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "license", "Show package license", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "name", "Show package name", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "date", "Show package release date", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "release", "Show package release version", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "version", "Show pharext version", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - ]); - } - - /** - * Perform cleaniup - */ - function __destruct() { - foreach ($this->cleanup as $cleanup) { - $cleanup->run(); - } - } - - private function extract($phar) { - $temp = (new Task\Extract($phar))->run($this->verbosity()); - $this->cleanup[] = new Task\Cleanup($temp); - return $temp; - } - - private function hooks(SplObjectStorage $phars) { - $hook = []; - foreach ($phars as $phar) { - if (isset($phar["pharext_package.php"])) { - $sdir = include $phar["pharext_package.php"]; - if ($sdir instanceof SourceDir) { - $this->args->compile($sdir->getArgs()); - $hook[] = $sdir; - } - } - } - return $hook; - } - - private function load() { - $list = new SplObjectStorage(); - $phar = extension_loaded("Phar") - ? new Phar(Phar::running(false)) - : new Archive(PHAREXT_PHAR); - $temp = $this->extract($phar); - - foreach ($phar as $entry) { - $dep_file = $entry->getBaseName(); - if (fnmatch("*.ext.phar*", $dep_file)) { - $dep_phar = extension_loaded("Phar") - ? new Phar("$temp/$dep_file") - : new Archive("$temp/$dep_file"); - $list[$dep_phar] = $this->extract($dep_phar); - } - } - - /* the actual ext.phar at last */ - $list[$phar] = $temp; - return $list; - } - - /** - * @inheritdoc - * @see \pharext\Command::run() - */ - public function run($argc, array $argv) { - try { - /* load the phar(s) */ - $list = $this->load(); - /* installer hooks */ - $hook = $this->hooks($list); - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::EEXTRACT); - } - - /* standard arg stuff */ - $errs = []; - $prog = array_shift($argv); - foreach ($this->args->parse(--$argc, $argv) as $error) { - $errs[] = $error; - } - - if ($this->args["help"]) { - $this->header(); - $this->help($prog); - exit; - } - try { - foreach (["signature", "name", "date", "license", "release", "version"] as $opt) { - if ($this->args[$opt]) { - printf("%s\n", $this->metadata($opt)); - exit; - } - } - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::EARGS); - } - - foreach ($this->args->validate() as $error) { - $errs[] = $error; - } - - if ($errs) { - if (!$this->args["quiet"]) { - $this->header(); - } - foreach ($errs as $err) { - $this->error("%s\n", $err); - } - if (!$this->args["quiet"]) { - $this->help($prog); - } - exit(self::EARGS); - } - - try { - /* post process hooks */ - foreach ($hook as $sdir) { - $sdir->setArgs($this->args); - } - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::EARGS); - } - - /* install packages */ - try { - foreach ($list as $phar) { - $this->info("Installing %s ...\n", basename($phar->getPath())); - $this->install($list[$phar]); - $this->activate($list[$phar]); - $this->info("Successfully installed %s!\n", basename($phar->getPath())); - } - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::EINSTALL); - } - } - - /** - * Phpize + trinity - */ - private function install($temp) { - // phpize - $phpize = new Task\Phpize($temp, $this->args->prefix, $this->args->{"common-name"}); - $phpize->run($this->verbosity()); - - // configure - $configure = new Task\Configure($temp, $this->args->configure, $this->args->prefix, $this->args->{"common-name"}); - $configure->run($this->verbosity()); - - // make - $make = new Task\Make($temp); - $make->run($this->verbosity()); - - // install - $sudo = isset($this->args->sudo) ? $this->args->sudo : null; - $install = new Task\Make($temp, ["install"], $sudo); - $install->run($this->verbosity()); - } - - private function activate($temp) { - if ($this->args->ini) { - $files = [$this->args->ini]; - } else { - $files = array_filter(array_map("trim", explode(",", php_ini_scanned_files()))); - $files[] = php_ini_loaded_file(); - } - - $sudo = isset($this->args->sudo) ? $this->args->sudo : null; - $type = $this->metadata("type") ?: "extension"; - - $activate = new Task\Activate($temp, $files, $type, $this->args->prefix, $this->args{"common-name"}, $sudo); - if (!$activate->run($this->verbosity())) { - $this->info("Extension already activated ...\n"); - } - } -} -mergeLicensePattern($name, strtolower($name)); - } - $exts = []; - foreach (["t{,e}xt", "rst", "asc{,i,ii}", "m{,ark}d{,own}", "htm{,l}"] as $ext) { - $exts[] = $this->mergeLicensePattern(strtoupper($ext), $ext); - } - - $pattern = "{". implode(",", $names) ."}{,.{". implode(",", $exts) ."}}"; - - if (($glob = glob("$dir/$pattern", GLOB_BRACE))) { - return current($glob); - } - } - - private function mergeLicensePattern($upper, $lower) { - $pattern = ""; - $length = strlen($upper); - for ($i = 0; $i < $length; ++$i) { - if ($lower{$i} === $upper{$i}) { - $pattern .= $upper{$i}; - } else { - $pattern .= "[" . $upper{$i} . $lower{$i} . "]"; - } - } - return $pattern; - } - - public function readLicense($file) { - $text = file_get_contents($file); - switch (strtolower(pathinfo($file, PATHINFO_EXTENSION))) { - case "htm": - case "html": - $text = strip_tags($text); - break; - } - return $text; - } -} -", self::version()); - } - - static function date() { - return gmdate("Y-m-d"); - } - - static function all() { - return [ - "version" => self::version(), - "header" => self::header(), - "date" => self::date(), - ]; - } -} -key); - $this->pub = openssl_pkey_get_details($key)["key"]; - } - - /** - * Sign the PHAR - * @param \Phar $package - */ - function sign(\Phar $package) { - $package->setSignatureAlgorithm(\Phar::OPENSSL, $this->key); - } - - /** - * Export the public key to a file - * @param string $file - * @throws \pharext\Exception - */ - function exportPublicKey($file) { - if (!file_put_contents("$file.tmp", $this->pub) || !rename("$file.tmp", $file)) { - throw new Exception; - } - } -} -args = new Cli\Args([ - ["h", "help", "Display this help", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - ["v", "verbose", "More output", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["q", "quiet", "Less output", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["n", "name", "Extension name", - Cli\Args::REQUIRED|Cli\Args::SINGLE|Cli\Args::REQARG], - ["r", "release", "Extension release version", - Cli\Args::REQUIRED|Cli\Args::SINGLE|Cli\Args::REQARG], - ["s", "source", "Extension source directory", - Cli\Args::REQUIRED|Cli\Args::SINGLE|Cli\Args::REQARG], - ["g", "git", "Use `git ls-tree` to determine file list", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["b", "branch", "Checkout this tag/branch", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG], - ["p", "pecl", "Use PECL package.xml to determine file list, name and release", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["d", "dest", "Destination directory", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG, - "."], - ["z", "gzip", "Create additional PHAR compressed with gzip", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["Z", "bzip", "Create additional PHAR compressed with bzip", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["S", "sign", "Sign the PHAR with a private key", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG], - ["E", "zend", "Mark as Zend Extension", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - [null, "signature", "Show pharext signature", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "license", "Show pharext license", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "version", "Show pharext version", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - ]); - } - - /** - * Perform cleaniup - */ - function __destruct() { - foreach ($this->cleanup as $cleanup) { - $cleanup->run(); - } - } - - /** - * @inheritdoc - * @see \pharext\Command::run() - */ - public function run($argc, array $argv) { - $errs = []; - $prog = array_shift($argv); - foreach ($this->args->parse(--$argc, $argv) as $error) { - $errs[] = $error; - } - - if ($this->args["help"]) { - $this->header(); - $this->help($prog); - exit; - } - try { - foreach (["signature", "license", "version"] as $opt) { - if ($this->args[$opt]) { - printf("%s\n", $this->metadata($opt)); - exit; - } - } - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::EARGS); - } - - try { - /* source needs to be evaluated before Cli\Args validation, - * so e.g. name and version can be overriden and Cli\Args - * does not complain about missing arguments - */ - $this->loadSource(); - } catch (\Exception $e) { - $errs[] = $e->getMessage(); - } - - foreach ($this->args->validate() as $error) { - $errs[] = $error; - } - - if ($errs) { - if (!$this->args["quiet"]) { - $this->header(); - } - foreach ($errs as $err) { - $this->error("%s\n", $err); - } - printf("\n"); - if (!$this->args["quiet"]) { - $this->help($prog); - } - exit(self::EARGS); - } - - $this->createPackage(); - } - - /** - * Download remote source - * @param string $source - * @return string local source - */ - private function download($source) { - if ($this->args->git) { - $task = new Task\GitClone($source, $this->args->branch); - } else { - /* print newline only once */ - $done = false; - $task = new Task\StreamFetch($source, function($bytes_pct) use(&$done) { - if (!$done) { - $this->info(" %3d%% [%s>%s] \r", - floor($bytes_pct*100), - str_repeat("=", round(50*$bytes_pct)), - str_repeat(" ", round(50*(1-$bytes_pct))) - ); - if ($bytes_pct == 1) { - $done = true; - $this->info("\n"); - } - } - }); - } - $local = $task->run($this->verbosity()); - - $this->cleanup[] = new Task\Cleanup($local); - return $local; - } - - /** - * Extract local archive - * @param stirng $source - * @return string extracted directory - */ - private function extract($source) { - try { - $task = new Task\Extract($source); - $dest = $task->run($this->verbosity()); - } catch (\Exception $e) { - if (false === strpos($e->getMessage(), "checksum mismatch")) { - throw $e; - } - $dest = (new Task\PaxFixup($source))->run($this->verbosity()); - } - - $this->cleanup[] = new Task\Cleanup($dest); - return $dest; - } - - /** - * Localize a possibly remote source - * @param string $source - * @return string local source directory - */ - private function localize($source) { - if (!stream_is_local($source) || ($this->args->git && isset($this->args->branch))) { - $source = $this->download($source); - $this->cleanup[] = new Task\Cleanup($source); - } - $source = realpath($source); - if (!is_dir($source)) { - $source = $this->extract($source); - $this->cleanup[] = new Task\Cleanup($source); - - if (!$this->args->git) { - $source = (new Task\PeclFixup($source))->run($this->verbosity()); - } - } - return $source; - } - - /** - * Load the source dir - * @throws \pharext\Exception - */ - private function loadSource(){ - if ($this->args["source"]) { - $source = $this->localize($this->args["source"]); - - if ($this->args["pecl"]) { - $this->source = new SourceDir\Pecl($source); - } elseif ($this->args["git"]) { - $this->source = new SourceDir\Git($source); - } elseif (is_file("$source/pharext_package.php")) { - $this->source = include "$source/pharext_package.php"; - } else { - $this->source = new SourceDir\Basic($source); - } - - if (!$this->source instanceof SourceDir) { - throw new Exception("Unknown source dir $source"); - } - - foreach ($this->source->getPackageInfo() as $key => $val) { - $this->args->$key = $val; - } - } - } - - /** - * Creates the extension phar - */ - private function createPackage() { - try { - $meta = array_merge(Metadata::all(), [ - "name" => $this->args->name, - "release" => $this->args->release, - "license" => $this->source->getLicense(), - "type" => $this->args->zend ? "zend_extension" : "extension", - ]); - $file = (new Task\PharBuild($this->source, __DIR__."/../pharext_installer.php", $meta))->run($this->verbosity()); - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::EBUILD); - } - - try { - if ($this->args->sign) { - $this->info("Using private key to sign phar ...\n"); - $pass = (new Task\Askpass)->run($this->verbosity()); - $sign = new Task\PharSign($file, $this->args->sign, $pass); - $pkey = $sign->run($this->verbosity()); - } - - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::ESIGN); - } - - if ($this->args->gzip) { - try { - $gzip = (new Task\PharCompress($file, Phar::GZ))->run(); - $move = new Task\PharRename($gzip, $this->args->dest, $this->args->name ."-". $this->args->release); - $name = $move->run($this->verbosity()); - - $this->info("Created gzipped phar %s\n", $name); - - if ($this->args->sign) { - $sign = new Task\PharSign($name, $this->args->sign, $pass); - $sign->run($this->verbosity())->exportPublicKey($name.".pubkey"); - } - - } catch (\Exception $e) { - $this->warn("%s\n", $e->getMessage()); - } - } - - if ($this->args->bzip) { - try { - $bzip = (new Task\PharCompress($file, Phar::BZ2))->run(); - $move = new Task\PharRename($bzip, $this->args->dest, $this->args->name ."-". $this->args->release); - $name = $move->run($this->verbosity()); - - $this->info("Created bzipped phar %s\n", $name); - - if ($this->args->sign) { - $sign = new Task\PharSign($name, $this->args->sign, $pass); - $sign->run($this->verbosity())->exportPublicKey($name.".pubkey"); - } - - } catch (\Exception $e) { - $this->warn("%s\n", $e->getMessage()); - } - } - - try { - $move = new Task\PharRename($file, $this->args->dest, $this->args->name ."-". $this->args->release); - $name = $move->run($this->verbosity()); - - $this->info("Created executable phar %s\n", $name); - - if (isset($pkey)) { - $pkey->exportPublicKey($name.".pubkey"); - } - - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::EBUILD); - } - } -} -path = $path; - } - - public function getBaseDir() { - return $this->path; - } - - public function getPackageInfo() { - return []; - } - - public function getLicense() { - if (($file = $this->findLicense($this->getBaseDir()))) { - return $this->readLicense($file); - } - return "UNKNOWN"; - } - - public function getArgs() { - return []; - } - - public function setArgs(Args $args) { - } - - public function filter($current, $key, $iterator) { - $sub = $current->getSubPath(); - if ($sub === ".git" || $sub === ".hg" || $sub === ".svn") { - return false; - } - return true; - } - - public function getIterator() { - $rdi = new RecursiveDirectoryIterator($this->path, - FilesystemIterator::CURRENT_AS_SELF | // needed for 5.5 - FilesystemIterator::KEY_AS_PATHNAME | - FilesystemIterator::SKIP_DOTS); - $rci = new RecursiveCallbackFilterIterator($rdi, [$this, "filter"]); - $rii = new RecursiveIteratorIterator($rci); - foreach ($rii as $path => $child) { - if (!$child->isDir()) { - yield realpath($path); - } - } - } -} -path = $path; - } - - /** - * @inheritdoc - * @see \pharext\SourceDir::getBaseDir() - */ - public function getBaseDir() { - return $this->path; - } - - /** - * @inheritdoc - * @return array - */ - public function getPackageInfo() { - return []; - } - - /** - * @inheritdoc - * @return string - */ - public function getLicense() { - if (($file = $this->findLicense($this->getBaseDir()))) { - return $this->readLicense($file); - } - return "UNKNOWN"; - } - - /** - * @inheritdoc - * @return array - */ - public function getArgs() { - return []; - } - - /** - * @inheritdoc - */ - public function setArgs(Args $args) { - } - - /** - * Generate a list of files by `git ls-files` - * @return Generator - */ - private function generateFiles() { - $pwd = getcwd(); - chdir($this->path); - if (($pipe = popen("git ls-tree -r --name-only HEAD", "r"))) { - $path = realpath($this->path); - while (!feof($pipe)) { - if (strlen($file = trim(fgets($pipe)))) { - /* there may be symlinks, so no realpath here */ - yield "$path/$file"; - } - } - pclose($pipe); - } - chdir($pwd); - } - - /** - * Implements IteratorAggregate - * @see IteratorAggregate::getIterator() - */ - public function getIterator() { - return $this->generateFiles(); - } -} -file = "$path/package2.xml"); - } elseif (is_file("$path/package.xml")) { - $sxe = simplexml_load_file($this->file = "$path/package.xml"); - } else { - throw new Exception("Missing package.xml in $path"); - } - - $sxe->registerXPathNamespace("pecl", $sxe->getDocNamespaces()[""]); - - $this->sxe = $sxe; - $this->path = realpath($path); - } - - /** - * @inheritdoc - * @see \pharext\SourceDir::getBaseDir() - */ - public function getBaseDir() { - return $this->path; - } - - /** - * Retrieve gathered package info - * @return Generator - */ - public function getPackageInfo() { - if (($name = $this->sxe->xpath("/pecl:package/pecl:name"))) { - yield "name" => (string) $name[0]; - } - if (($release = $this->sxe->xpath("/pecl:package/pecl:version/pecl:release"))) { - yield "release" => (string) $release[0]; - } - if ($this->sxe->xpath("/pecl:package/pecl:zendextsrcrelease")) { - yield "zend" => true; - } - } - - /** - * @inheritdoc - * @return string - */ - public function getLicense() { - if (($license = $this->sxe->xpath("/pecl:package/pecl:license"))) { - if (($file = $this->findLicense($this->getBaseDir(), $license[0]["filesource"]))) { - return $this->readLicense($file); - } - } - if (($file = $this->findLicense($this->getBaseDir()))) { - return $this->readLicense($file); - } - if ($license) { - return $license[0] ." ". $license[0]["uri"]; - } - return "UNKNOWN"; - } - - /** - * @inheritdoc - * @see \pharext\SourceDir::getArgs() - */ - public function getArgs() { - $configure = $this->sxe->xpath("/pecl:package/pecl:extsrcrelease/pecl:configureoption"); - foreach ($configure as $cfg) { - yield [null, $cfg["name"], ucfirst($cfg["prompt"]), Args::OPTARG, - strlen($cfg["default"]) ? $cfg["default"] : null]; - } - $configure = $this->sxe->xpath("/pecl:package/pecl:zendextsrcrelease/pecl:configureoption"); - foreach ($configure as $cfg) { - yield [null, $cfg["name"], ucfirst($cfg["prompt"]), Args::OPTARG, - strlen($cfg["default"]) ? $cfg["default"] : null]; - } - } - - /** - * @inheritdoc - * @see \pharext\SourceDir::setArgs() - */ - public function setArgs(Args $args) { - $configure = $this->sxe->xpath("/pecl:package/pecl:extsrcrelease/pecl:configureoption"); - foreach ($configure as $cfg) { - if (isset($args[$cfg["name"]])) { - $args->configure = "--{$cfg["name"]}={$args[$cfg["name"]]}"; - } - } - $configure = $this->sxe->xpath("/pecl:package/pecl:zendextsrcrelease/pecl:configureoption"); - foreach ($configure as $cfg) { - if (isset($args[$cfg["name"]])) { - $args->configure = "--{$cfg["name"]}={$args[$cfg["name"]]}"; - } - } - } - - /** - * Compute the path of a file by parent dir nodes - * @param \SimpleXMLElement $ele - * @return string - */ - private function dirOf($ele) { - $path = ""; - while (($ele = current($ele->xpath(".."))) && $ele->getName() == "dir") { - $path = trim($ele["name"], "/") ."/". $path ; - } - return trim($path, "/"); - } - - /** - * Generate a list of files from the package.xml - * @return Generator - */ - private function generateFiles() { - /* hook */ - $temp = tmpfile(); - fprintf($temp, " $temp; - - /* deps */ - $dependencies = $this->sxe->xpath("/pecl:package/pecl:dependencies/pecl:required/pecl:package"); - foreach ($dependencies as $key => $dep) { - if (($glob = glob("{$this->path}/{$dep->name}-*.ext.phar*"))) { - usort($glob, function($a, $b) { - return version_compare( - substr($a, strpos(".ext.phar", $a)), - substr($b, strpos(".ext.phar", $b)) - ); - }); - yield end($glob); - } - } - - /* files */ - yield realpath($this->file); - foreach ($this->sxe->xpath("//pecl:file") as $file) { - yield realpath($this->path ."/". $this->dirOf($file) ."/". $file["name"]); - } - } - - /** - * Implements IteratorAggregate - * @see IteratorAggregate::getIterator() - */ - public function getIterator() { - return $this->generateFiles(); - } -} -cwd = $cwd; - $this->type = $type; - $this->sudo = $sudo; - if (!$this->inis = $inis) { - throw new Exception("No PHP INIs given"); - } - $cmd = $common_name . "-config"; - if (isset($prefix)) { - $cmd = $prefix . "/bin/" . $cmd; - } - $this->php_config = $cmd; - } - - /** - * @param bool $verbose - * @return boolean false, if extension was already activated - */ - public function run($verbose = false) { - if ($verbose !== false) { - printf("Running INI activation ...\n"); - } - $extension = basename(current(glob("{$this->cwd}/modules/*.so"))); - - if ($this->type === "zend_extension") { - $pattern = preg_quote((new ExecCmd($this->php_config))->run(["--extension-dir"])->getOutput() . "/$extension", "/"); - } else { - $pattern = preg_quote($extension, "/"); - } - - foreach ($this->inis as $file) { - if ($verbose) { - printf("Checking %s ...\n", $file); - } - if (!file_exists($file)) { - throw new Exception(sprintf("INI file '%s' does not exist", $file)); - } - $temp = new Tempfile("phpini"); - foreach (file($file) as $line) { - if (preg_match("/^\s*{$this->type}\s*=\s*[\"']?{$pattern}[\"']?\s*(;.*)?\$/", $line)) { - return false; - } - fwrite($temp->getStream(), $line); - } - } - - /* not found; append to last processed file, which is the main by default */ - if ($verbose) { - printf("Activating in %s ...\n", $file); - } - fprintf($temp->getStream(), $this->type . "=%s\n", $extension); - $temp->closeStream(); - - $path = $temp->getPathname(); - $stat = stat($file); - - // owner transfer - $ugid = sprintf("%d:%d", $stat["uid"], $stat["gid"]); - $cmd = new ExecCmd("chown", $verbose); - if (isset($this->sudo)) { - $cmd->setSu($this->sudo); - } - $cmd->run([$ugid, $path]); - - // permission transfer - $perm = decoct($stat["mode"] & 0777); - $cmd = new ExecCmd("chmod", $verbose); - if (isset($this->sudo)) { - $cmd->setSu($this->sudo); - } - $cmd->run([$perm, $path]); - - // rename - $cmd = new ExecCmd("mv", $verbose); - if (isset($this->sudo)) { - $cmd->setSu($this->sudo); - } - $cmd->run([$path, $file]); - - if ($verbose) { - printf("Replaced %s ...\n", $file); - } - - return true; - } -} -prompt = $prompt; - } - - /** - * @param bool $verbose - * @return string - */ - public function run($verbose = false) { - system("stty -echo"); - printf("%s ", $this->prompt); - $pass = fgets(STDIN, 1024); - printf("\n"); - system("stty echo"); - if (substr($pass, -1) == "\n") { - $pass = substr($pass, 0, -1); - } - return $pass; - } -} -rewind(); $rii->valid(); $rii->next()) { - if (!$rii->isDot()) { - yield $rii->getSubPathname() => $rii->key(); - } - } - } -} -rm = $rm; - } - - /** - * @param bool $verbose - */ - public function run($verbose = false) { - if ($verbose) { - printf("Cleaning up %s ...\n", $this->rm); - } - if ($this->rm instanceof Tempfile) { - unset($this->rm); - } elseif (is_dir($this->rm)) { - $rdi = new RecursiveDirectoryIterator($this->rm, - FilesystemIterator::CURRENT_AS_SELF | // needed for 5.5 - FilesystemIterator::KEY_AS_PATHNAME | - FilesystemIterator::SKIP_DOTS); - $rii = new RecursiveIteratorIterator($rdi, - RecursiveIteratorIterator::CHILD_FIRST); - foreach ($rii as $path => $child) { - if ($child->isDir()) { - @rmdir($path); - } else { - @unlink($path); - } - } - @rmdir($this->rm); - } elseif (file_exists($this->rm)) { - @unlink($this->rm); - } - } -} -cwd = $cwd; - $cmd = $common_name . "-config"; - if (isset($prefix)) { - $cmd = $prefix . "/bin/" . $cmd; - } - $this->args = ["--with-php-config=$cmd"]; - if ($args) { - $this->args = array_merge($this->args, $args); - } - } - - public function run($verbose = false) { - if ($verbose !== false) { - printf("Running ./configure ...\n"); - } - $pwd = getcwd(); - if (!chdir($this->cwd)) { - throw new Exception; - } - try { - $cmd = new ExecCmd("./configure", $verbose); - $cmd->run($this->args); - } finally { - chdir($pwd); - } - } -} -source = $source; - } else { - $this->source = new PharData($source); - } - } - - /** - * @param bool $verbose - * @return \pharext\Tempdir - */ - public function run($verbose = false) { - if ($verbose) { - printf("Extracting %s ...\n", basename($this->source->getPath())); - } - if ($this->source instanceof Archive) { - return $this->source->extract(); - } - $dest = new Tempdir("extract"); - $this->source->extractTo($dest); - return $dest; - } -} -source = $source; - $this->branch = $branch; - } - - /** - * @param bool $verbose - * @return \pharext\Tempdir - */ - public function run($verbose = false) { - if ($verbose !== false) { - printf("Fetching %s ...\n", $this->source); - } - $local = new Tempdir("gitclone"); - $cmd = new ExecCmd("git", $verbose); - if (strlen($this->branch)) { - $cmd->run(["clone", "--depth", 1, "--branch", $this->branch, $this->source, $local]); - } else { - $cmd->run(["clone", $this->source, $local]); - } - return $local; - } -} -cwd = $cwd; - $this->sudo = $sudo; - $this->args = $args; - } - - /** - * - * @param bool $verbose - * @throws \pharext\Exception - */ - public function run($verbose = false) { - if ($verbose !== false) { - printf("Running make"); - if ($this->args) { - foreach ($this->args as $arg) { - printf(" %s", $arg); - } - } - printf(" ...\n"); - } - $pwd = getcwd(); - if (!chdir($this->cwd)) { - throw new Exception; - } - try { - $cmd = new ExecCmd("make", $verbose); - if (isset($this->sudo)) { - $cmd->setSu($this->sudo); - } - $args = $this->args; - if (!$verbose) { - $args = array_merge((array) $args, ["-s"]); - } - $cmd->run($args); - } finally { - chdir($pwd); - } - } -} -source = $source; - } - - private function openArchive($source) { - $hdr = file_get_contents($source, false, null, 0, 3); - if ($hdr === "\x1f\x8b\x08") { - $fd = fopen("compress.zlib://$source", "r"); - } elseif ($hdr === "BZh") { - $fd = fopen("compress.bzip2://$source", "r"); - } else { - $fd = fopen($source, "r"); - } - if (!is_resource($fd)) { - throw new Exception; - } - return $fd; - } - - public function run($verbose = false) { - if ($verbose !== false) { - printf("Fixing up a tarball with global pax header ...\n"); - } - $temp = new Tempfile("paxfix"); - stream_copy_to_stream($this->openArchive($this->source), - $temp->getStream(), -1, 1024); - $temp->closeStream(); - return (new Extract((string) $temp))->run($verbose); - } -}source = $source; - } - - /** - * @param bool $verbose - * @return string sanitized source location - * @throws \pahrext\Exception - */ - public function run($verbose = false) { - if ($verbose !== false) { - printf("Sanitizing PECL dir ...\n"); - } - $dirs = glob("{$this->source}/*", GLOB_ONLYDIR); - $files = array_diff(glob("{$this->source}/*"), $dirs); - $check = array_reduce($files, function($r, $v) { - return $v && fnmatch("package*.xml", basename($v)); - }, true); - - if (count($dirs) !== 1 || !$check) { - throw new Exception("Does not look like an extracted PECL dir: {$this->source}"); - } - - $dest = current($dirs); - - foreach ($files as $file) { - if ($verbose) { - printf("Moving %s into %s ...\n", basename($file), basename($dest)); - } - if (!rename($file, "$dest/" . basename($file))) { - throw new Exception; - } - } - - return $dest; - } -} -source = $source; - $this->stub = $stub; - $this->meta = $meta; - $this->readonly = $readonly; - } - - /** - * @param bool $verbose - * @return \pharext\Tempname - * @throws \pharext\Exception - */ - public function run($verbose = false) { - /* Phar::compress() and ::convert*() use strtok("."), ugh! - * so, be sure to not use any other dots in the filename - * except for .phar - */ - $temp = new Tempname("", "-pharext.phar"); - - $phar = new Phar($temp); - $phar->startBuffering(); - - if ($this->meta) { - $phar->setMetadata($this->meta); - } - if ($this->stub) { - (new PharStub($phar, $this->stub))->run($verbose); - } - - $phar->buildFromIterator((new Task\BundleGenerator)->run()); - - if ($this->source) { - if ($verbose) { - $bdir = $this->source->getBaseDir(); - $blen = strlen($bdir); - foreach ($this->source as $index => $file) { - if (is_resource($file)) { - printf("Packaging %s ...\n", $index); - $phar[$index] = $file; - } else { - printf("Packaging %s ...\n", $index = trim(substr($file, $blen), "/")); - $phar->addFile($file, $index); - } - } - } else { - $phar->buildFromIterator($this->source, $this->source->getBaseDir()); - } - } - - $phar->stopBuffering(); - - if (!chmod($temp, fileperms($temp) | 0111)) { - throw new Exception; - } - - return $temp; - } -}file = $file; - $this->package = new Phar($file); - $this->encoding = $encoding; - - switch ($encoding) { - case Phar::GZ: - $this->extension = ".gz"; - break; - case Phar::BZ2: - $this->extension = ".bz2"; - break; - } - } - - /** - * @param bool $verbose - * @return string - */ - public function run($verbose = false) { - if ($verbose) { - printf("Compressing %s ...\n", basename($this->package->getPath())); - } - /* stop shebang */ - $stub = $this->package->getStub(); - $phar = $this->package->compress($this->encoding); - $phar->setStub(substr($stub, strpos($stub, "\n")+1)); - return $this->file . $this->extension; - } -} -phar = $phar; - $this->dest = $dest; - $this->name = $name; - } - - /** - * @param bool $verbose - * @return string path to renamed phar - * @throws \pharext\Exception - */ - public function run($verbose = false) { - $extension = substr(strstr($this->phar, "-pharext.phar"), 8); - $name = sprintf("%s/%s.ext%s", $this->dest, $this->name, $extension); - - if ($verbose) { - printf("Renaming %s to %s ...\n", basename($this->phar), basename($name)); - } - - if (!rename($this->phar, $name)) { - throw new Exception; - } - - return $name; - } -} -phar = $phar; - } else { - $this->phar = new Phar($phar); - } - $this->pkey = new Openssl\PrivateKey($pkey, $pass); - } - - /** - * @param bool $verbose - * @return \pharext\Openssl\PrivateKey - */ - public function run($verbose = false) { - if ($verbose) { - printf("Signing %s ...\n", basename($this->phar->getPath())); - } - $this->pkey->sign($this->phar); - return $this->pkey; - } -} -phar = $phar; - if (!file_exists($this->stub = $stub)) { - throw new Exception("File '$stub' does not exist"); - } - } - - /** - * @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); - } -} -cwd = $cwd; - $cmd = $common_name . "ize"; - if (isset($prefix)) { - $cmd = $prefix . "/bin/" . $cmd; - } - $this->phpize = $cmd; - } - - /** - * @param bool $verbose - * @throws \pharext\Exception - */ - public function run($verbose = false) { - if ($verbose !== false) { - printf("Running %s ...\n", $this->phpize); - } - $pwd = getcwd(); - if (!chdir($this->cwd)) { - throw new Exception; - } - try { - $cmd = new ExecCmd($this->phpize, $verbose); - $cmd->run(); - } finally { - chdir($pwd); - } - } -} -source = $source; - $this->progress = $progress; - } - - private function createStreamContext() { - $progress = $this->progress; - - /* avoid bytes_max bug of older PHP versions */ - $maxbytes = 0; - return stream_context_create([],["notification" => function($notification, $severity, $message, $code, $bytes_cur, $bytes_max) use($progress, &$maxbytes) { - if ($bytes_max > $maxbytes) { - $maxbytes = $bytes_max; - } - switch ($notification) { - case STREAM_NOTIFY_CONNECT: - $progress(0); - break; - case STREAM_NOTIFY_PROGRESS: - $progress($maxbytes > 0 ? $bytes_cur/$maxbytes : .5); - break; - case STREAM_NOTIFY_COMPLETED: - /* this is sometimes not generated, why? */ - $progress(1); - break; - } - }]); - } - - /** - * @param bool $verbose - * @return \pharext\Task\Tempfile - * @throws \pharext\Exception - */ - public function run($verbose = false) { - if ($verbose !== false) { - printf("Fetching %s ...\n", $this->source); - } - $context = $this->createStreamContext(); - - if (!$remote = fopen($this->source, "r", false, $context)) { - throw new Exception; - } - - $local = new Tempfile("remote"); - if (!stream_copy_to_stream($remote, $local->getStream())) { - throw new Exception; - } - $local->closeStream(); - - /* STREAM_NOTIFY_COMPLETED is not generated, see above */ - call_user_func($this->progress, 1); - - return $local; - } -} -handle = fopen($path, "x"); - } while (!is_resource($this->handle) && $tries++ < 10); - umask($omask); - - if (!is_resource($this->handle)) { - throw new Exception("Could not create temporary file"); - } - - parent::__construct($path); - } - - /** - * Unlink the file - */ - public function __destruct() { - if (is_file($this->getPathname())) { - @unlink($this->getPathname()); - } - } - - /** - * Close the stream - */ - public function closeStream() { - fclose($this->handle); - } - - /** - * Retrieve the stream resource - * @return resource - */ - public function getStream() { - return $this->handle; - } -} -getUser(); - if (!is_dir($temp) && !mkdir($temp, 0700, true)) { - throw new Exception; - } - $this->name = $temp ."/". uniqid($prefix) . $suffix; - } - - private function getUser() { - if (extension_loaded("posix") && function_exists("posix_getpwuid")) { - return posix_getpwuid(posix_getuid())["name"]; - } - return trim(`whoami 2>/dev/null`) - ?: trim(`id -nu 2>/dev/null`) - ?: getenv("USER") - ?: get_current_user(); - } - - /** - * @return string - */ - public function __toString() { - return (string) $this->name; - } -} -args = new Cli\Args([ - ["h", "help", "Display this help", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - ["v", "verbose", "More output", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - ["q", "quiet", "Less output", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], - [null, "signature", "Show pharext signature", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "license", "Show pharext license", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [null, "version", "Show pharext version", - Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], - [0, "path", "Path to .ext.phar to update", - Cli\Args::REQUIRED|Cli\Args::MULTI], - ]); - } - - /** - * @inheritdoc - * @see \pharext\Command::run() - */ - public function run($argc, array $argv) { - $errs = []; - $prog = array_shift($argv); - foreach ($this->args->parse(--$argc, $argv) as $error) { - $errs[] = $error; - } - - if ($this->args["help"]) { - $this->header(); - $this->help($prog); - exit; - } - - try { - foreach (["signature", "license", "version"] as $opt) { - if ($this->args[$opt]) { - printf("%s\n", $this->metadata($opt)); - exit; - } - } - } catch (\Exception $e) { - $this->error("%s\n", $e->getMessage()); - exit(self::EARGS); - } - - - foreach ($this->args->validate() as $error) { - $errs[] = $error; - } - - if ($errs) { - if (!$this->args["quiet"]) { - $this->header(); - } - foreach ($errs as $err) { - $this->error("%s\n", $err); - } - printf("\n"); - if (!$this->args["quiet"]) { - $this->help($prog); - } - exit(self::EARGS); - } - - foreach ($this->args[0] as $file) { - $info = new SplFileInfo($file); - - while ($info->isLink()) { - $info = new SplFileInfo($info->getLinkTarget()); - } - - if ($info->isFile()) { - if (!$this->updatePackage($info)) { - $this->warn("Cannot upgrade pre-v3 packages\n"); - } - } else { - $this->error("File '%s' does not exist\n", $file); - exit(self::EARGS); - } - } - } - - /** - * Replace the pharext core in an .ext.phar package - * @param string $temp path to temp phar - * @return boolean FALSE if the package is too old (pre-v3) to upgrade - */ - private function replacePharext($temp) { - $phar = new Phar($temp, Phar::CURRENT_AS_SELF); - $phar->startBuffering(); - - if (!$meta = $phar->getMetadata()) { - // don't upgrade pre-v3 packages - return false; - } - - // replace current pharext files - $core = (new Task\BundleGenerator)->run($this->verbosity()); - $phar->buildFromIterator($core); - $stub = __DIR__."/../pharext_installer.php"; - (new Task\PharStub($phar, $stub))->run($this->verbosity()); - - // check dependencies - foreach ($phar as $info) { - if (fnmatch("*.ext.phar*", $info->getBasename())) { - $this->updatePackage($info, $phar); - } - } - - $phar->stopBuffering(); - - $phar->setMetadata([ - "version" => Metadata::version(), - "header" => Metadata::header(), - ] + $meta); - - $this->info("Updated pharext version from '%s' to '%s'\n", - isset($meta["version"]) ? $meta["version"] : "(unknown)", - $phar->getMetadata()["version"]); - - return true; - } - - /** - * Update an .ext.phar package to the current pharext version - * @param SplFileInfo $file - * @param Phar $phar the parent phar containing $file as dependency - * @return boolean FALSE if the package is too old (pre-v3) to upgrade - * @throws Exception - */ - private function updatePackage(SplFileInfo $file, Phar $phar = null) { - $this->info("Updating pharext core in '%s'...\n", basename($file)); - - $temp = new Tempname("update", substr(strstr($file, ".ext.phar"), 4)); - - if (!copy($file->getPathname(), $temp)) { - throw new Exception; - } - if (!chmod($temp, $file->getPerms())) { - throw new Exception; - } - - if (!$this->replacePharext($temp)) { - return false; - } - - if ($phar) { - $phar->addFile($temp, $file); - } elseif (!rename($temp, $file->getPathname())) { - throw new Exception; - } - - return true; - } -} -#!/usr/bin/env php - -#include -#include -#include -#include - -namespace pharext; - -if (extension_loaded("Phar")) { - \Phar::interceptFileFuncs(); - \Phar::mapPhar(); - $phardir = "phar://".__FILE__; -} else { - $archive = new Archive(__FILE__); - $phardir = $archive->extract(); -} - -set_include_path("$phardir:". get_include_path()); - -$installer = new Installer(); -$installer->run($argc, $argv); - -__HALT_COMPILER(); -#!/usr/bin/php -dphar.readonly=0 -run($argc, $argv); - -__HALT_COMPILER(); -#!/usr/bin/php -dphar.readonly=0 -run($argc, $argv); - -__HALT_COMPILER(); - - - raphf - pecl.php.net - Resource and persistent handles factory - A reusable split-off of pecl_http's persistent handle and resource factory API. - - Michael Wallner - mike - mike@php.net - yes - - 2015-07-28 - - 1.1.0 - 1.0.0 - - - stable - stable - - BSD, revised - - - - - - - - - - - - - - - - - - - - - - - 5.3.0 - 7.0.0 - 7.0.0 - - - 1.4.0 - - - - raphf - - - -raphf -Michael Wallner -Copyright (c) 2013, Michael Wallner . -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# Doxyfile 1.8.9.1 - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -DOXYFILE_ENCODING = UTF-8 -PROJECT_NAME = "Resource and persistent handle factory API" -PROJECT_NUMBER = -PROJECT_BRIEF = "A facility to manage possibly persistent resources with a comprehensible API. Provides simliar functionality like the zend_list API, but with more flexiblity and freedom." -PROJECT_LOGO = raphf.png -OUTPUT_DIRECTORY = -CREATE_SUBDIRS = NO -ALLOW_UNICODE_NAMES = NO -OUTPUT_LANGUAGE = English -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = NO -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = YES -QT_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -INHERIT_DOCS = YES -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 4 -ALIASES = -TCL_SUBST = -OPTIMIZE_OUTPUT_FOR_C = YES -OPTIMIZE_OUTPUT_JAVA = NO -OPTIMIZE_FOR_FORTRAN = NO -OPTIMIZE_OUTPUT_VHDL = NO -EXTENSION_MAPPING = -MARKDOWN_SUPPORT = YES -AUTOLINK_SUPPORT = YES -BUILTIN_STL_SUPPORT = NO -CPP_CLI_SUPPORT = NO -SIP_SUPPORT = NO -IDL_PROPERTY_SUPPORT = YES -DISTRIBUTE_GROUP_DOC = NO -SUBGROUPING = YES -INLINE_GROUPED_CLASSES = NO -INLINE_SIMPLE_STRUCTS = YES -TYPEDEF_HIDES_STRUCT = NO -LOOKUP_CACHE_SIZE = 0 -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = YES -EXTRACT_PRIVATE = NO -EXTRACT_PACKAGE = NO -EXTRACT_STATIC = NO -EXTRACT_LOCAL_CLASSES = NO -EXTRACT_LOCAL_METHODS = NO -EXTRACT_ANON_NSPACES = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -HIDE_COMPOUND_REFERENCE= NO -SHOW_INCLUDE_FILES = YES -SHOW_GROUPED_MEMB_INC = NO -FORCE_LOCAL_INCLUDES = NO -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -SORT_BRIEF_DOCS = NO -SORT_MEMBERS_CTORS_1ST = NO -SORT_GROUP_NAMES = NO -SORT_BY_SCOPE_NAME = NO -STRICT_PROTO_MATCHING = NO -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -GENERATE_DEPRECATEDLIST= YES -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = YES -SHOW_FILES = YES -SHOW_NAMESPACES = YES -FILE_VERSION_FILTER = -LAYOUT_FILE = -CITE_BIB_FILES = -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = php_raphf.h -INPUT_ENCODING = UTF-8 -FILE_PATTERNS = -RECURSIVE = NO -EXCLUDE = -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXCLUDE_SYMBOLS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = NO -FILTER_SOURCE_PATTERNS = -USE_MDFILE_AS_MAINPAGE = -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = NO -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = YES -REFERENCES_RELATION = NO -REFERENCES_LINK_SOURCE = YES -SOURCE_TOOLTIPS = YES -USE_HTAGS = NO -VERBATIM_HEADERS = YES -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = YES -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = . -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_EXTRA_STYLESHEET = -HTML_EXTRA_FILES = -HTML_COLORSTYLE_HUE = 220 -HTML_COLORSTYLE_SAT = 100 -HTML_COLORSTYLE_GAMMA = 80 -HTML_TIMESTAMP = NO -HTML_DYNAMIC_SECTIONS = NO -HTML_INDEX_NUM_ENTRIES = 100 -GENERATE_DOCSET = NO -DOCSET_FEEDNAME = "Doxygen generated docs" -DOCSET_BUNDLE_ID = org.doxygen.Project -DOCSET_PUBLISHER_ID = org.doxygen.Publisher -DOCSET_PUBLISHER_NAME = Publisher -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -CHM_INDEX_ENCODING = -BINARY_TOC = NO -TOC_EXPAND = NO -GENERATE_QHP = NO -QCH_FILE = -QHP_NAMESPACE = org.doxygen.Project -QHP_VIRTUAL_FOLDER = doc -QHP_CUST_FILTER_NAME = -QHP_CUST_FILTER_ATTRS = -QHP_SECT_FILTER_ATTRS = -QHG_LOCATION = -GENERATE_ECLIPSEHELP = NO -ECLIPSE_DOC_ID = org.doxygen.Project -DISABLE_INDEX = NO -GENERATE_TREEVIEW = YES -ENUM_VALUES_PER_LINE = 4 -TREEVIEW_WIDTH = 250 -EXT_LINKS_IN_WINDOW = NO -FORMULA_FONTSIZE = 10 -FORMULA_TRANSPARENT = YES -USE_MATHJAX = NO -MATHJAX_FORMAT = HTML-CSS -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest -MATHJAX_EXTENSIONS = -MATHJAX_CODEFILE = -SEARCHENGINE = YES -SERVER_BASED_SEARCH = NO -EXTERNAL_SEARCH = NO -SEARCHENGINE_URL = -SEARCHDATA_FILE = searchdata.xml -EXTERNAL_SEARCH_ID = -EXTRA_SEARCH_MAPPINGS = -#--------------------------------------------------------------------------- -# Configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4 -EXTRA_PACKAGES = -LATEX_HEADER = -LATEX_FOOTER = -LATEX_EXTRA_STYLESHEET = -LATEX_EXTRA_FILES = -PDF_HYPERLINKS = YES -USE_PDFLATEX = YES -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -LATEX_SOURCE_CODE = NO -LATEX_BIB_STYLE = plain -#--------------------------------------------------------------------------- -# Configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -RTF_SOURCE_CODE = NO -#--------------------------------------------------------------------------- -# Configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_SUBDIR = -MAN_LINKS = NO -#--------------------------------------------------------------------------- -# Configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = NO -XML_OUTPUT = xml -XML_PROGRAMLISTING = YES -#--------------------------------------------------------------------------- -# Configuration options related to the DOCBOOK output -#--------------------------------------------------------------------------- -GENERATE_DOCBOOK = NO -DOCBOOK_OUTPUT = docbook -DOCBOOK_PROGRAMLISTING = NO -#--------------------------------------------------------------------------- -# Configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -#--------------------------------------------------------------------------- -# Configuration options related to the Perl module output -#--------------------------------------------------------------------------- -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = YES -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = DOXYGEN \ - TSRMLS_C= \ - TSRMLS_D= \ - TSRMLS_CC= \ - TSRMLS_DC= \ - PHP_RAPHF_API= -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES -#--------------------------------------------------------------------------- -# Configuration options related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -EXTERNAL_PAGES = YES -PERL_PATH = /usr/bin/perl -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = YES -MSCGEN_PATH = -DIA_PATH = -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = YES -DOT_NUM_THREADS = 0 -DOT_FONTNAME = Helvetica -DOT_FONTSIZE = 10 -DOT_FONTPATH = -CLASS_GRAPH = NO -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -UML_LIMIT_NUM_FIELDS = 10 -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = YES -CALLER_GRAPH = YES -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -INTERACTIVE_SVG = NO -DOT_PATH = -DOTFILE_DIRS = -MSCFILE_DIRS = -DIAFILE_DIRS = -PLANTUML_JAR_PATH = -PLANTUML_INCLUDE_PATH = -DOT_GRAPH_MAX_NODES = 50 -MAX_DOT_GRAPH_DEPTH = 0 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -PHP_ARG_ENABLE(raphf, whether to enable raphf support, -[ --enable-raphf Enable resource and persistent handles factory support]) - -if test "$PHP_RAPHF" != "no"; then - PHP_INSTALL_HEADERS(ext/raphf, php_raphf.h php_raphf_api.h) - PHP_NEW_EXTENSION(raphf, php_raphf.c, $ext_shared) -fi - - -ARG_ENABLE("raphf", "for raphf support", "no"); - -if (PHP_RAPHF == "yes") { - EXTENSION("raphf", "php_raphf.c"); - - AC_DEFINE("HAVE_RAPHF", 1); - PHP_INSTALL_HEADERS("ext/raphf", "php_raphf.h"); -} -/* - +--------------------------------------------------------------------+ - | PECL :: raphf | - +--------------------------------------------------------------------+ - | Redistribution and use in source and binary forms, with or without | - | modification, are permitted provided that the conditions mentioned | - | in the accompanying LICENSE file are met. | - +--------------------------------------------------------------------+ - | Copyright (c) 2013, Michael Wallner | - +--------------------------------------------------------------------+ -*/ - -#ifndef PHP_RAPHF_H -#define PHP_RAPHF_H - -extern zend_module_entry raphf_module_entry; -#define phpext_raphf_ptr &raphf_module_entry - -#define PHP_RAPHF_VERSION "1.1.0" - -#ifdef PHP_WIN32 -# define PHP_RAPHF_API __declspec(dllexport) -#elif defined(__GNUC__) && __GNUC__ >= 4 -# define PHP_RAPHF_API extern __attribute__ ((visibility("default"))) -#else -# define PHP_RAPHF_API extern -#endif - -#ifdef ZTS -# include "TSRM.h" -#endif - -#include "php_raphf_api.h" - -#endif /* PHP_RAPHF_H */ - - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim600: noet sw=4 ts=4 fdm=marker - * vim<600: noet sw=4 ts=4 - */ -/* - +--------------------------------------------------------------------+ - | PECL :: raphf | - +--------------------------------------------------------------------+ - | Redistribution and use in source and binary forms, with or without | - | modification, are permitted provided that the conditions mentioned | - | in the accompanying LICENSE file are met. | - +--------------------------------------------------------------------+ - | Copyright (c) 2013, Michael Wallner | - +--------------------------------------------------------------------+ -*/ - -#ifndef PHP_RAPHF_API_H -#define PHP_RAPHF_API_H - -/** - * A resource constructor. - * - * @param opaque is the \a data from php_persistent_handle_provide() - * @param init_arg is the \a init_arg from php_resource_factory_init() - * @return the created (persistent) handle - */ -typedef void *(*php_resource_factory_handle_ctor_t)(void *opaque, - void *init_arg TSRMLS_DC); - -/** - * The copy constructor of a resource. - * - * @param opaque the factory's data - * @param handle the (persistent) handle to copy - */ -typedef void *(*php_resource_factory_handle_copy_t)(void *opaque, - void *handle TSRMLS_DC); - -/** - * The destructor of a resource. - * - * @param opaque the factory's data - * @param handle the handle to destroy - */ -typedef void (*php_resource_factory_handle_dtor_t)(void *opaque, - void *handle TSRMLS_DC); - -/** - * The resource ops consisting of a ctor, a copy ctor and a dtor. - * - * Define this ops and register them with php_persistent_handle_provide() - * in MINIT. - */ -typedef struct php_resource_factory_ops { - /** The resource constructor */ - php_resource_factory_handle_ctor_t ctor; - /** The resource's copy constructor */ - php_resource_factory_handle_copy_t copy; - /** The resource's destructor */ - php_resource_factory_handle_dtor_t dtor; -} php_resource_factory_ops_t; - -/** - * The resource factory. - */ -typedef struct php_resource_factory { - /** The resource ops */ - php_resource_factory_ops_t fops; - /** Opaque user data */ - void *data; - /** User data destructor */ - void (*dtor)(void *data); - /** How often this factory is referenced */ - unsigned refcount; -} php_resource_factory_t; - -/** - * Initialize a resource factory. - * - * If you register a \a dtor for a resource factory used with a persistent - * handle provider, be sure to call php_persistent_handle_cleanup() for your - * registered provider in MSHUTDOWN, else the dtor will point to no longer - * available memory if the extension has already been unloaded. - * - * @param f the factory to initialize; if NULL allocated on the heap - * @param fops the resource ops to assign to the factory - * @param data opaque user data; may be NULL - * @param dtor a destructor for the data; may be NULL - * @return \a f or an allocated resource factory - */ -PHP_RAPHF_API php_resource_factory_t *php_resource_factory_init( - php_resource_factory_t *f, php_resource_factory_ops_t *fops, void *data, - void (*dtor)(void *data)); - -/** - * Increase the refcount of the resource factory. - * - * @param rf the resource factory - * @return the new refcount - */ -PHP_RAPHF_API unsigned php_resource_factory_addref(php_resource_factory_t *rf); - -/** - * Destroy the resource factory. - * - * If the factory's refcount reaches 0, the \a dtor for \a data is called. - * - * @param f the resource factory - */ -PHP_RAPHF_API void php_resource_factory_dtor(php_resource_factory_t *f); - -/** - * Destroy and free the resource factory. - * - * Calls php_resource_factory_dtor() and frees \æ f if the factory's refcount - * reached 0. - * - * @param f the resource factory - */ -PHP_RAPHF_API void php_resource_factory_free(php_resource_factory_t **f); - -/** - * Construct a resource by the resource factory \a f - * - * @param f the resource factory - * @param init_arg for the resource constructor - * @return the new resource - */ -PHP_RAPHF_API void *php_resource_factory_handle_ctor(php_resource_factory_t *f, - void *init_arg TSRMLS_DC); - -/** - * Create a copy of the resource \a handle - * - * @param f the resource factory - * @param handle the resource to copy - * @return the copy - */ -PHP_RAPHF_API void *php_resource_factory_handle_copy(php_resource_factory_t *f, - void *handle TSRMLS_DC); - -/** - * Destroy (and free) the resource - * - * @param f the resource factory - * @param handle the resource to destroy - */ -PHP_RAPHF_API void php_resource_factory_handle_dtor(php_resource_factory_t *f, - void *handle TSRMLS_DC); - -/** - * Persistent handles storage - */ -typedef struct php_persistent_handle_list { - /** Storage of free resources */ - HashTable free; - /** Count of acquired resources */ - ulong used; -} php_persistent_handle_list_t; - -/** - * Definition of a persistent handle provider. - * Holds a resource factory an a persistent handle list. - */ -typedef struct php_persistent_handle_provider { - /** - * The list of free handles. - * Hash of "ident" => array(handles) entries. Persistent handles are - * acquired out of this list. - */ - php_persistent_handle_list_t list; - - /** - * The resource factory. - * New handles are created by this factory. - */ - php_resource_factory_t rf; -} php_persistent_handle_provider_t; - -typedef struct php_persistent_handle_factory php_persistent_handle_factory_t; - -/** - * Wakeup the persistent handle on re-acquisition. - */ -typedef void (*php_persistent_handle_wakeup_t)( - php_persistent_handle_factory_t *f, void **handle TSRMLS_DC); -/** - * Retire the persistent handle on release. - */ -typedef void (*php_persistent_handle_retire_t)( - php_persistent_handle_factory_t *f, void **handle TSRMLS_DC); - -/** - * Definition of a persistent handle factory. - * - * php_persistent_handle_concede() will return a pointer to a - * php_persistent_handle_factory if a provider for the \a name_str has - * been registered with php_persistent_handle_provide(). - */ -struct php_persistent_handle_factory { - /** The persistent handle provider */ - php_persistent_handle_provider_t *provider; - /** The persistent handle wakeup routine; may be NULL */ - php_persistent_handle_wakeup_t wakeup; - /** The persistent handle retire routine; may be NULL */ - php_persistent_handle_retire_t retire; - - /** The ident for which this factory manages resources */ - struct { - /** ident string */ - char *str; - /** ident length */ - size_t len; - } ident; - - /** Whether it has to be free'd on php_persistent_handle_abandon() */ - unsigned free_on_abandon:1; -}; - -/** - * Register a persistent handle provider in MINIT. - * - * Registers a factory provider for \a name_str with \a fops resource factory - * ops. Call this in your MINIT. - * - * A php_resource_factory will be created with \a fops, \a data and \a dtor - * and will be stored together with a php_persistent_handle_list in the global - * raphf hash. - * - * A php_persistent_handle_factory can then be retrieved by - * php_persistent_handle_concede() at runtime. - * - * @param name_str the provider name, e.g. "http\Client\Curl" - * @param name_len the provider name length, e.g. strlen("http\Client\Curl") - * @param fops the resource factory ops - * @param data opaque user data - * @param dtor \a data destructor - * @return SUCCESS/FAILURE - */ -PHP_RAPHF_API int /* SUCCESS|FAILURE */ php_persistent_handle_provide( - const char *name_str, size_t name_len, php_resource_factory_ops_t *fops, - void *data, void (*dtor)(void *) TSRMLS_DC); - -/** - * Retrieve a persistent handle factory at runtime. - * - * If a persistent handle provider has been registered for \a name_str, a new - * php_persistent_handle_factory creating resources in the \a ident_str - * namespace will be constructed. - * - * The wakeup routine \a wakeup and the retire routine \a retire will be - * assigned to the new php_persistent_handle_factory. - * - * @param a pointer to a factory; allocated on the heap if NULL - * @param name_str the provider name, e.g. "http\Client\Curl" - * @param name_len the provider name length, e.g. strlen("http\Client\Curl") - * @param ident_str the subsidiary namespace, e.g. "php.net:80" - * @param ident_len the subsidiary namespace lenght, e.g. strlen("php.net:80") - * @param wakeup any persistent handle wakeup routine - * @param retire any persistent handle retire routine - * @return \a a or an allocated persistent handle factory - */ -PHP_RAPHF_API php_persistent_handle_factory_t *php_persistent_handle_concede( - php_persistent_handle_factory_t *a, const char *name_str, - size_t name_len, const char *ident_str, size_t ident_len, - php_persistent_handle_wakeup_t wakeup, - php_persistent_handle_retire_t retire TSRMLS_DC); - -/** - * Abandon the persistent handle factory. - * - * Destroy a php_persistent_handle_factory created by - * php_persistent_handle_concede(). If the memory for the factory was allocated, - * it will automatically be free'd. - * - * @param a the persistent handle factory to destroy - */ -PHP_RAPHF_API void php_persistent_handle_abandon( - php_persistent_handle_factory_t *a); - -/** - * Acquire a persistent handle. - * - * That is, either re-use a resource from the free list or create a new handle. - * - * If a handle is acquired from the free list, the - * php_persistent_handle_factory::wakeup callback will be executed for that - * handle. - * - * @param a the persistent handle factory - * @param init_arg the \a init_arg for php_resource_factory_handle_ctor() - * @return the acquired resource - */ -PHP_RAPHF_API void *php_persistent_handle_acquire( - php_persistent_handle_factory_t *a, void *init_arg TSRMLS_DC); - -/** - * Release a persistent handle. - * - * That is, either put it back into the free list for later re-use or clean it - * up with php_resource_factory_handle_dtor(). - * - * If a handle is put back into the free list, the - * php_persistent_handle_factory::retire callback will be executed for that - * handle. - * - * @param a the persistent handle factory - * @param handle the handle to release - */ -PHP_RAPHF_API void php_persistent_handle_release( - php_persistent_handle_factory_t *a, void *handle TSRMLS_DC); - -/** - * Copy a persistent handle. - * - * Let the underlying resource factory copy the \a handle. - * - * @param a the persistent handle factory - * @param handle the resource to accrete - */ -PHP_RAPHF_API void *php_persistent_handle_accrete( - php_persistent_handle_factory_t *a, void *handle TSRMLS_DC); - -/** - * Retrieve persistent handle resource factory ops. - * - * These ops can be used to mask a persistent handle factory as - * resource factory itself, so you can transparently use the - * resource factory API, both for persistent and non-persistent - * ressources. - * - * Example: - * ~~~~~~~~~~~~~~~{.c} - * php_resource_factory_t *create_my_rf(const char *persistent_id_str, - * size_t persistent_id_len TSRMLS_DC) - * { - * php_resource_factory_t *rf; - * - * if (persistent_id_str) { - * php_persistent_handle_factory_t *pf; - * php_resource_factory_ops_t *ops; - * - * ops = php_persistent_handle_get_resource_factory_ops(); - * - * pf = php_persistent_handle_concede(NULL, "my", 2, - * persistent_id_str, persistent_id_len, NULL, NULL TSRMLS_CC); - * - * rf = php_persistent_handle_resource_factory_init(NULL, pf); - * } else { - * rf = php_resource_factory_init(NULL, &myops, NULL, NULL); - * } - * return rf; - * } - * ~~~~~~~~~~~~~~~ - */ -PHP_RAPHF_API php_resource_factory_ops_t * -php_persistent_handle_get_resource_factory_ops(void); - -/** - * Create a resource factory for persistent handles. - * - * This will create a resource factory with persistent handle ops, which wraps - * the provided reource factory \a pf. - * - * @param a the persistent handle resource factory to initialize - * @param pf the resource factory to wrap - */ -PHP_RAPHF_API php_resource_factory_t * -php_persistent_handle_resource_factory_init(php_resource_factory_t *a, - php_persistent_handle_factory_t *pf); - -/** - * Check whether a resource factory is a persistent handle resource factory. - * - * @param a the resource factory to check - */ -PHP_RAPHF_API zend_bool php_resource_factory_is_persistent( - php_resource_factory_t *a); - -/** - * Clean persistent handles up. - * - * Destroy persistent handles of provider \a name_str and in subsidiary - * namespace \a ident_str. - * - * If \a name_str is NULL, all persistent handles of all providers with a - * matching \a ident_str will be cleaned up. - * - * If \a ident_str is NULL all persistent handles of the provider will be - * cleaned up. - * - * Ergo, if both, \a name_str and \a ident_str are NULL, then all - * persistent handles will be cleaned up. - * - * You must call this in MSHUTDOWN, if your resource factory ops hold a - * registered php_resource_factory::dtor, else the dtor will point to - * memory not any more available if the extension has already been unloaded. - * - * @param name_str the provider name; may be NULL - * @param name_len the provider name length - * @param ident_str the subsidiary namespace name; may be NULL - * @param ident_len the subsidiary namespace name length - */ -PHP_RAPHF_API void php_persistent_handle_cleanup(const char *name_str, - size_t name_len, const char *ident_str, size_t ident_len TSRMLS_DC); - -/** - * Retrieve statistics about the current process/thread's persistent handles. - * - * @return a HashTable like: - * ~~~~~~~~~~~~~~~ - * [ - * "name" => [ - * "ident" => [ - * "used" => 1, - * "free" => 0, - * ] - * ] - * ] - * ~~~~~~~~~~~~~~~ - */ -PHP_RAPHF_API HashTable *php_persistent_handle_statall(HashTable *ht TSRMLS_DC); - -#endif /* PHP_RAPHF_API_H */ - - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim600: noet sw=4 ts=4 fdm=marker - * vim<600: noet sw=4 ts=4 - */ -/* - +--------------------------------------------------------------------+ - | PECL :: raphf | - +--------------------------------------------------------------------+ - | Redistribution and use in source and binary forms, with or without | - | modification, are permitted provided that the conditions mentioned | - | in the accompanying LICENSE file are met. | - +--------------------------------------------------------------------+ - | Copyright (c) 2013, Michael Wallner | - +--------------------------------------------------------------------+ -*/ - -#ifdef HAVE_CONFIG_H -# include "config.h" -#endif - -#include "php.h" -#include "php_ini.h" -#include "ext/standard/info.h" -#include "php_raphf.h" - -struct php_persistent_handle_globals { - ulong limit; - HashTable hash; -}; - -ZEND_BEGIN_MODULE_GLOBALS(raphf) - struct php_persistent_handle_globals persistent_handle; -ZEND_END_MODULE_GLOBALS(raphf) - -#ifdef ZTS -# define PHP_RAPHF_G ((zend_raphf_globals *) \ - (*((void ***) tsrm_ls))[TSRM_UNSHUFFLE_RSRC_ID(raphf_globals_id)]) -#else -# define PHP_RAPHF_G (&raphf_globals) -#endif - -ZEND_DECLARE_MODULE_GLOBALS(raphf) - -#if PHP_VERSION_ID < 50500 -#undef SUCCESS -#undef FAILURE -typedef enum { - SUCCESS = 0, - FAILURE = -1 -} ZEND_RESULT_CODE; -#endif - -#ifndef PHP_RAPHF_DEBUG_PHANDLES -# define PHP_RAPHF_DEBUG_PHANDLES 0 -#endif -#if PHP_RAPHF_DEBUG_PHANDLES -# undef inline -# define inline -#endif - -php_resource_factory_t *php_resource_factory_init(php_resource_factory_t *f, - php_resource_factory_ops_t *fops, void *data, void (*dtor)(void *data)) -{ - if (!f) { - f = emalloc(sizeof(*f)); - } - memset(f, 0, sizeof(*f)); - - memcpy(&f->fops, fops, sizeof(*fops)); - - f->data = data; - f->dtor = dtor; - - f->refcount = 1; - - return f; -} - -unsigned php_resource_factory_addref(php_resource_factory_t *rf) -{ - return ++rf->refcount; -} - -void php_resource_factory_dtor(php_resource_factory_t *f) -{ - --f->refcount; - - if (!f->refcount) { - if (f->dtor) { - f->dtor(f->data); - } - } -} - -void php_resource_factory_free(php_resource_factory_t **f) -{ - if (*f) { - php_resource_factory_dtor(*f); - if (!(*f)->refcount) { - efree(*f); - *f = NULL; - } - } -} - -void *php_resource_factory_handle_ctor(php_resource_factory_t *f, - void *init_arg TSRMLS_DC) -{ - if (f->fops.ctor) { - return f->fops.ctor(f->data, init_arg TSRMLS_CC); - } - return NULL; -} - -void *php_resource_factory_handle_copy(php_resource_factory_t *f, - void *handle TSRMLS_DC) -{ - if (f->fops.copy) { - return f->fops.copy(f->data, handle TSRMLS_CC); - } - return NULL; -} - -void php_resource_factory_handle_dtor(php_resource_factory_t *f, - void *handle TSRMLS_DC) -{ - if (f->fops.dtor) { - f->fops.dtor(f->data, handle TSRMLS_CC); - } -} - -php_resource_factory_t *php_persistent_handle_resource_factory_init( - php_resource_factory_t *a, php_persistent_handle_factory_t *pf) -{ - return php_resource_factory_init(a, - php_persistent_handle_get_resource_factory_ops(), pf, - (void(*)(void*)) php_persistent_handle_abandon); -} - -zend_bool php_resource_factory_is_persistent(php_resource_factory_t *a) -{ - return a->dtor == (void(*)(void *)) php_persistent_handle_abandon; -} - - -static inline php_persistent_handle_list_t *php_persistent_handle_list_init( - php_persistent_handle_list_t *list) -{ - int free_list; - - if ((free_list = !list)) { - list = pemalloc(sizeof(php_persistent_handle_list_t), 1); - } - - list->used = 0; - - if (SUCCESS != zend_hash_init(&list->free, 0, NULL, NULL, 1)) { - if (free_list) { - pefree(list, 1); - } - list = NULL; - } - - return list; -} - -static int php_persistent_handle_apply_stat(void *p TSRMLS_DC, int argc, - va_list argv, zend_hash_key *key) -{ - php_persistent_handle_list_t **list = p; - zval *zsubentry, *zentry = va_arg(argv, zval *); - - MAKE_STD_ZVAL(zsubentry); - array_init(zsubentry); - add_assoc_long_ex(zsubentry, ZEND_STRS("used"), (*list)->used); - add_assoc_long_ex(zsubentry, ZEND_STRS("free"), - zend_hash_num_elements(&(*list)->free)); - add_assoc_zval_ex(zentry, key->arKey, key->nKeyLength, zsubentry); - - return ZEND_HASH_APPLY_KEEP; -} - -static int php_persistent_handle_apply_statall(void *p TSRMLS_DC, int argc, - va_list argv, zend_hash_key *key) -{ - php_persistent_handle_provider_t *provider = p; - HashTable *ht = va_arg(argv, HashTable *); - zval *zentry; - - MAKE_STD_ZVAL(zentry); - array_init(zentry); - - zend_hash_apply_with_arguments(&provider->list.free TSRMLS_CC, - php_persistent_handle_apply_stat, 1, zentry); - zend_symtable_update(ht, key->arKey, key->nKeyLength, &zentry, - sizeof(zval *), NULL); - - return ZEND_HASH_APPLY_KEEP; -} - -static int php_persistent_handle_apply_cleanup_ex(void *pp, void *arg TSRMLS_DC) -{ - php_resource_factory_t *rf = arg; - void **handle = pp; - -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "DESTROY: %p\n", *handle); -#endif - php_resource_factory_handle_dtor(rf, *handle TSRMLS_CC); - return ZEND_HASH_APPLY_REMOVE; -} - -static int php_persistent_handle_apply_cleanup(void *pp, void *arg TSRMLS_DC) -{ - php_resource_factory_t *rf = arg; - php_persistent_handle_list_t **listp = pp; - - zend_hash_apply_with_argument(&(*listp)->free, - php_persistent_handle_apply_cleanup_ex, rf TSRMLS_CC); - if ((*listp)->used) { - return ZEND_HASH_APPLY_KEEP; - } - zend_hash_destroy(&(*listp)->free); -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "LSTFREE: %p\n", *listp); -#endif - pefree(*listp, 1); - *listp = NULL; - return ZEND_HASH_APPLY_REMOVE; -} - -static inline void php_persistent_handle_list_dtor( - php_persistent_handle_list_t *list, - php_persistent_handle_provider_t *provider TSRMLS_DC) -{ -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "LSTDTOR: %p\n", list); -#endif - zend_hash_apply_with_argument(&list->free, - php_persistent_handle_apply_cleanup_ex, &provider->rf TSRMLS_CC); - zend_hash_destroy(&list->free); -} - -static inline void php_persistent_handle_list_free( - php_persistent_handle_list_t **list, - php_persistent_handle_provider_t *provider TSRMLS_DC) -{ - php_persistent_handle_list_dtor(*list, provider TSRMLS_CC); -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "LSTFREE: %p\n", *list); -#endif - pefree(*list, 1); - *list = NULL; -} - -static int php_persistent_handle_list_apply_dtor(void *listp, - void *provider TSRMLS_DC) -{ - php_persistent_handle_list_free(listp, provider TSRMLS_CC); - return ZEND_HASH_APPLY_REMOVE; -} - -static inline php_persistent_handle_list_t *php_persistent_handle_list_find( - php_persistent_handle_provider_t *provider, const char *ident_str, - size_t ident_len TSRMLS_DC) -{ - php_persistent_handle_list_t **list, *new_list; - ZEND_RESULT_CODE rv = zend_symtable_find(&provider->list.free, ident_str, - ident_len + 1, (void *) &list); - - if (SUCCESS == rv) { -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "LSTFIND: %p\n", *list); -#endif - return *list; - } - - if ((new_list = php_persistent_handle_list_init(NULL))) { - rv = zend_symtable_update(&provider->list.free, ident_str, ident_len+1, - (void *) &new_list, sizeof(php_persistent_handle_list_t *), - (void *) &list); - if (SUCCESS == rv) { -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "LSTFIND: %p (new)\n", *list); -#endif - return *list; - } - php_persistent_handle_list_free(&new_list, provider TSRMLS_CC); - } - - return NULL; -} - -static int php_persistent_handle_apply_cleanup_all(void *p TSRMLS_DC, int argc, - va_list argv, zend_hash_key *key) -{ - php_persistent_handle_provider_t *provider = p; - const char *ident_str = va_arg(argv, const char *); - size_t ident_len = va_arg(argv, size_t); - php_persistent_handle_list_t *list; - - if (ident_str && ident_len) { - if ((list = php_persistent_handle_list_find(provider, ident_str, - ident_len TSRMLS_CC))) { - zend_hash_apply_with_argument(&list->free, - php_persistent_handle_apply_cleanup_ex, - &provider->rf TSRMLS_CC); - } - } else { - zend_hash_apply_with_argument(&provider->list.free, - php_persistent_handle_apply_cleanup, &provider->rf TSRMLS_CC); - } - - return ZEND_HASH_APPLY_KEEP; -} - -static void php_persistent_handle_hash_dtor(void *p) -{ - php_persistent_handle_provider_t *provider; - TSRMLS_FETCH(); - - provider = (php_persistent_handle_provider_t *) p; - zend_hash_apply_with_argument(&provider->list.free, - php_persistent_handle_list_apply_dtor, provider TSRMLS_CC); - zend_hash_destroy(&provider->list.free); - php_resource_factory_dtor(&provider->rf); -} - -PHP_RAPHF_API ZEND_RESULT_CODE php_persistent_handle_provide(const char *name_str, - size_t name_len, php_resource_factory_ops_t *fops, void *data, - void (*dtor)(void *) TSRMLS_DC) -{ - ZEND_RESULT_CODE status = FAILURE; - php_persistent_handle_provider_t provider; - - if (php_persistent_handle_list_init(&provider.list)) { - if (php_resource_factory_init(&provider.rf, fops, data, dtor)) { -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "PROVIDE: %p %s\n", PHP_RAPHF_G, name_str); -#endif - - status = zend_symtable_update(&PHP_RAPHF_G->persistent_handle.hash, - name_str, name_len+1, (void *) &provider, - sizeof(php_persistent_handle_provider_t), NULL); - if (SUCCESS != status) { - php_resource_factory_dtor(&provider.rf); - } - } - } - - return status; -} - -php_persistent_handle_factory_t *php_persistent_handle_concede( - php_persistent_handle_factory_t *a, const char *name_str, - size_t name_len, const char *ident_str, size_t ident_len, - php_persistent_handle_wakeup_t wakeup, - php_persistent_handle_retire_t retire TSRMLS_DC) -{ - ZEND_RESULT_CODE status = FAILURE; - php_persistent_handle_factory_t *free_a = NULL; - - if (!a) { - free_a = a = emalloc(sizeof(*a)); - } - memset(a, 0, sizeof(*a)); - - status = zend_symtable_find(&PHP_RAPHF_G->persistent_handle.hash, name_str, - name_len+1, (void *) &a->provider); - - if (SUCCESS == status) { - a->ident.str = estrndup(ident_str, ident_len); - a->ident.len = ident_len; - - a->wakeup = wakeup; - a->retire = retire; - - if (free_a) { - a->free_on_abandon = 1; - } - } else { - if (free_a) { - efree(free_a); - } - a = NULL; - } - -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "CONCEDE: %p %p (%s) (%s)\n", PHP_RAPHF_G, - a ? a->provider : NULL, name_str, ident_str); -#endif - - return a; -} - -PHP_RAPHF_API void php_persistent_handle_abandon( - php_persistent_handle_factory_t *a) -{ - zend_bool f = a->free_on_abandon; - -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "ABANDON: %p\n", a->provider); -#endif - - STR_FREE(a->ident.str); - memset(a, 0, sizeof(*a)); - if (f) { - efree(a); - } -} - -void *php_persistent_handle_acquire( - php_persistent_handle_factory_t *a, void *init_arg TSRMLS_DC) -{ - int key; - ZEND_RESULT_CODE rv; - ulong index; - void **handle_ptr, *handle = NULL; - php_persistent_handle_list_t *list; - - list = php_persistent_handle_list_find(a->provider, a->ident.str, - a->ident.len TSRMLS_CC); - if (list) { - zend_hash_internal_pointer_end(&list->free); - key = zend_hash_get_current_key(&list->free, NULL, &index, 0); - rv = zend_hash_get_current_data(&list->free, (void *) &handle_ptr); - if (HASH_KEY_NON_EXISTANT != key && SUCCESS == rv) { - handle = *handle_ptr; - if (a->wakeup) { - a->wakeup(a, &handle TSRMLS_CC); - } - zend_hash_index_del(&list->free, index); - } else { - handle = php_resource_factory_handle_ctor(&a->provider->rf, - init_arg TSRMLS_CC); - } -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "CREATED: %p\n", *handle); -#endif - if (handle) { - ++a->provider->list.used; - ++list->used; - } - } - - return handle; -} - -void *php_persistent_handle_accrete( - php_persistent_handle_factory_t *a, void *handle TSRMLS_DC) -{ - void *new_handle = NULL; - php_persistent_handle_list_t *list; - - new_handle = php_resource_factory_handle_copy(&a->provider->rf, - handle TSRMLS_CC); - if (handle) { - list = php_persistent_handle_list_find(a->provider, a->ident.str, - a->ident.len TSRMLS_CC); - if (list) { - ++list->used; - } - ++a->provider->list.used; - } - - return new_handle; -} - -void php_persistent_handle_release( - php_persistent_handle_factory_t *a, void *handle TSRMLS_DC) -{ - php_persistent_handle_list_t *list; - - list = php_persistent_handle_list_find(a->provider, a->ident.str, - a->ident.len TSRMLS_CC); - if (list) { - if (a->provider->list.used >= PHP_RAPHF_G->persistent_handle.limit) { -#if PHP_RAPHF_DEBUG_PHANDLES - fprintf(stderr, "DESTROY: %p\n", *handle); -#endif - php_resource_factory_handle_dtor(&a->provider->rf, - handle TSRMLS_CC); - } else { - if (a->retire) { - a->retire(a, &handle TSRMLS_CC); - } - zend_hash_next_index_insert(&list->free, (void *) &handle, - sizeof(void *), NULL); - } - - --a->provider->list.used; - --list->used; - } -} - -void php_persistent_handle_cleanup(const char *name_str, size_t name_len, - const char *ident_str, size_t ident_len TSRMLS_DC) -{ - php_persistent_handle_provider_t *provider; - php_persistent_handle_list_t *list; - ZEND_RESULT_CODE rv; - - if (name_str && name_len) { - rv = zend_symtable_find(&PHP_RAPHF_G->persistent_handle.hash, name_str, - name_len+1, (void *) &provider); - - if (SUCCESS == rv) { - if (ident_str && ident_len) { - list = php_persistent_handle_list_find(provider, ident_str, - ident_len TSRMLS_CC); - if (list) { - zend_hash_apply_with_argument(&list->free, - php_persistent_handle_apply_cleanup_ex, - &provider->rf TSRMLS_CC); - } - } else { - zend_hash_apply_with_argument(&provider->list.free, - php_persistent_handle_apply_cleanup, - &provider->rf TSRMLS_CC); - } - } - } else { - zend_hash_apply_with_arguments( - &PHP_RAPHF_G->persistent_handle.hash TSRMLS_CC, - php_persistent_handle_apply_cleanup_all, 2, ident_str, - ident_len); - } -} - -HashTable *php_persistent_handle_statall(HashTable *ht TSRMLS_DC) -{ - if (zend_hash_num_elements(&PHP_RAPHF_G->persistent_handle.hash)) { - if (!ht) { - ALLOC_HASHTABLE(ht); - zend_hash_init(ht, 0, NULL, ZVAL_PTR_DTOR, 0); - } - zend_hash_apply_with_arguments( - &PHP_RAPHF_G->persistent_handle.hash TSRMLS_CC, - php_persistent_handle_apply_statall, 1, ht); - } else if (ht) { - ht = NULL; - } - - return ht; -} - -static php_resource_factory_ops_t php_persistent_handle_resource_factory_ops = { - (php_resource_factory_handle_ctor_t) php_persistent_handle_acquire, - (php_resource_factory_handle_copy_t) php_persistent_handle_accrete, - (php_resource_factory_handle_dtor_t) php_persistent_handle_release -}; - -php_resource_factory_ops_t *php_persistent_handle_get_resource_factory_ops(void) -{ - return &php_persistent_handle_resource_factory_ops; -} - -ZEND_BEGIN_ARG_INFO_EX(ai_raphf_stat_persistent_handles, 0, 0, 0) -ZEND_END_ARG_INFO(); -static PHP_FUNCTION(raphf_stat_persistent_handles) -{ - if (SUCCESS == zend_parse_parameters_none()) { - object_init(return_value); - if (php_persistent_handle_statall(HASH_OF(return_value) TSRMLS_CC)) { - return; - } - zval_dtor(return_value); - } - RETURN_FALSE; -} - -ZEND_BEGIN_ARG_INFO_EX(ai_raphf_clean_persistent_handles, 0, 0, 0) - ZEND_ARG_INFO(0, name) - ZEND_ARG_INFO(0, ident) -ZEND_END_ARG_INFO(); -static PHP_FUNCTION(raphf_clean_persistent_handles) -{ - char *name_str = NULL, *ident_str = NULL; - int name_len = 0, ident_len = 0; - - if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!", - &name_str, &name_len, &ident_str, &ident_len)) { - php_persistent_handle_cleanup(name_str, name_len, ident_str, - ident_len TSRMLS_CC); - } -} - -static const zend_function_entry raphf_functions[] = { - ZEND_NS_FENTRY("raphf", stat_persistent_handles, - ZEND_FN(raphf_stat_persistent_handles), - ai_raphf_stat_persistent_handles, 0) - ZEND_NS_FENTRY("raphf", clean_persistent_handles, - ZEND_FN(raphf_clean_persistent_handles), - ai_raphf_clean_persistent_handles, 0) - {0} -}; - -PHP_INI_BEGIN() - STD_PHP_INI_ENTRY("raphf.persistent_handle.limit", "-1", PHP_INI_SYSTEM, - OnUpdateLong, persistent_handle.limit, zend_raphf_globals, - raphf_globals) -PHP_INI_END() - -static HashTable *php_persistent_handles_global_hash; - -static PHP_GINIT_FUNCTION(raphf) -{ - raphf_globals->persistent_handle.limit = -1; - - zend_hash_init(&raphf_globals->persistent_handle.hash, 0, NULL, - php_persistent_handle_hash_dtor, 1); - if (php_persistent_handles_global_hash) { - zend_hash_copy(&raphf_globals->persistent_handle.hash, - php_persistent_handles_global_hash, NULL, NULL, - sizeof(php_persistent_handle_provider_t)); - } -} - -static PHP_GSHUTDOWN_FUNCTION(raphf) -{ - zend_hash_destroy(&raphf_globals->persistent_handle.hash); -} - -PHP_MINIT_FUNCTION(raphf) -{ - php_persistent_handles_global_hash = &PHP_RAPHF_G->persistent_handle.hash; - REGISTER_INI_ENTRIES(); - return SUCCESS; -} - -PHP_MSHUTDOWN_FUNCTION(raphf) -{ - UNREGISTER_INI_ENTRIES(); - php_persistent_handles_global_hash = NULL; - return SUCCESS; -} - -static int php_persistent_handle_apply_info_ex(void *p TSRMLS_DC, int argc, - va_list argv, zend_hash_key *key) -{ - php_persistent_handle_list_t **list = p; - zend_hash_key *super_key = va_arg(argv, zend_hash_key *); - char used[21], free[21]; - - slprintf(used, sizeof(used), "%u", (*list)->used); - slprintf(free, sizeof(free), "%d", zend_hash_num_elements(&(*list)->free)); - - php_info_print_table_row(4, super_key->arKey, key->arKey, used, free); - - return ZEND_HASH_APPLY_KEEP; -} - -static int php_persistent_handle_apply_info(void *p TSRMLS_DC, int argc, - va_list argv, zend_hash_key *key) -{ - php_persistent_handle_provider_t *provider = p; - - zend_hash_apply_with_arguments(&provider->list.free TSRMLS_CC, - php_persistent_handle_apply_info_ex, 1, key); - - return ZEND_HASH_APPLY_KEEP; -} - -PHP_MINFO_FUNCTION(raphf) -{ - php_info_print_table_start(); - php_info_print_table_header(2, - "Resource and persistent handle factory support", "enabled"); - php_info_print_table_row(2, "Extension version", PHP_RAPHF_VERSION); - php_info_print_table_end(); - - php_info_print_table_start(); - php_info_print_table_colspan_header(4, "Persistent handles in this " -#ifdef ZTS - "thread" -#else - "process" -#endif - ); - php_info_print_table_header(4, "Provider", "Ident", "Used", "Free"); - zend_hash_apply_with_arguments( - &PHP_RAPHF_G->persistent_handle.hash TSRMLS_CC, - php_persistent_handle_apply_info, 0); - php_info_print_table_end(); - - DISPLAY_INI_ENTRIES(); -} - -zend_module_entry raphf_module_entry = { - STANDARD_MODULE_HEADER, - "raphf", - raphf_functions, - PHP_MINIT(raphf), - PHP_MSHUTDOWN(raphf), - NULL, - NULL, - PHP_MINFO(raphf), - PHP_RAPHF_VERSION, - ZEND_MODULE_GLOBALS(raphf), - PHP_GINIT(raphf), - PHP_GSHUTDOWN(raphf), - NULL, - STANDARD_MODULE_PROPERTIES_EX -}; -/* }}} */ - -#ifdef COMPILE_DL_RAPHF -ZEND_GET_MODULE(raphf) -#endif - - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - * vim600: noet sw=4 ts=4 fdm=marker - * vim<600: noet sw=4 ts=4 - */ ---TEST-- -pecl/http-v2 - general and stat ---SKIPIF-- - ---FILE-- -enqueue(new http\Client\Request("GET", "http://php.net")); -} while (count($c) < 3); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - -unset($c); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - -?> -Done ---EXPECTF-- -Test -array(2) { - ["http\Client\Curl"]=> - array(0) { - } - ["http\Client\Curl\Request"]=> - array(0) { - } -} -array(2) { - ["http\Client\Curl"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(1) - ["free"]=> - int(0) - } - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(3) - ["free"]=> - int(0) - } - } -} -array(2) { - ["http\Client\Curl"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(1) - } - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(3) - } - } -} -Done ---TEST-- -pecl/http-v2 - clean with name and id ---SKIPIF-- - ---FILE-- -enqueue(new http\Client\Request("GET", "http://php.net")); -} while (count($c) < 3); - -unset($c); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - - -raphf\clean_persistent_handles("http\\Client\\Curl"); -raphf\clean_persistent_handles("http\\Client\\Curl\\Request", "php.net:80"); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - -?> -Done ---EXPECTF-- -Test -array(2) { - ["http\Client\Curl"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(1) - } - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(3) - } - } -} -array(2) { - ["http\Client\Curl"]=> - array(0) { - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(0) - } - } -} -Done ---TEST-- -pecl/http-v2 - clean with id only ---SKIPIF-- - ---FILE-- -enqueue(new http\Client\Request("GET", "http://php.net")); -} while (count($c) < 3); - -unset($c); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - -raphf\clean_persistent_handles(null, "php.net:80"); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - -?> -Done ---EXPECTF-- -Test -array(2) { - ["http\Client\Curl"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(1) - } - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(3) - } - } -} -array(2) { - ["http\Client\Curl"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(0) - } - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(0) - ["free"]=> - int(0) - } - } -} -Done ---TEST-- -pecl/http-v2 - partial clean ---SKIPIF-- - ---FILE-- -enqueue(new http\Client\Request("GET", "http://php.net")); - $c2->enqueue(new http\Client\Request("GET", "http://php.net")); -} while (count($c) < 3); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - -unset($c); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - -raphf\clean_persistent_handles(); - -$h = (array) raphf\stat_persistent_handles(); -var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); - -?> -Done ---EXPECTF-- -Test -array(2) { - ["http\Client\Curl"]=> - array(0) { - } - ["http\Client\Curl\Request"]=> - array(0) { - } -} -array(2) { - ["http\Client\Curl"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(2) - ["free"]=> - int(0) - } - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(6) - ["free"]=> - int(0) - } - } -} -array(2) { - ["http\Client\Curl"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(1) - ["free"]=> - int(1) - } - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(3) - ["free"]=> - int(3) - } - } -} -array(2) { - ["http\Client\Curl"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(1) - ["free"]=> - int(0) - } - } - ["http\Client\Curl\Request"]=> - array(1) { - ["php.net:80"]=> - array(2) { - ["used"]=> - int(3) - ["free"]=> - int(0) - } - } -} -Done -©œÝÆ¿¢è‰õp¡4ºÈ0¸.|—¯GBMB \ No newline at end of file diff --git a/travis/raphf-master.ext.phar b/travis/raphf-master.ext.phar new file mode 100755 index 0000000..42a263e --- /dev/null +++ b/travis/raphf-master.ext.phar @@ -0,0 +1,7053 @@ +#!/usr/bin/env php +getUser(); + if (!is_dir($temp) && !mkdir($temp, 0700, true)) { + throw new Exception; + } + $this->name = $temp ."/". uniqid($prefix) . $suffix; + } + + private function getUser() { + if (extension_loaded("posix") && function_exists("posix_getpwuid")) { + return posix_getpwuid(posix_getuid())["name"]; + } + return trim(`whoami 2>/dev/null`) + ?: trim(`id -nu 2>/dev/null`) + ?: getenv("USER") + ?: get_current_user(); + } + + /** + * @return string + */ + public function __toString() { + return (string) $this->name; + } +} + + + +namespace pharext; + +/** + * Create a new temporary file + */ +class Tempfile extends \SplFileInfo +{ + /** + * @var resource + */ + private $handle; + + /** + * @param string $prefix uniqid() prefix + * @param string $suffix e.g. file extension + * @throws \pharext\Exception + */ + public function __construct($prefix, $suffix = ".tmp") { + $tries = 0; + $omask = umask(077); + do { + $path = new Tempname($prefix, $suffix); + $this->handle = fopen($path, "x"); + } while (!is_resource($this->handle) && $tries++ < 10); + umask($omask); + + if (!is_resource($this->handle)) { + throw new Exception("Could not create temporary file"); + } + + parent::__construct($path); + } + + /** + * Unlink the file + */ + public function __destruct() { + if (is_file($this->getPathname())) { + @unlink($this->getPathname()); + } + } + + /** + * Close the stream + */ + public function closeStream() { + fclose($this->handle); + } + + /** + * Retrieve the stream resource + * @return resource + */ + public function getStream() { + return $this->handle; + } +} + + + +namespace pharext; + +/** + * Create a temporary directory + */ +class Tempdir extends \SplFileInfo +{ + /** + * @param string $prefix prefix to uniqid() + * @throws \pharext\Exception + */ + public function __construct($prefix) { + $temp = new Tempname($prefix); + if (!is_dir($temp) && !mkdir($temp, 0700, true)) { + throw new Exception("Could not create tempdir: ".error_get_last()["message"]); + } + parent::__construct($temp); + } +} + + + +namespace pharext; + +use ArrayAccess; +use IteratorAggregate; +use RecursiveDirectoryIterator; +use SplFileInfo; + +use pharext\Exception; + +class Archive implements ArrayAccess, IteratorAggregate +{ + const HALT_COMPILER = "\137\137\150\141\154\164\137\143\157\155\160\151\154\145\162\50\51\73"; + const SIGNED = 0x10000; + const SIG_MD5 = 0x0001; + const SIG_SHA1 = 0x0002; + const SIG_SHA256 = 0x0003; + const SIG_SHA512 = 0x0004; + const SIG_OPENSSL= 0x0010; + + private static $siglen = [ + self::SIG_MD5 => 16, + self::SIG_SHA1 => 20, + self::SIG_SHA256 => 32, + self::SIG_SHA512 => 64, + self::SIG_OPENSSL=> 0 + ]; + + private static $sigalg = [ + self::SIG_MD5 => "md5", + self::SIG_SHA1 => "sha1", + self::SIG_SHA256 => "sha256", + self::SIG_SHA512 => "sha512", + self::SIG_OPENSSL=> "openssl" + ]; + + private static $sigtyp = [ + self::SIG_MD5 => "MD5", + self::SIG_SHA1 => "SHA-1", + self::SIG_SHA256 => "SHA-256", + self::SIG_SHA512 => "SHA-512", + self::SIG_OPENSSL=> "OpenSSL", + ]; + + const PERM_FILE_MASK = 0x01ff; + const COMP_FILE_MASK = 0xf000; + const COMP_GZ_FILE = 0x1000; + const COMP_BZ2_FILE = 0x2000; + + const COMP_PHAR_MASK= 0xf000; + const COMP_PHAR_GZ = 0x1000; + const COMP_PHAR_BZ2 = 0x2000; + + private $file; + private $fd; + private $stub; + private $manifest; + private $signature; + private $extracted; + + function __construct($file = null) { + if (strlen($file)) { + $this->open($file); + } + } + + function open($file) { + if (!$this->fd = @fopen($file, "r")) { + throw new Exception; + } + $this->file = $file; + $this->stub = $this->readStub(); + $this->manifest = $this->readManifest(); + $this->signature = $this->readSignature(); + } + + function getIterator() { + return new RecursiveDirectoryIterator($this->extract()); + } + + function extract() { + return $this->extracted ?: $this->extractTo(new Tempdir("archive")); + } + + function extractTo($dir) { + if ((string) $this->extracted == (string) $dir) { + return $this->extracted; + } + foreach ($this->manifest["entries"] as $file => $entry) { + fseek($this->fd, $this->manifest["offset"]+$entry["offset"]); + $path = "$dir/$file"; + $copy = stream_copy_to_stream($this->fd, $this->outFd($path, $entry["flags"]), $entry["csize"]); + if ($entry["osize"] != $copy) { + throw new Exception("Copied '$copy' of '$file', expected '{$entry["osize"]}' from '{$entry["csize"]}"); + } + + $crc = hexdec(hash_file("crc32b", $path)); + if ($crc !== $entry["crc32"]) { + throw new Exception("CRC mismatch of '$file': '$crc' != '{$entry["crc32"]}"); + } + + chmod($path, $entry["flags"] & self::PERM_FILE_MASK); + touch($path, $entry["stamp"]); + } + return $this->extracted = $dir; + } + + function offsetExists($o) { + return isset($this->entries[$o]); + } + + function offsetGet($o) { + $this->extract(); + return new SplFileInfo($this->extracted."/$o"); + } + + function offsetSet($o, $v) { + throw new Exception("Archive is read-only"); + } + + function offsetUnset($o) { + throw new Exception("Archive is read-only"); + } + + function getSignature() { + /* compatible with Phar::getSignature() */ + return [ + "hash_type" => self::$sigtyp[$this->signature["flags"]], + "hash" => strtoupper(bin2hex($this->signature["hash"])), + ]; + } + + function getPath() { + /* compatible with Phar::getPath() */ + return new SplFileInfo($this->file); + } + + function getMetadata($key = null) { + if (isset($key)) { + return $this->manifest["meta"][$key]; + } + return $this->manifest["meta"]; + } + + private function outFd($path, $flags) { + $dirn = dirname($path); + if (!is_dir($dirn) && !@mkdir($dirn, 0777, true)) { + throw new Exception; + } + if (!$fd = @fopen($path, "w")) { + throw new Exception; + } + switch ($flags & self::COMP_FILE_MASK) { + case self::COMP_GZ_FILE: + if (!@stream_filter_append($fd, "zlib.inflate")) { + throw new Exception; + } + break; + case self::COMP_BZ2_FILE: + if (!@stream_filter_append($fd, "bz2.decompress")) { + throw new Exception; + } + break; + } + + } + private function readVerified($fd, $len) { + if ($len != strlen($data = fread($fd, $len))) { + throw new Exception("Unexpected EOF"); + } + return $data; + } + + private function readFormat($format, $fd, $len) { + if (false === ($data = @unpack($format, $this->readVerified($fd, $len)))) { + throw new Exception; + } + return $data; + } + + private function readSingleFormat($format, $fd, $len) { + return current($this->readFormat($format, $fd, $len)); + } + + private function readStringBinary($fd) { + if (($length = $this->readSingleFormat("V", $fd, 4))) { + return $this->readVerified($this->fd, $length); + } + return null; + } + + private function readSerializedBinary($fd) { + if (($length = $this->readSingleFormat("V", $fd, 4))) { + if (false === ($data = unserialize($this->readVerified($fd, $length)))) { + throw new Exception; + } + return $data; + } + return null; + } + + private function readStub() { + $stub = ""; + while (!feof($this->fd)) { + $line = fgets($this->fd); + $stub .= $line; + if (false !== stripos($line, self::HALT_COMPILER)) { + /* check for '?>' on a separate line */ + if ('?>' === $this->readVerified($this->fd, 2)) { + $stub .= '?>' . fgets($this->fd); + } else { + fseek($this->fd, -2, SEEK_CUR); + } + break; + } + } + return $stub; + } + + private function readManifest() { + $current = ftell($this->fd); + $header = $this->readFormat("Vlen/Vnum/napi/Vflags", $this->fd, 14); + $alias = $this->readStringBinary($this->fd); + $meta = $this->readSerializedBinary($this->fd); + $entries = []; + for ($i = 0; $i < $header["num"]; ++$i) { + $this->readEntry($entries); + } + $offset = ftell($this->fd); + if (($length = $offset - $current - 4) != $header["len"]) { + throw new Exception("Manifest length read was '$length', expected '{$header["len"]}'"); + } + return $header + compact("alias", "meta", "entries", "offset"); + } + + private function readEntry(array &$entries) { + if (!count($entries)) { + $offset = 0; + } else { + $last = end($entries); + $offset = $last["offset"] + $last["csize"]; + } + $file = $this->readStringBinary($this->fd); + if (!strlen($file)) { + throw new Exception("Empty file name encountered at offset '$offset'"); + } + $header = $this->readFormat("Vosize/Vstamp/Vcsize/Vcrc32/Vflags", $this->fd, 20); + $meta = $this->readSerializedBinary($this->fd); + $entries[$file] = $header + compact("meta", "offset"); + } + + private function readSignature() { + fseek($this->fd, -8, SEEK_END); + $sig = $this->readFormat("Vflags/Z4magic", $this->fd, 8); + $end = ftell($this->fd); + + if ($sig["magic"] !== "GBMB") { + throw new Exception("Invalid signature magic value '{$sig["magic"]}"); + } + + switch ($sig["flags"]) { + case self::SIG_OPENSSL: + fseek($this->fd, -12, SEEK_END); + if (($hash = $this->readSingleFormat("V", $this->fd, 4))) { + $offset = 4 + $hash; + fseek($this->fd, -$offset, SEEK_CUR); + $hash = $this->readVerified($this->fd, $hash); + fseek($this->fd, 0, SEEK_SET); + $valid = openssl_verify($this->readVerified($this->fd, $end - $offset - 8), + $hash, @file_get_contents($this->file.".pubkey")) === 1; + } + break; + + case self::SIG_MD5: + case self::SIG_SHA1: + case self::SIG_SHA256: + case self::SIG_SHA512: + $offset = 8 + self::$siglen[$sig["flags"]]; + fseek($this->fd, -$offset, SEEK_END); + $hash = $this->readVerified($this->fd, self::$siglen[$sig["flags"]]); + $algo = hash_init(self::$sigalg[$sig["flags"]]); + fseek($this->fd, 0, SEEK_SET); + hash_update_stream($algo, $this->fd, $end - $offset); + $valid = hash_final($algo, true) === $hash; + break; + + default: + throw new Exception("Invalid signature type '{$sig["flags"]}"); + } + + return $sig + compact("hash", "valid"); + } +} + + +namespace pharext; + +if (extension_loaded("Phar")) { + \Phar::interceptFileFuncs(); + \Phar::mapPhar(); + $phardir = "phar://".__FILE__; +} else { + $archive = new Archive(__FILE__); + $phardir = $archive->extract(); +} + +set_include_path("$phardir:". get_include_path()); + +$installer = new Installer(); +$installer->run($argc, $argv); + +__HALT_COMPILER(); ?> +DH)a:7:{s:7:"version";s:5:"4.1.1";s:6:"header";s:49:"pharext v4.1.1 (c) Michael Wallner ";s:4:"date";s:10:"2015-12-03";s:4:"name";s:5:"raphf";s:7:"release";s:6:"master";s:7:"license";s:1345:"Copyright (c) 2013, Michael Wallner . +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +";s:4:"type";s:9:"extension";}pharext/Archive.phpx9`V4-ÔI¶pharext/Cli/Args/Help.phpÉ x9`VÉ gX'¶pharext/Cli/Args.phpx9`V?nö¶pharext/Cli/Command.phpk x9`Vk d„aê¶pharext/Command.phpx9`VÔm`Ͷpharext/Exception.phpcx9`VcU†Ï{¶pharext/ExecCmd.phpx9`V¹l”ʶpharext/Installer.php&x9`V&ød&À¶pharext/License.php“x9`V“îòE¶pharext/Metadata.php•x9`V•¿Úž¶pharext/Openssl/PrivateKey.phpÁx9`VÁ&æP¶pharext/Packager.phpÌ!x9`VÌ!0<¶pharext/SourceDir/Basic.phpzx9`Vz÷+Ôâ¶pharext/SourceDir/Git.phpZx9`VZÉÎ\¶pharext/SourceDir/Pecl.phpøx9`Vøãùжpharext/SourceDir.php½x9`V½3·#¶pharext/Task/Activate.phpÜ x9`VÜ I“¶pharext/Task/Askpass.phpUx9`VU‡*¶ pharext/Task/BundleGenerator.php}x9`V} ï`Y¶pharext/Task/Cleanup.phpx9`VÉI€B¶pharext/Task/Configure.phpTx9`VT}Ëì¶pharext/Task/Extract.phppx9`Vp[¨Û̶pharext/Task/GitClone.phpmx9`Vmóyµ@¶pharext/Task/Make.phpªx9`Vªœç6 ¶pharext/Task/PaxFixup.php¬x9`V¬y⯶pharext/Task/PeclFixup.phpœx9`Vœeùtš¶pharext/Task/PharBuild.phpâx9`Vâζ0ɶpharext/Task/PharCompress.phpcx9`Vc½³Ï¶pharext/Task/PharRename.phpäx9`VäŠ[Þ˶pharext/Task/PharSign.php¨x9`V¨Ûº¦i¶pharext/Task/PharStub.phpæx9`VæY|­›¶pharext/Task/Phpize.phpx9`Vù 2Ѷpharext/Task/StreamFetch.phpx9`Vˆîs\¶pharext/Task.phpwx9`Vw ÄIǶpharext/Tempdir.phpµx9`Vµë–,¶pharext/Tempfile.phpx9`V®ô¶pharext/Tempname.phptx9`Vtžn<¶pharext/Updater.phpx9`VžÏv¶pharext_installer.phpÝx9`VÝŒÞq¶pharext_packager.phpbx9`VbîVÓ϶pharext_updater.phphx9`Vh Êúj¶ .editorconfigLx9`VLލ1¶.gitattributesGx9`VGy–¶ +.gitignorex9`V} +I¶ .gitmodulesnx9`Vn¥ÉN‚¶ .travis.ymlõx9`Võ(@©D¶AUTHORSx9`V\ÄH­¶BUGS*x9`V*<î¶CONTRIBUTING.mdŽx9`VŽ¶Nq¶CREDITSx9`VCµ]²¶DoxyfileÓ,x9`VÓ,Mc¾Ü¶LICENSEAx9`VA¾¬Jþ¶ Makefile.frag¾x9`V¾ݯõ¯¶ README.mdx9`V™ËÜ?¶THANKSdx9`VdÌD"å¶TODOx9`Vy_÷E¶ config.m4x9`Voêd”¶ +config.w32òx9`VòL÷fO¶ +config0.m4åx9`VåÇ×Îb¶ package.xml. x9`V. Z-Áü¶ php_raphf.hx9`Vµ˜:Ž¶php_raphf_test.cÍx9`VÍ·f>x¶ raphf.png|px9`V|ps䙳¶scripts/gen_travis_yml.phpãx9`VãîÌÙö¶src/php_raphf_api.cEx9`VE™P¶src/php_raphf_api.hf2x9`Vf2ÓI}ž¶tests/http001.phptx9`V *®¶tests/http002.phptLx9`VL€ÔïS¶tests/http003.phpt^x9`V^ˆp¶tests/http004.phpt[x9`V[Y諶tests/test.phpt¾ +x9`V¾ +$àíY¶ travis/peclx9`V¶ 16, + self::SIG_SHA1 => 20, + self::SIG_SHA256 => 32, + self::SIG_SHA512 => 64, + self::SIG_OPENSSL=> 0 + ]; + + private static $sigalg = [ + self::SIG_MD5 => "md5", + self::SIG_SHA1 => "sha1", + self::SIG_SHA256 => "sha256", + self::SIG_SHA512 => "sha512", + self::SIG_OPENSSL=> "openssl" + ]; + + private static $sigtyp = [ + self::SIG_MD5 => "MD5", + self::SIG_SHA1 => "SHA-1", + self::SIG_SHA256 => "SHA-256", + self::SIG_SHA512 => "SHA-512", + self::SIG_OPENSSL=> "OpenSSL", + ]; + + const PERM_FILE_MASK = 0x01ff; + const COMP_FILE_MASK = 0xf000; + const COMP_GZ_FILE = 0x1000; + const COMP_BZ2_FILE = 0x2000; + + const COMP_PHAR_MASK= 0xf000; + const COMP_PHAR_GZ = 0x1000; + const COMP_PHAR_BZ2 = 0x2000; + + private $file; + private $fd; + private $stub; + private $manifest; + private $signature; + private $extracted; + + function __construct($file = null) { + if (strlen($file)) { + $this->open($file); + } + } + + function open($file) { + if (!$this->fd = @fopen($file, "r")) { + throw new Exception; + } + $this->file = $file; + $this->stub = $this->readStub(); + $this->manifest = $this->readManifest(); + $this->signature = $this->readSignature(); + } + + function getIterator() { + return new RecursiveDirectoryIterator($this->extract()); + } + + function extract() { + return $this->extracted ?: $this->extractTo(new Tempdir("archive")); + } + + function extractTo($dir) { + if ((string) $this->extracted == (string) $dir) { + return $this->extracted; + } + foreach ($this->manifest["entries"] as $file => $entry) { + fseek($this->fd, $this->manifest["offset"]+$entry["offset"]); + $path = "$dir/$file"; + $copy = stream_copy_to_stream($this->fd, $this->outFd($path, $entry["flags"]), $entry["csize"]); + if ($entry["osize"] != $copy) { + throw new Exception("Copied '$copy' of '$file', expected '{$entry["osize"]}' from '{$entry["csize"]}"); + } + + $crc = hexdec(hash_file("crc32b", $path)); + if ($crc !== $entry["crc32"]) { + throw new Exception("CRC mismatch of '$file': '$crc' != '{$entry["crc32"]}"); + } + + chmod($path, $entry["flags"] & self::PERM_FILE_MASK); + touch($path, $entry["stamp"]); + } + return $this->extracted = $dir; + } + + function offsetExists($o) { + return isset($this->entries[$o]); + } + + function offsetGet($o) { + $this->extract(); + return new SplFileInfo($this->extracted."/$o"); + } + + function offsetSet($o, $v) { + throw new Exception("Archive is read-only"); + } + + function offsetUnset($o) { + throw new Exception("Archive is read-only"); + } + + function getSignature() { + /* compatible with Phar::getSignature() */ + return [ + "hash_type" => self::$sigtyp[$this->signature["flags"]], + "hash" => strtoupper(bin2hex($this->signature["hash"])), + ]; + } + + function getPath() { + /* compatible with Phar::getPath() */ + return new SplFileInfo($this->file); + } + + function getMetadata($key = null) { + if (isset($key)) { + return $this->manifest["meta"][$key]; + } + return $this->manifest["meta"]; + } + + private function outFd($path, $flags) { + $dirn = dirname($path); + if (!is_dir($dirn) && !@mkdir($dirn, 0777, true)) { + throw new Exception; + } + if (!$fd = @fopen($path, "w")) { + throw new Exception; + } + switch ($flags & self::COMP_FILE_MASK) { + case self::COMP_GZ_FILE: + if (!@stream_filter_append($fd, "zlib.inflate")) { + throw new Exception; + } + break; + case self::COMP_BZ2_FILE: + if (!@stream_filter_append($fd, "bz2.decompress")) { + throw new Exception; + } + break; + } + + } + private function readVerified($fd, $len) { + if ($len != strlen($data = fread($fd, $len))) { + throw new Exception("Unexpected EOF"); + } + return $data; + } + + private function readFormat($format, $fd, $len) { + if (false === ($data = @unpack($format, $this->readVerified($fd, $len)))) { + throw new Exception; + } + return $data; + } + + private function readSingleFormat($format, $fd, $len) { + return current($this->readFormat($format, $fd, $len)); + } + + private function readStringBinary($fd) { + if (($length = $this->readSingleFormat("V", $fd, 4))) { + return $this->readVerified($this->fd, $length); + } + return null; + } + + private function readSerializedBinary($fd) { + if (($length = $this->readSingleFormat("V", $fd, 4))) { + if (false === ($data = unserialize($this->readVerified($fd, $length)))) { + throw new Exception; + } + return $data; + } + return null; + } + + private function readStub() { + $stub = ""; + while (!feof($this->fd)) { + $line = fgets($this->fd); + $stub .= $line; + if (false !== stripos($line, self::HALT_COMPILER)) { + /* check for '?>' on a separate line */ + if ('?>' === $this->readVerified($this->fd, 2)) { + $stub .= '?>' . fgets($this->fd); + } else { + fseek($this->fd, -2, SEEK_CUR); + } + break; + } + } + return $stub; + } + + private function readManifest() { + $current = ftell($this->fd); + $header = $this->readFormat("Vlen/Vnum/napi/Vflags", $this->fd, 14); + $alias = $this->readStringBinary($this->fd); + $meta = $this->readSerializedBinary($this->fd); + $entries = []; + for ($i = 0; $i < $header["num"]; ++$i) { + $this->readEntry($entries); + } + $offset = ftell($this->fd); + if (($length = $offset - $current - 4) != $header["len"]) { + throw new Exception("Manifest length read was '$length', expected '{$header["len"]}'"); + } + return $header + compact("alias", "meta", "entries", "offset"); + } + + private function readEntry(array &$entries) { + if (!count($entries)) { + $offset = 0; + } else { + $last = end($entries); + $offset = $last["offset"] + $last["csize"]; + } + $file = $this->readStringBinary($this->fd); + if (!strlen($file)) { + throw new Exception("Empty file name encountered at offset '$offset'"); + } + $header = $this->readFormat("Vosize/Vstamp/Vcsize/Vcrc32/Vflags", $this->fd, 20); + $meta = $this->readSerializedBinary($this->fd); + $entries[$file] = $header + compact("meta", "offset"); + } + + private function readSignature() { + fseek($this->fd, -8, SEEK_END); + $sig = $this->readFormat("Vflags/Z4magic", $this->fd, 8); + $end = ftell($this->fd); + + if ($sig["magic"] !== "GBMB") { + throw new Exception("Invalid signature magic value '{$sig["magic"]}"); + } + + switch ($sig["flags"]) { + case self::SIG_OPENSSL: + fseek($this->fd, -12, SEEK_END); + if (($hash = $this->readSingleFormat("V", $this->fd, 4))) { + $offset = 4 + $hash; + fseek($this->fd, -$offset, SEEK_CUR); + $hash = $this->readVerified($this->fd, $hash); + fseek($this->fd, 0, SEEK_SET); + $valid = openssl_verify($this->readVerified($this->fd, $end - $offset - 8), + $hash, @file_get_contents($this->file.".pubkey")) === 1; + } + break; + + case self::SIG_MD5: + case self::SIG_SHA1: + case self::SIG_SHA256: + case self::SIG_SHA512: + $offset = 8 + self::$siglen[$sig["flags"]]; + fseek($this->fd, -$offset, SEEK_END); + $hash = $this->readVerified($this->fd, self::$siglen[$sig["flags"]]); + $algo = hash_init(self::$sigalg[$sig["flags"]]); + fseek($this->fd, 0, SEEK_SET); + hash_update_stream($algo, $this->fd, $end - $offset); + $valid = hash_final($algo, true) === $hash; + break; + + default: + throw new Exception("Invalid signature type '{$sig["flags"]}"); + } + + return $sig + compact("hash", "valid"); + } +} +prog = $prog; + $this->args = $args; + } + + function __toString() { + $usage = "Usage:\n\n \$ "; + $usage .= $this->prog; + + list($flags, $required, $optional, $positional) = $this->listSpec(); + if ($flags) { + $usage .= $this->dumpFlags($flags); + } + if ($required) { + $usage .= $this->dumpRequired($required); + } + if ($optional) { + $usage .= $this->dumpOptional($optional); + } + if ($positional) { + $usage .= $this->dumpPositional($positional); + } + + $help = $this->dumpHelp($positional); + + return $usage . "\n\n" . $help . "\n"; + } + + function listSpec() { + $flags = []; + $required = []; + $optional = []; + $positional = []; + foreach ($this->args->getSpec() as $spec) { + if (is_numeric($spec[0])) { + $positional[] = $spec; + } elseif ($spec[3] & Args::REQUIRED) { + $required[] = $spec; + } elseif ($spec[3] & (Args::OPTARG|Args::REQARG)) { + $optional[] = $spec; + } else { + $flags[] = $spec; + } + } + + return [$flags, $required, $optional, $positional] + + compact("flags", "required", "optional", "positional"); + } + + function dumpFlags(array $flags) { + return sprintf(" [-%s]", implode("", array_column($flags, 0))); + } + + function dumpRequired(array $required) { + $dump = ""; + foreach ($required as $req) { + $dump .= sprintf(" -%s <%s>", $req[0], $req[1]); + } + return $dump; + } + + function dumpOptional(array $optional) { + $req = array_filter($optional, function($a) { + return $a[3] & Args::REQARG; + }); + $opt = array_filter($optional, function($a) { + return $a[3] & Args::OPTARG; + }); + + $dump = ""; + if ($req) { + $dump .= sprintf(" [-%s ]", implode("|-", array_column($req, 0))); + } + if ($opt) { + $dump .= sprintf(" [-%s []]", implode("|-", array_column($opt, 0))); + } + return $dump; + } + + function dumpPositional(array $positional) { + $dump = " [--]"; + foreach ($positional as $pos) { + if ($pos[3] & Args::REQUIRED) { + $dump .= sprintf(" <%s>", $pos[1]); + } else { + $dump .= sprintf(" [<%s>]", $pos[1]); + } + if ($pos[3] & Args::MULTI) { + $dump .= sprintf(" [<%s>]...", $pos[1]); + } + } + return $dump; + } + + function calcMaxLen() { + $spc = $this->args->getSpec(); + $max = max(array_map("strlen", array_column($spc, 1))); + $max += $max % 8 + 2; + return $max; + } + + function dumpHelp() { + $max = $this->calcMaxLen(); + $dump = ""; + foreach ($this->args->getSpec() as $spec) { + $dump .= " "; + if (is_numeric($spec[0])) { + $dump .= sprintf("-- %s ", $spec[1]); + } elseif (isset($spec[0])) { + $dump .= sprintf("-%s|", $spec[0]); + } + if (!is_numeric($spec[0])) { + $dump .= sprintf("--%s ", $spec[1]); + } + if ($spec[3] & Args::REQARG) { + $dump .= " "; + } elseif ($spec[3] & Args::OPTARG) { + $dump .= "[]"; + } else { + $dump .= " "; + } + + $dump .= str_repeat(" ", $max-strlen($spec[1])+3*!isset($spec[0])); + $dump .= $spec[2]; + + if ($spec[3] & Args::REQUIRED) { + $dump .= " (REQUIRED)"; + } + if ($spec[3] & Args::MULTI) { + $dump .= " (MULTIPLE)"; + } + if (isset($spec[4])) { + $dump .= sprintf(" [%s]", $spec[4]); + } + $dump .= "\n"; + } + return $dump; + } +} +compile($spec); + } + + } + + /** + * Compile the original spec + * @param array|Traversable $spec + * @return pharext\Cli\Args self + */ + public function compile($spec) { + foreach ($spec as $arg) { + if (isset($arg[0]) && is_numeric($arg[0])) { + $arg[3] &= ~0xf00; + $this->spec["--".$arg[0]] = $arg; + } elseif (isset($arg[0])) { + $this->spec["-".$arg[0]] = $arg; + $this->spec["--".$arg[1]] = $arg; + } else { + $this->spec["--".$arg[1]] = $arg; + } + $this->orig[] = $arg; + } + return $this; + } + + /** + * Get original spec + * @return array + */ + public function getSpec() { + return $this->orig; + } + + /** + * Get compiled spec + * @return array + */ + public function getCompiledSpec() { + return $this->spec; + } + + /** + * Parse command line arguments according to the compiled spec. + * + * The Generator yields any parsing errors. + * Parsing will stop when all arguments are processed or the first option + * flagged Cli\Args::HALT was encountered. + * + * @param int $argc + * @param array $argv + * @return Generator + */ + public function parse($argc, array $argv) { + for ($f = false, $p = 0, $i = 0; $i < $argc; ++$i) { + $o = $argv[$i]; + + if ($o{0} === "-" && strlen($o) > 2 && $o{1} !== "-") { + // multiple short opts, e.g. -vps + $argc += strlen($o) - 2; + array_splice($argv, $i, 1, array_map(function($s) { + return "-$s"; + }, str_split(substr($o, 1)))); + $o = $argv[$i]; + } elseif ($o{0} === "-" && strlen($o) > 2 && $o{1} === "-" && 0 < ($eq = strpos($o, "="))) { + // long opt with argument, e.g. --foo=bar + $argc++; + array_splice($argv, $i, 1, [ + substr($o, 0, $eq++), + substr($o, $eq) + ]); + $o = $argv[$i]; + } elseif ($o === "--") { + // only positional args following + $f = true; + continue; + } + + if ($f || !isset($this->spec[$o])) { + if ($o{0} !== "-" && isset($this->spec["--$p"])) { + $this[$p] = $o; + if (!$this->optIsMulti($p)) { + ++$p; + } + } else { + yield sprintf("Unknown option %s", $o); + } + } elseif (!$this->optAcceptsArg($o)) { + $this[$o] = true; + } elseif ($i+1 < $argc && !isset($this->spec[$argv[$i+1]])) { + $this[$o] = $argv[++$i]; + } elseif ($this->optRequiresArg($o)) { + yield sprintf("Option --%s requires an argument", $this->optLongName($o)); + } else { + // OPTARG + $this[$o] = $this->optDefaultArg($o); + } + + if ($this->optHalts($o)) { + return; + } + } + } + + /** + * Validate that all required options were given. + * + * The Generator yields any validation errors. + * + * @return Generator + */ + public function validate() { + $required = array_filter($this->orig, function($spec) { + return $spec[3] & self::REQUIRED; + }); + foreach ($required as $req) { + if ($req[3] & self::MULTI) { + if (is_array($this[$req[0]])) { + continue; + } + } elseif (strlen($this[$req[0]])) { + continue; + } + if (is_numeric($req[0])) { + yield sprintf("Argument <%s> is required", $req[1]); + } else { + yield sprintf("Option --%s is required", $req[1]); + } + } + } + + + public function toArray() { + $args = []; + foreach ($this->spec as $spec) { + $opt = $this->opt($spec[1]); + $args[$opt] = $this[$opt]; + } + return $args; + } + + /** + * Retreive the default argument of an option + * @param string $o + * @return mixed + */ + private function optDefaultArg($o) { + $o = $this->opt($o); + if (isset($this->spec[$o][4])) { + return $this->spec[$o][4]; + } + return null; + } + + /** + * Retrieve the help message of an option + * @param string $o + * @return string + */ + private function optHelp($o) { + $o = $this->opt($o); + if (isset($this->spec[$o][2])) { + return $this->spec[$o][2]; + } + return ""; + } + + /** + * Retrieve option's flags + * @param string $o + * @return int + */ + private function optFlags($o) { + $o = $this->opt($o); + if (isset($this->spec[$o])) { + return $this->spec[$o][3]; + } + return null; + } + + /** + * Check whether an option is flagged for halting argument processing + * @param string $o + * @return boolean + */ + private function optHalts($o) { + return $this->optFlags($o) & self::HALT; + } + + /** + * Check whether an option needs an argument + * @param string $o + * @return boolean + */ + private function optRequiresArg($o) { + return $this->optFlags($o) & self::REQARG; + } + + /** + * Check wether an option accepts any argument + * @param string $o + * @return boolean + */ + private function optAcceptsArg($o) { + return $this->optFlags($o) & 0xf00; + } + + /** + * Check whether an option can be used more than once + * @param string $o + * @return boolean + */ + private function optIsMulti($o) { + return $this->optFlags($o) & self::MULTI; + } + + /** + * Retreive the long name of an option + * @param string $o + * @return string + */ + private function optLongName($o) { + $o = $this->opt($o); + return is_numeric($this->spec[$o][0]) ? $this->spec[$o][0] : $this->spec[$o][1]; + } + + /** + * Retreive the short name of an option + * @param string $o + * @return string + */ + private function optShortName($o) { + $o = $this->opt($o); + return is_numeric($this->spec[$o][0]) ? null : $this->spec[$o][0]; + } + + /** + * Retreive the canonical name (--long-name) of an option + * @param string $o + * @return string + */ + private function opt($o) { + if (is_numeric($o)) { + return "--$o"; + } + if ($o{0} !== '-') { + if (strlen($o) > 1) { + $o = "-$o"; + } + $o = "-$o"; + } + return $o; + } + + /**@+ + * Implements ArrayAccess and virtual properties + */ + function offsetExists($o) { + $o = $this->opt($o); + return isset($this->args[$o]); + } + function __isset($o) { + return $this->offsetExists($o); + } + function offsetGet($o) { + $o = $this->opt($o); + if (isset($this->args[$o])) { + return $this->args[$o]; + } + return $this->optDefaultArg($o); + } + function __get($o) { + return $this->offsetGet($o); + } + function offsetSet($o, $v) { + $osn = $this->optShortName($o); + $oln = $this->optLongName($o); + if ($this->optIsMulti($o)) { + if (isset($osn)) { + $this->args["-$osn"][] = $v; + } + $this->args["--$oln"][] = $v; + } else { + if (isset($osn)) { + $this->args["-$osn"] = $v; + } + $this->args["--$oln"] = $v; + } + } + function __set($o, $v) { + $this->offsetSet($o, $v); + } + function offsetUnset($o) { + unset($this->args["-".$this->optShortName($o)]); + unset($this->args["--".$this->optLongName($o)]); + } + function __unset($o) { + $this->offsetUnset($o); + } + /**@-*/ +} +args; + } + + /** + * Retrieve metadata of the currently running phar + * @param string $key + * @return mixed + */ + public function metadata($key = null) { + if (extension_loaded("Phar")) { + $running = new Phar(Phar::running(false)); + } else { + $running = new Archive(PHAREXT_PHAR); + } + + if ($key === "signature") { + $sig = $running->getSignature(); + return sprintf("%s signature of %s\n%s", + $sig["hash_type"], + $this->metadata("name"), + chunk_split($sig["hash"], 64, "\n")); + } + + $metadata = $running->getMetadata(); + if (isset($key)) { + return $metadata[$key]; + } + return $metadata; + } + + /** + * Output pharext vX.Y.Z header + */ + public function header() { + if (!headers_sent()) { + /* only display header, if we didn't generate any output yet */ + printf("%s\n\n", $this->metadata("header")); + } + } + + /** + * @inheritdoc + * @see \pharext\Command::debug() + */ + public function debug($fmt) { + if ($this->args->verbose) { + vprintf($fmt, array_slice(func_get_args(), 1)); + } + } + + /** + * @inheritdoc + * @see \pharext\Command::info() + */ + public function info($fmt) { + if (!$this->args->quiet) { + vprintf($fmt, array_slice(func_get_args(), 1)); + } + } + + /** + * @inheritdoc + * @see \pharext\Command::warn() + */ + public function warn($fmt) { + if (!$this->args->quiet) { + if (!isset($fmt)) { + $fmt = "%s\n"; + $arg = error_get_last()["message"]; + } else { + $arg = array_slice(func_get_args(), 1); + } + vfprintf(STDERR, "Warning: $fmt", $arg); + } + } + + /** + * @inheritdoc + * @see \pharext\Command::error() + */ + public function error($fmt) { + if (!isset($fmt)) { + $fmt = "%s\n"; + $arg = error_get_last()["message"]; + } else { + $arg = array_slice(func_get_args(), 1); + } + vfprintf(STDERR, "ERROR: $fmt", $arg); + } + + /** + * Output command line help message + * @param string $prog + */ + public function help($prog) { + print new Args\Help($prog, $this->args); + } + + /** + * Verbosity + * @return boolean + */ + public function verbosity() { + if ($this->args->verbose) { + return true; + } elseif ($this->args->quiet) { + return false; + } else { + return null; + } + } +} +command = $command; + $this->verbose = $verbose; + } + + /** + * (Re-)set sudo command + * @param string $sudo + */ + public function setSu($sudo = false) { + $this->sudo = $sudo; + } + + /** + * Execute a program with escalated privileges handling interactive password prompt + * @param string $command + * @param bool $verbose + * @return int exit status + */ + private function suExec($command, $verbose = null) { + if (!($proc = proc_open($command, [STDIN,["pipe","w"],["pipe","w"]], $pipes))) { + $this->status = -1; + throw new Exception("Failed to run {$command}"); + } + + $stdout = $pipes[1]; + $passwd = 0; + $checks = 10; + + while (!feof($stdout)) { + $R = [$stdout]; $W = []; $E = []; + if (!stream_select($R, $W, $E, null)) { + continue; + } + $data = fread($stdout, 0x1000); + /* only check a few times */ + if ($passwd < $checks) { + $passwd++; + if (stristr($data, "password")) { + $passwd = $checks + 1; + printf("\n%s", $data); + continue; + } + } elseif ($passwd > $checks) { + /* new line after pw entry */ + printf("\n"); + $passwd = $checks; + } + + if ($verbose === null) { + print $this->progress($data, 0); + } else { + if ($verbose) { + printf("%s", $data); + } + $this->output .= $data; + } + } + if ($verbose === null) { + $this->progress("", PHP_OUTPUT_HANDLER_FINAL); + } + return $this->status = proc_close($proc); + } + + /** + * Output handler that displays some progress while soaking output + * @param string $string + * @param int $flags + * @return string + */ + private function progress($string, $flags) { + static $counter = 0; + static $symbols = ["\\","|","/","-"]; + + $this->output .= $string; + + if (false !== strpos($string, "\n")) { + ++$counter; + } + + return $flags & PHP_OUTPUT_HANDLER_FINAL + ? " \r" + : sprintf(" %s\r", $symbols[$counter % 4]); + } + + /** + * Run the command + * @param array $args + * @return \pharext\ExecCmd self + * @throws \pharext\Exception + */ + public function run(array $args = null) { + $exec = escapeshellcmd($this->command); + if ($args) { + $exec .= " ". implode(" ", array_map("escapeshellarg", (array) $args)); + } + + if ($this->sudo) { + $this->suExec(sprintf($this->sudo." 2>&1", $exec), $this->verbose); + } elseif ($this->verbose) { + ob_start(function($s) { + $this->output .= $s; + return $s; + }, 1); + passthru($exec, $this->status); + ob_end_flush(); + } elseif ($this->verbose !== false /* !quiet */) { + ob_start([$this, "progress"], 1); + passthru($exec . " 2>&1", $this->status); + ob_end_flush(); + } else { + exec($exec ." 2>&1", $output, $this->status); + $this->output = implode("\n", $output); + } + + if ($this->status) { + throw new Exception("Command {$exec} failed ({$this->status})"); + } + + return $this; + } + + /** + * Retrieve exit code of cmd run + * @return int + */ + public function getStatus() { + return $this->status; + } + + /** + * Retrieve output of cmd run + * @return string + */ + public function getOutput() { + return $this->output; + } +} +args = new Cli\Args([ + ["h", "help", "Display help", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + ["v", "verbose", "More output", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["q", "quiet", "Less output", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["p", "prefix", "PHP installation prefix if phpize is not in \$PATH, e.g. /opt/php7", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG], + ["n", "common-name", "PHP common program name, e.g. php5 or zts-php", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG, + "php"], + ["c", "configure", "Additional extension configure flags, e.g. -c --with-flag", + Cli\Args::OPTIONAL|Cli\Args::MULTI|Cli\Args::REQARG], + ["s", "sudo", "Installation might need increased privileges", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::OPTARG, + "sudo -S %s"], + ["i", "ini", "Activate in this php.ini instead of loaded default php.ini", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG], + [null, "signature", "Show package signature", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "license", "Show package license", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "name", "Show package name", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "date", "Show package release date", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "release", "Show package release version", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "version", "Show pharext version", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + ]); + } + + /** + * Perform cleaniup + */ + function __destruct() { + foreach ($this->cleanup as $cleanup) { + $cleanup->run(); + } + } + + private function extract($phar) { + $temp = (new Task\Extract($phar))->run($this->verbosity()); + $this->cleanup[] = new Task\Cleanup($temp); + return $temp; + } + + private function hooks(SplObjectStorage $phars) { + $hook = []; + foreach ($phars as $phar) { + if (isset($phar["pharext_package.php"])) { + $sdir = include $phar["pharext_package.php"]; + if ($sdir instanceof SourceDir) { + $this->args->compile($sdir->getArgs()); + $hook[] = $sdir; + } + } + } + return $hook; + } + + private function load() { + $list = new SplObjectStorage(); + $phar = extension_loaded("Phar") + ? new Phar(Phar::running(false)) + : new Archive(PHAREXT_PHAR); + $temp = $this->extract($phar); + + foreach ($phar as $entry) { + $dep_file = $entry->getBaseName(); + if (fnmatch("*.ext.phar*", $dep_file)) { + $dep_phar = extension_loaded("Phar") + ? new Phar("$temp/$dep_file") + : new Archive("$temp/$dep_file"); + $list[$dep_phar] = $this->extract($dep_phar); + } + } + + /* the actual ext.phar at last */ + $list[$phar] = $temp; + return $list; + } + + /** + * @inheritdoc + * @see \pharext\Command::run() + */ + public function run($argc, array $argv) { + try { + /* load the phar(s) */ + $list = $this->load(); + /* installer hooks */ + $hook = $this->hooks($list); + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::EEXTRACT); + } + + /* standard arg stuff */ + $errs = []; + $prog = array_shift($argv); + foreach ($this->args->parse(--$argc, $argv) as $error) { + $errs[] = $error; + } + + if ($this->args["help"]) { + $this->header(); + $this->help($prog); + exit; + } + try { + foreach (["signature", "name", "date", "license", "release", "version"] as $opt) { + if ($this->args[$opt]) { + printf("%s\n", $this->metadata($opt)); + exit; + } + } + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::EARGS); + } + + foreach ($this->args->validate() as $error) { + $errs[] = $error; + } + + if ($errs) { + if (!$this->args["quiet"]) { + $this->header(); + } + foreach ($errs as $err) { + $this->error("%s\n", $err); + } + if (!$this->args["quiet"]) { + $this->help($prog); + } + exit(self::EARGS); + } + + try { + /* post process hooks */ + foreach ($hook as $sdir) { + $sdir->setArgs($this->args); + } + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::EARGS); + } + + /* install packages */ + try { + foreach ($list as $phar) { + $this->info("Installing %s ...\n", basename($phar->getPath())); + $this->install($list[$phar]); + $this->activate($list[$phar]); + $this->info("Successfully installed %s!\n", basename($phar->getPath())); + } + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::EINSTALL); + } + } + + /** + * Phpize + trinity + */ + private function install($temp) { + // phpize + $phpize = new Task\Phpize($temp, $this->args->prefix, $this->args->{"common-name"}); + $phpize->run($this->verbosity()); + + // configure + $configure = new Task\Configure($temp, $this->args->configure, $this->args->prefix, $this->args->{"common-name"}); + $configure->run($this->verbosity()); + + // make + $make = new Task\Make($temp); + $make->run($this->verbosity()); + + // install + $sudo = isset($this->args->sudo) ? $this->args->sudo : null; + $install = new Task\Make($temp, ["install"], $sudo); + $install->run($this->verbosity()); + } + + private function activate($temp) { + if ($this->args->ini) { + $files = [$this->args->ini]; + } else { + $files = array_filter(array_map("trim", explode(",", php_ini_scanned_files()))); + $files[] = php_ini_loaded_file(); + } + + $sudo = isset($this->args->sudo) ? $this->args->sudo : null; + $type = $this->metadata("type") ?: "extension"; + + $activate = new Task\Activate($temp, $files, $type, $this->args->prefix, $this->args{"common-name"}, $sudo); + if (!$activate->run($this->verbosity())) { + $this->info("Extension already activated ...\n"); + } + } +} +mergeLicensePattern($name, strtolower($name)); + } + $exts = []; + foreach (["t{,e}xt", "rst", "asc{,i,ii}", "m{,ark}d{,own}", "htm{,l}"] as $ext) { + $exts[] = $this->mergeLicensePattern(strtoupper($ext), $ext); + } + + $pattern = "{". implode(",", $names) ."}{,.{". implode(",", $exts) ."}}"; + + if (($glob = glob("$dir/$pattern", GLOB_BRACE))) { + return current($glob); + } + } + + private function mergeLicensePattern($upper, $lower) { + $pattern = ""; + $length = strlen($upper); + for ($i = 0; $i < $length; ++$i) { + if ($lower{$i} === $upper{$i}) { + $pattern .= $upper{$i}; + } else { + $pattern .= "[" . $upper{$i} . $lower{$i} . "]"; + } + } + return $pattern; + } + + public function readLicense($file) { + $text = file_get_contents($file); + switch (strtolower(pathinfo($file, PATHINFO_EXTENSION))) { + case "htm": + case "html": + $text = strip_tags($text); + break; + } + return $text; + } +} +", self::version()); + } + + static function date() { + return gmdate("Y-m-d"); + } + + static function all() { + return [ + "version" => self::version(), + "header" => self::header(), + "date" => self::date(), + ]; + } +} +key); + $this->pub = openssl_pkey_get_details($key)["key"]; + } + + /** + * Sign the PHAR + * @param \Phar $package + */ + function sign(\Phar $package) { + $package->setSignatureAlgorithm(\Phar::OPENSSL, $this->key); + } + + /** + * Export the public key to a file + * @param string $file + * @throws \pharext\Exception + */ + function exportPublicKey($file) { + if (!file_put_contents("$file.tmp", $this->pub) || !rename("$file.tmp", $file)) { + throw new Exception; + } + } +} +args = new Cli\Args([ + ["h", "help", "Display this help", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + ["v", "verbose", "More output", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["q", "quiet", "Less output", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["n", "name", "Extension name", + Cli\Args::REQUIRED|Cli\Args::SINGLE|Cli\Args::REQARG], + ["r", "release", "Extension release version", + Cli\Args::REQUIRED|Cli\Args::SINGLE|Cli\Args::REQARG], + ["s", "source", "Extension source directory", + Cli\Args::REQUIRED|Cli\Args::SINGLE|Cli\Args::REQARG], + ["g", "git", "Use `git ls-tree` to determine file list", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["b", "branch", "Checkout this tag/branch", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG], + ["p", "pecl", "Use PECL package.xml to determine file list, name and release", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["d", "dest", "Destination directory", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG, + "."], + ["z", "gzip", "Create additional PHAR compressed with gzip", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["Z", "bzip", "Create additional PHAR compressed with bzip", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["S", "sign", "Sign the PHAR with a private key", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::REQARG], + ["E", "zend", "Mark as Zend Extension", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + [null, "signature", "Show pharext signature", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "license", "Show pharext license", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "version", "Show pharext version", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + ]); + } + + /** + * Perform cleaniup + */ + function __destruct() { + foreach ($this->cleanup as $cleanup) { + $cleanup->run(); + } + } + + /** + * @inheritdoc + * @see \pharext\Command::run() + */ + public function run($argc, array $argv) { + $errs = []; + $prog = array_shift($argv); + foreach ($this->args->parse(--$argc, $argv) as $error) { + $errs[] = $error; + } + + if ($this->args["help"]) { + $this->header(); + $this->help($prog); + exit; + } + try { + foreach (["signature", "license", "version"] as $opt) { + if ($this->args[$opt]) { + printf("%s\n", $this->metadata($opt)); + exit; + } + } + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::EARGS); + } + + try { + /* source needs to be evaluated before Cli\Args validation, + * so e.g. name and version can be overriden and Cli\Args + * does not complain about missing arguments + */ + $this->loadSource(); + } catch (\Exception $e) { + $errs[] = $e->getMessage(); + } + + foreach ($this->args->validate() as $error) { + $errs[] = $error; + } + + if ($errs) { + if (!$this->args["quiet"]) { + $this->header(); + } + foreach ($errs as $err) { + $this->error("%s\n", $err); + } + printf("\n"); + if (!$this->args["quiet"]) { + $this->help($prog); + } + exit(self::EARGS); + } + + $this->createPackage(); + } + + /** + * Download remote source + * @param string $source + * @return string local source + */ + private function download($source) { + if ($this->args->git) { + $task = new Task\GitClone($source, $this->args->branch); + } else { + /* print newline only once */ + $done = false; + $task = new Task\StreamFetch($source, function($bytes_pct) use(&$done) { + if (!$done) { + $this->info(" %3d%% [%s>%s] \r", + floor($bytes_pct*100), + str_repeat("=", round(50*$bytes_pct)), + str_repeat(" ", round(50*(1-$bytes_pct))) + ); + if ($bytes_pct == 1) { + $done = true; + $this->info("\n"); + } + } + }); + } + $local = $task->run($this->verbosity()); + + $this->cleanup[] = new Task\Cleanup($local); + return $local; + } + + /** + * Extract local archive + * @param stirng $source + * @return string extracted directory + */ + private function extract($source) { + try { + $task = new Task\Extract($source); + $dest = $task->run($this->verbosity()); + } catch (\Exception $e) { + if (false === strpos($e->getMessage(), "checksum mismatch")) { + throw $e; + } + $dest = (new Task\PaxFixup($source))->run($this->verbosity()); + } + + $this->cleanup[] = new Task\Cleanup($dest); + return $dest; + } + + /** + * Localize a possibly remote source + * @param string $source + * @return string local source directory + */ + private function localize($source) { + if (!stream_is_local($source) || ($this->args->git && isset($this->args->branch))) { + $source = $this->download($source); + $this->cleanup[] = new Task\Cleanup($source); + } + $source = realpath($source); + if (!is_dir($source)) { + $source = $this->extract($source); + $this->cleanup[] = new Task\Cleanup($source); + + if (!$this->args->git) { + $source = (new Task\PeclFixup($source))->run($this->verbosity()); + } + } + return $source; + } + + /** + * Load the source dir + * @throws \pharext\Exception + */ + private function loadSource(){ + if ($this->args["source"]) { + $source = $this->localize($this->args["source"]); + + if ($this->args["pecl"]) { + $this->source = new SourceDir\Pecl($source); + } elseif ($this->args["git"]) { + $this->source = new SourceDir\Git($source); + } elseif (is_file("$source/pharext_package.php")) { + $this->source = include "$source/pharext_package.php"; + } else { + $this->source = new SourceDir\Basic($source); + } + + if (!$this->source instanceof SourceDir) { + throw new Exception("Unknown source dir $source"); + } + + foreach ($this->source->getPackageInfo() as $key => $val) { + $this->args->$key = $val; + } + } + } + + /** + * Creates the extension phar + */ + private function createPackage() { + try { + $meta = array_merge(Metadata::all(), [ + "name" => $this->args->name, + "release" => $this->args->release, + "license" => $this->source->getLicense(), + "type" => $this->args->zend ? "zend_extension" : "extension", + ]); + $file = (new Task\PharBuild($this->source, __DIR__."/../pharext_installer.php", $meta))->run($this->verbosity()); + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::EBUILD); + } + + try { + if ($this->args->sign) { + $this->info("Using private key to sign phar ...\n"); + $pass = (new Task\Askpass)->run($this->verbosity()); + $sign = new Task\PharSign($file, $this->args->sign, $pass); + $pkey = $sign->run($this->verbosity()); + } + + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::ESIGN); + } + + if ($this->args->gzip) { + try { + $gzip = (new Task\PharCompress($file, Phar::GZ))->run(); + $move = new Task\PharRename($gzip, $this->args->dest, $this->args->name ."-". $this->args->release); + $name = $move->run($this->verbosity()); + + $this->info("Created gzipped phar %s\n", $name); + + if ($this->args->sign) { + $sign = new Task\PharSign($name, $this->args->sign, $pass); + $sign->run($this->verbosity())->exportPublicKey($name.".pubkey"); + } + + } catch (\Exception $e) { + $this->warn("%s\n", $e->getMessage()); + } + } + + if ($this->args->bzip) { + try { + $bzip = (new Task\PharCompress($file, Phar::BZ2))->run(); + $move = new Task\PharRename($bzip, $this->args->dest, $this->args->name ."-". $this->args->release); + $name = $move->run($this->verbosity()); + + $this->info("Created bzipped phar %s\n", $name); + + if ($this->args->sign) { + $sign = new Task\PharSign($name, $this->args->sign, $pass); + $sign->run($this->verbosity())->exportPublicKey($name.".pubkey"); + } + + } catch (\Exception $e) { + $this->warn("%s\n", $e->getMessage()); + } + } + + try { + $move = new Task\PharRename($file, $this->args->dest, $this->args->name ."-". $this->args->release); + $name = $move->run($this->verbosity()); + + $this->info("Created executable phar %s\n", $name); + + if (isset($pkey)) { + $pkey->exportPublicKey($name.".pubkey"); + } + + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::EBUILD); + } + } +} +path = $path; + } + + public function getBaseDir() { + return $this->path; + } + + public function getPackageInfo() { + return []; + } + + public function getLicense() { + if (($file = $this->findLicense($this->getBaseDir()))) { + return $this->readLicense($file); + } + return "UNKNOWN"; + } + + public function getArgs() { + return []; + } + + public function setArgs(Args $args) { + } + + public function filter($current, $key, $iterator) { + $sub = $current->getSubPath(); + if ($sub === ".git" || $sub === ".hg" || $sub === ".svn") { + return false; + } + return true; + } + + public function getIterator() { + $rdi = new RecursiveDirectoryIterator($this->path, + FilesystemIterator::CURRENT_AS_SELF | // needed for 5.5 + FilesystemIterator::KEY_AS_PATHNAME | + FilesystemIterator::SKIP_DOTS); + $rci = new RecursiveCallbackFilterIterator($rdi, [$this, "filter"]); + $rii = new RecursiveIteratorIterator($rci); + foreach ($rii as $path => $child) { + if (!$child->isDir()) { + yield realpath($path); + } + } + } +} +path = $path; + } + + /** + * @inheritdoc + * @see \pharext\SourceDir::getBaseDir() + */ + public function getBaseDir() { + return $this->path; + } + + /** + * @inheritdoc + * @return array + */ + public function getPackageInfo() { + return []; + } + + /** + * @inheritdoc + * @return string + */ + public function getLicense() { + if (($file = $this->findLicense($this->getBaseDir()))) { + return $this->readLicense($file); + } + return "UNKNOWN"; + } + + /** + * @inheritdoc + * @return array + */ + public function getArgs() { + return []; + } + + /** + * @inheritdoc + */ + public function setArgs(Args $args) { + } + + /** + * Generate a list of files by `git ls-files` + * @return Generator + */ + private function generateFiles() { + $pwd = getcwd(); + chdir($this->path); + if (($pipe = popen("git ls-tree -r --name-only HEAD", "r"))) { + $path = realpath($this->path); + while (!feof($pipe)) { + if (strlen($file = trim(fgets($pipe)))) { + /* there may be symlinks, so no realpath here */ + yield "$path/$file"; + } + } + pclose($pipe); + } + chdir($pwd); + } + + /** + * Implements IteratorAggregate + * @see IteratorAggregate::getIterator() + */ + public function getIterator() { + return $this->generateFiles(); + } +} +file = "$path/package2.xml"); + } elseif (is_file("$path/package.xml")) { + $sxe = simplexml_load_file($this->file = "$path/package.xml"); + } else { + throw new Exception("Missing package.xml in $path"); + } + + $sxe->registerXPathNamespace("pecl", $sxe->getDocNamespaces()[""]); + + $this->sxe = $sxe; + $this->path = realpath($path); + } + + /** + * @inheritdoc + * @see \pharext\SourceDir::getBaseDir() + */ + public function getBaseDir() { + return $this->path; + } + + /** + * Retrieve gathered package info + * @return Generator + */ + public function getPackageInfo() { + if (($name = $this->sxe->xpath("/pecl:package/pecl:name"))) { + yield "name" => (string) $name[0]; + } + if (($release = $this->sxe->xpath("/pecl:package/pecl:version/pecl:release"))) { + yield "release" => (string) $release[0]; + } + if ($this->sxe->xpath("/pecl:package/pecl:zendextsrcrelease")) { + yield "zend" => true; + } + } + + /** + * @inheritdoc + * @return string + */ + public function getLicense() { + if (($license = $this->sxe->xpath("/pecl:package/pecl:license"))) { + if (($file = $this->findLicense($this->getBaseDir(), $license[0]["filesource"]))) { + return $this->readLicense($file); + } + } + if (($file = $this->findLicense($this->getBaseDir()))) { + return $this->readLicense($file); + } + if ($license) { + return $license[0] ." ". $license[0]["uri"]; + } + return "UNKNOWN"; + } + + /** + * @inheritdoc + * @see \pharext\SourceDir::getArgs() + */ + public function getArgs() { + $configure = $this->sxe->xpath("/pecl:package/pecl:extsrcrelease/pecl:configureoption"); + foreach ($configure as $cfg) { + yield [null, $cfg["name"], ucfirst($cfg["prompt"]), Args::OPTARG, + strlen($cfg["default"]) ? $cfg["default"] : null]; + } + $configure = $this->sxe->xpath("/pecl:package/pecl:zendextsrcrelease/pecl:configureoption"); + foreach ($configure as $cfg) { + yield [null, $cfg["name"], ucfirst($cfg["prompt"]), Args::OPTARG, + strlen($cfg["default"]) ? $cfg["default"] : null]; + } + } + + /** + * @inheritdoc + * @see \pharext\SourceDir::setArgs() + */ + public function setArgs(Args $args) { + $configure = $this->sxe->xpath("/pecl:package/pecl:extsrcrelease/pecl:configureoption"); + foreach ($configure as $cfg) { + if (isset($args[$cfg["name"]])) { + $args->configure = "--{$cfg["name"]}={$args[$cfg["name"]]}"; + } + } + $configure = $this->sxe->xpath("/pecl:package/pecl:zendextsrcrelease/pecl:configureoption"); + foreach ($configure as $cfg) { + if (isset($args[$cfg["name"]])) { + $args->configure = "--{$cfg["name"]}={$args[$cfg["name"]]}"; + } + } + } + + /** + * Compute the path of a file by parent dir nodes + * @param \SimpleXMLElement $ele + * @return string + */ + private function dirOf($ele) { + $path = ""; + while (($ele = current($ele->xpath(".."))) && $ele->getName() == "dir") { + $path = trim($ele["name"], "/") ."/". $path ; + } + return trim($path, "/"); + } + + /** + * Generate a list of files from the package.xml + * @return Generator + */ + private function generateFiles() { + /* hook */ + $temp = tmpfile(); + fprintf($temp, " $temp; + + /* deps */ + $dependencies = $this->sxe->xpath("/pecl:package/pecl:dependencies/pecl:required/pecl:package"); + foreach ($dependencies as $key => $dep) { + if (($glob = glob("{$this->path}/{$dep->name}-*.ext.phar*"))) { + usort($glob, function($a, $b) { + return version_compare( + substr($a, strpos(".ext.phar", $a)), + substr($b, strpos(".ext.phar", $b)) + ); + }); + yield end($glob); + } + } + + /* files */ + yield realpath($this->file); + foreach ($this->sxe->xpath("//pecl:file") as $file) { + yield realpath($this->path ."/". $this->dirOf($file) ."/". $file["name"]); + } + } + + /** + * Implements IteratorAggregate + * @see IteratorAggregate::getIterator() + */ + public function getIterator() { + return $this->generateFiles(); + } +} +cwd = $cwd; + $this->type = $type; + $this->sudo = $sudo; + if (!$this->inis = $inis) { + throw new Exception("No PHP INIs given"); + } + $cmd = $common_name . "-config"; + if (isset($prefix)) { + $cmd = $prefix . "/bin/" . $cmd; + } + $this->php_config = $cmd; + } + + /** + * @param bool $verbose + * @return boolean false, if extension was already activated + */ + public function run($verbose = false) { + if ($verbose !== false) { + printf("Running INI activation ...\n"); + } + $extension = basename(current(glob("{$this->cwd}/modules/*.so"))); + + if ($this->type === "zend_extension") { + $pattern = preg_quote((new ExecCmd($this->php_config))->run(["--extension-dir"])->getOutput() . "/$extension", "/"); + } else { + $pattern = preg_quote($extension, "/"); + } + + foreach ($this->inis as $file) { + if ($verbose) { + printf("Checking %s ...\n", $file); + } + if (!file_exists($file)) { + throw new Exception(sprintf("INI file '%s' does not exist", $file)); + } + $temp = new Tempfile("phpini"); + foreach (file($file) as $line) { + if (preg_match("/^\s*{$this->type}\s*=\s*[\"']?{$pattern}[\"']?\s*(;.*)?\$/", $line)) { + return false; + } + fwrite($temp->getStream(), $line); + } + } + + /* not found; append to last processed file, which is the main by default */ + if ($verbose) { + printf("Activating in %s ...\n", $file); + } + fprintf($temp->getStream(), $this->type . "=%s\n", $extension); + $temp->closeStream(); + + $path = $temp->getPathname(); + $stat = stat($file); + + // owner transfer + $ugid = sprintf("%d:%d", $stat["uid"], $stat["gid"]); + $cmd = new ExecCmd("chown", $verbose); + if (isset($this->sudo)) { + $cmd->setSu($this->sudo); + } + $cmd->run([$ugid, $path]); + + // permission transfer + $perm = decoct($stat["mode"] & 0777); + $cmd = new ExecCmd("chmod", $verbose); + if (isset($this->sudo)) { + $cmd->setSu($this->sudo); + } + $cmd->run([$perm, $path]); + + // rename + $cmd = new ExecCmd("mv", $verbose); + if (isset($this->sudo)) { + $cmd->setSu($this->sudo); + } + $cmd->run([$path, $file]); + + if ($verbose) { + printf("Replaced %s ...\n", $file); + } + + return true; + } +} +prompt = $prompt; + } + + /** + * @param bool $verbose + * @return string + */ + public function run($verbose = false) { + system("stty -echo"); + printf("%s ", $this->prompt); + $pass = fgets(STDIN, 1024); + printf("\n"); + system("stty echo"); + if (substr($pass, -1) == "\n") { + $pass = substr($pass, 0, -1); + } + return $pass; + } +} +rewind(); $rii->valid(); $rii->next()) { + if (!$rii->isDot()) { + yield $rii->getSubPathname() => $rii->key(); + } + } + } +} +rm = $rm; + } + + /** + * @param bool $verbose + */ + public function run($verbose = false) { + if ($verbose) { + printf("Cleaning up %s ...\n", $this->rm); + } + if ($this->rm instanceof Tempfile) { + unset($this->rm); + } elseif (is_dir($this->rm)) { + $rdi = new RecursiveDirectoryIterator($this->rm, + FilesystemIterator::CURRENT_AS_SELF | // needed for 5.5 + FilesystemIterator::KEY_AS_PATHNAME | + FilesystemIterator::SKIP_DOTS); + $rii = new RecursiveIteratorIterator($rdi, + RecursiveIteratorIterator::CHILD_FIRST); + foreach ($rii as $path => $child) { + if ($child->isDir()) { + @rmdir($path); + } else { + @unlink($path); + } + } + @rmdir($this->rm); + } elseif (file_exists($this->rm)) { + @unlink($this->rm); + } + } +} +cwd = $cwd; + $cmd = $common_name . "-config"; + if (isset($prefix)) { + $cmd = $prefix . "/bin/" . $cmd; + } + $this->args = ["--with-php-config=$cmd"]; + if ($args) { + $this->args = array_merge($this->args, $args); + } + } + + public function run($verbose = false) { + if ($verbose !== false) { + printf("Running ./configure ...\n"); + } + $pwd = getcwd(); + if (!chdir($this->cwd)) { + throw new Exception; + } + try { + $cmd = new ExecCmd("./configure", $verbose); + $cmd->run($this->args); + } finally { + chdir($pwd); + } + } +} +source = $source; + } else { + $this->source = new PharData($source); + } + } + + /** + * @param bool $verbose + * @return \pharext\Tempdir + */ + public function run($verbose = false) { + if ($verbose) { + printf("Extracting %s ...\n", basename($this->source->getPath())); + } + if ($this->source instanceof Archive) { + return $this->source->extract(); + } + $dest = new Tempdir("extract"); + $this->source->extractTo($dest); + return $dest; + } +} +source = $source; + $this->branch = $branch; + } + + /** + * @param bool $verbose + * @return \pharext\Tempdir + */ + public function run($verbose = false) { + if ($verbose !== false) { + printf("Fetching %s ...\n", $this->source); + } + $local = new Tempdir("gitclone"); + $cmd = new ExecCmd("git", $verbose); + if (strlen($this->branch)) { + $cmd->run(["clone", "--depth", 1, "--branch", $this->branch, $this->source, $local]); + } else { + $cmd->run(["clone", $this->source, $local]); + } + return $local; + } +} +cwd = $cwd; + $this->sudo = $sudo; + $this->args = $args; + } + + /** + * + * @param bool $verbose + * @throws \pharext\Exception + */ + public function run($verbose = false) { + if ($verbose !== false) { + printf("Running make"); + if ($this->args) { + foreach ($this->args as $arg) { + printf(" %s", $arg); + } + } + printf(" ...\n"); + } + $pwd = getcwd(); + if (!chdir($this->cwd)) { + throw new Exception; + } + try { + $cmd = new ExecCmd("make", $verbose); + if (isset($this->sudo)) { + $cmd->setSu($this->sudo); + } + $args = $this->args; + if (!$verbose) { + $args = array_merge((array) $args, ["-s"]); + } + $cmd->run($args); + } finally { + chdir($pwd); + } + } +} +source = $source; + } + + private function openArchive($source) { + $hdr = file_get_contents($source, false, null, 0, 3); + if ($hdr === "\x1f\x8b\x08") { + $fd = fopen("compress.zlib://$source", "r"); + } elseif ($hdr === "BZh") { + $fd = fopen("compress.bzip2://$source", "r"); + } else { + $fd = fopen($source, "r"); + } + if (!is_resource($fd)) { + throw new Exception; + } + return $fd; + } + + public function run($verbose = false) { + if ($verbose !== false) { + printf("Fixing up a tarball with global pax header ...\n"); + } + $temp = new Tempfile("paxfix"); + stream_copy_to_stream($this->openArchive($this->source), + $temp->getStream(), -1, 1024); + $temp->closeStream(); + return (new Extract((string) $temp))->run($verbose); + } +}source = $source; + } + + /** + * @param bool $verbose + * @return string sanitized source location + * @throws \pahrext\Exception + */ + public function run($verbose = false) { + if ($verbose !== false) { + printf("Sanitizing PECL dir ...\n"); + } + $dirs = glob("{$this->source}/*", GLOB_ONLYDIR); + $files = array_diff(glob("{$this->source}/*"), $dirs); + $check = array_reduce($files, function($r, $v) { + return $v && fnmatch("package*.xml", basename($v)); + }, true); + + if (count($dirs) !== 1 || !$check) { + throw new Exception("Does not look like an extracted PECL dir: {$this->source}"); + } + + $dest = current($dirs); + + foreach ($files as $file) { + if ($verbose) { + printf("Moving %s into %s ...\n", basename($file), basename($dest)); + } + if (!rename($file, "$dest/" . basename($file))) { + throw new Exception; + } + } + + return $dest; + } +} +source = $source; + $this->stub = $stub; + $this->meta = $meta; + $this->readonly = $readonly; + } + + /** + * @param bool $verbose + * @return \pharext\Tempname + * @throws \pharext\Exception + */ + public function run($verbose = false) { + /* Phar::compress() and ::convert*() use strtok("."), ugh! + * so, be sure to not use any other dots in the filename + * except for .phar + */ + $temp = new Tempname("", "-pharext.phar"); + + $phar = new Phar($temp); + $phar->startBuffering(); + + if ($this->meta) { + $phar->setMetadata($this->meta); + } + if ($this->stub) { + (new PharStub($phar, $this->stub))->run($verbose); + } + + $phar->buildFromIterator((new Task\BundleGenerator)->run()); + + if ($this->source) { + if ($verbose) { + $bdir = $this->source->getBaseDir(); + $blen = strlen($bdir); + foreach ($this->source as $index => $file) { + if (is_resource($file)) { + printf("Packaging %s ...\n", $index); + $phar[$index] = $file; + } else { + printf("Packaging %s ...\n", $index = trim(substr($file, $blen), "/")); + $phar->addFile($file, $index); + } + } + } else { + $phar->buildFromIterator($this->source, $this->source->getBaseDir()); + } + } + + $phar->stopBuffering(); + + if (!chmod($temp, fileperms($temp) | 0111)) { + throw new Exception; + } + + return $temp; + } +}file = $file; + $this->package = new Phar($file); + $this->encoding = $encoding; + + switch ($encoding) { + case Phar::GZ: + $this->extension = ".gz"; + break; + case Phar::BZ2: + $this->extension = ".bz2"; + break; + } + } + + /** + * @param bool $verbose + * @return string + */ + public function run($verbose = false) { + if ($verbose) { + printf("Compressing %s ...\n", basename($this->package->getPath())); + } + /* stop shebang */ + $stub = $this->package->getStub(); + $phar = $this->package->compress($this->encoding); + $phar->setStub(substr($stub, strpos($stub, "\n")+1)); + return $this->file . $this->extension; + } +} +phar = $phar; + $this->dest = $dest; + $this->name = $name; + } + + /** + * @param bool $verbose + * @return string path to renamed phar + * @throws \pharext\Exception + */ + public function run($verbose = false) { + $extension = substr(strstr($this->phar, "-pharext.phar"), 8); + $name = sprintf("%s/%s.ext%s", $this->dest, $this->name, $extension); + + if ($verbose) { + printf("Renaming %s to %s ...\n", basename($this->phar), basename($name)); + } + + if (!rename($this->phar, $name)) { + throw new Exception; + } + + return $name; + } +} +phar = $phar; + } else { + $this->phar = new Phar($phar); + } + $this->pkey = new Openssl\PrivateKey($pkey, $pass); + } + + /** + * @param bool $verbose + * @return \pharext\Openssl\PrivateKey + */ + public function run($verbose = false) { + if ($verbose) { + printf("Signing %s ...\n", basename($this->phar->getPath())); + } + $this->pkey->sign($this->phar); + return $this->pkey; + } +} +phar = $phar; + if (!file_exists($this->stub = $stub)) { + throw new Exception("File '$stub' does not exist"); + } + } + + /** + * @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); + } +} +cwd = $cwd; + $cmd = $common_name . "ize"; + if (isset($prefix)) { + $cmd = $prefix . "/bin/" . $cmd; + } + $this->phpize = $cmd; + } + + /** + * @param bool $verbose + * @throws \pharext\Exception + */ + public function run($verbose = false) { + if ($verbose !== false) { + printf("Running %s ...\n", $this->phpize); + } + $pwd = getcwd(); + if (!chdir($this->cwd)) { + throw new Exception; + } + try { + $cmd = new ExecCmd($this->phpize, $verbose); + $cmd->run(); + } finally { + chdir($pwd); + } + } +} +source = $source; + $this->progress = $progress; + } + + private function createStreamContext() { + $progress = $this->progress; + + /* avoid bytes_max bug of older PHP versions */ + $maxbytes = 0; + return stream_context_create([],["notification" => function($notification, $severity, $message, $code, $bytes_cur, $bytes_max) use($progress, &$maxbytes) { + if ($bytes_max > $maxbytes) { + $maxbytes = $bytes_max; + } + switch ($notification) { + case STREAM_NOTIFY_CONNECT: + $progress(0); + break; + case STREAM_NOTIFY_PROGRESS: + $progress($maxbytes > 0 ? $bytes_cur/$maxbytes : .5); + break; + case STREAM_NOTIFY_COMPLETED: + /* this is sometimes not generated, why? */ + $progress(1); + break; + } + }]); + } + + /** + * @param bool $verbose + * @return \pharext\Task\Tempfile + * @throws \pharext\Exception + */ + public function run($verbose = false) { + if ($verbose !== false) { + printf("Fetching %s ...\n", $this->source); + } + $context = $this->createStreamContext(); + + if (!$remote = fopen($this->source, "r", false, $context)) { + throw new Exception; + } + + $local = new Tempfile("remote"); + if (!stream_copy_to_stream($remote, $local->getStream())) { + throw new Exception; + } + $local->closeStream(); + + /* STREAM_NOTIFY_COMPLETED is not generated, see above */ + call_user_func($this->progress, 1); + + return $local; + } +} +handle = fopen($path, "x"); + } while (!is_resource($this->handle) && $tries++ < 10); + umask($omask); + + if (!is_resource($this->handle)) { + throw new Exception("Could not create temporary file"); + } + + parent::__construct($path); + } + + /** + * Unlink the file + */ + public function __destruct() { + if (is_file($this->getPathname())) { + @unlink($this->getPathname()); + } + } + + /** + * Close the stream + */ + public function closeStream() { + fclose($this->handle); + } + + /** + * Retrieve the stream resource + * @return resource + */ + public function getStream() { + return $this->handle; + } +} +getUser(); + if (!is_dir($temp) && !mkdir($temp, 0700, true)) { + throw new Exception; + } + $this->name = $temp ."/". uniqid($prefix) . $suffix; + } + + private function getUser() { + if (extension_loaded("posix") && function_exists("posix_getpwuid")) { + return posix_getpwuid(posix_getuid())["name"]; + } + return trim(`whoami 2>/dev/null`) + ?: trim(`id -nu 2>/dev/null`) + ?: getenv("USER") + ?: get_current_user(); + } + + /** + * @return string + */ + public function __toString() { + return (string) $this->name; + } +} +args = new Cli\Args([ + ["h", "help", "Display this help", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + ["v", "verbose", "More output", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + ["q", "quiet", "Less output", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG], + [null, "signature", "Show pharext signature", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "license", "Show pharext license", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [null, "version", "Show pharext version", + Cli\Args::OPTIONAL|Cli\Args::SINGLE|Cli\Args::NOARG|Cli\Args::HALT], + [0, "path", "Path to .ext.phar to update", + Cli\Args::REQUIRED|Cli\Args::MULTI], + ]); + } + + /** + * @inheritdoc + * @see \pharext\Command::run() + */ + public function run($argc, array $argv) { + $errs = []; + $prog = array_shift($argv); + foreach ($this->args->parse(--$argc, $argv) as $error) { + $errs[] = $error; + } + + if ($this->args["help"]) { + $this->header(); + $this->help($prog); + exit; + } + + try { + foreach (["signature", "license", "version"] as $opt) { + if ($this->args[$opt]) { + printf("%s\n", $this->metadata($opt)); + exit; + } + } + } catch (\Exception $e) { + $this->error("%s\n", $e->getMessage()); + exit(self::EARGS); + } + + + foreach ($this->args->validate() as $error) { + $errs[] = $error; + } + + if ($errs) { + if (!$this->args["quiet"]) { + $this->header(); + } + foreach ($errs as $err) { + $this->error("%s\n", $err); + } + printf("\n"); + if (!$this->args["quiet"]) { + $this->help($prog); + } + exit(self::EARGS); + } + + foreach ($this->args[0] as $file) { + $info = new SplFileInfo($file); + + while ($info->isLink()) { + $info = new SplFileInfo($info->getLinkTarget()); + } + + if ($info->isFile()) { + if (!$this->updatePackage($info)) { + $this->warn("Cannot upgrade pre-v3 packages\n"); + } + } else { + $this->error("File '%s' does not exist\n", $file); + exit(self::EARGS); + } + } + } + + /** + * Replace the pharext core in an .ext.phar package + * @param string $temp path to temp phar + * @return boolean FALSE if the package is too old (pre-v3) to upgrade + */ + private function replacePharext($temp) { + $phar = new Phar($temp, Phar::CURRENT_AS_SELF); + $phar->startBuffering(); + + if (!$meta = $phar->getMetadata()) { + // don't upgrade pre-v3 packages + return false; + } + + // replace current pharext files + $core = (new Task\BundleGenerator)->run($this->verbosity()); + $phar->buildFromIterator($core); + $stub = __DIR__."/../pharext_installer.php"; + (new Task\PharStub($phar, $stub))->run($this->verbosity()); + + // check dependencies + foreach ($phar as $info) { + if (fnmatch("*.ext.phar*", $info->getBasename())) { + $this->updatePackage($info, $phar); + } + } + + $phar->stopBuffering(); + + $phar->setMetadata([ + "version" => Metadata::version(), + "header" => Metadata::header(), + ] + $meta); + + $this->info("Updated pharext version from '%s' to '%s'\n", + isset($meta["version"]) ? $meta["version"] : "(unknown)", + $phar->getMetadata()["version"]); + + return true; + } + + /** + * Update an .ext.phar package to the current pharext version + * @param SplFileInfo $file + * @param Phar $phar the parent phar containing $file as dependency + * @return boolean FALSE if the package is too old (pre-v3) to upgrade + * @throws Exception + */ + private function updatePackage(SplFileInfo $file, Phar $phar = null) { + $this->info("Updating pharext core in '%s'...\n", basename($file)); + + $temp = new Tempname("update", substr(strstr($file, ".ext.phar"), 4)); + + if (!copy($file->getPathname(), $temp)) { + throw new Exception; + } + if (!chmod($temp, $file->getPerms())) { + throw new Exception; + } + + if (!$this->replacePharext($temp)) { + return false; + } + + if ($phar) { + $phar->addFile($temp, $file); + } elseif (!rename($temp, $file->getPathname())) { + throw new Exception; + } + + return true; + } +} +#!/usr/bin/env php + +#include +#include +#include +#include + +namespace pharext; + +if (extension_loaded("Phar")) { + \Phar::interceptFileFuncs(); + \Phar::mapPhar(); + $phardir = "phar://".__FILE__; +} else { + $archive = new Archive(__FILE__); + $phardir = $archive->extract(); +} + +set_include_path("$phardir:". get_include_path()); + +$installer = new Installer(); +$installer->run($argc, $argv); + +__HALT_COMPILER(); +#!/usr/bin/php -dphar.readonly=0 +run($argc, $argv); + +__HALT_COMPILER(); +#!/usr/bin/php -dphar.readonly=0 +run($argc, $argv); + +__HALT_COMPILER(); +; see http://editorconfig.org +root = true + +[*] +end_of_line = lf +insert_final_newline = true +indent_style = tab +charset = utf-8 +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.json] +indent_style = space +indent_size = 4 + +[package.xml] +indent_style = space +indent_size = 1 + +[config.w32] +end_of_line = crlf +package.xml merge=touch +php_raphf.h merge=touch +config.w32 eol=crlf + +# / +*~ +/*.tgz +/.deps +*.lo +*.la +/config.[^mw]* +/configure* +/lib* +/ac*.m4 +/ltmain.sh +/install-sh +/Make* +/mk* +/missing +/.libs +/build +/include +/modules +/autom4te* +/.dep.inc +run-tests.php +/.cproject +/.project +.libs/ +/php_raphf_api.h +Doxyfile.bak +!/Makefile.frag +[submodule "travis-pecl"] + path = travis/pecl + url = https://github.com/m6w6/travis-pecl.git + branch = master +# autogenerated file; do not edit +sudo: false +language: c + +addons: + apt: + packages: + - php5-cli + - php-pear + +env: + matrix: + - PHP=master enable_debug=no enable_maintainer_zts=no + - PHP=master enable_debug=yes enable_maintainer_zts=no + - PHP=master enable_debug=no enable_maintainer_zts=yes + - PHP=master enable_debug=yes enable_maintainer_zts=yes + +before_script: + - make -f travis/pecl/Makefile php + - make -f travis/pecl/Makefile ext PECL=raphf + +script: + - make -f travis/pecl/Makefile test +Michael Wallner +Yay, now known and unresolved issues yet! +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of +fostering an open and welcoming community, we pledge to respect all people who +contribute through reporting issues, posting feature requests, updating +documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free +experience for everyone, regardless of level of experience, gender, gender +identity and expression, sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic + addresses, without explicit permission +* Other unethical or unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct. By adopting this Code of Conduct, project +maintainers commit themselves to fairly and consistently applying these +principles to every aspect of managing this project. Project maintainers who do +not follow or enforce the Code of Conduct may be permanently removed from the +project team. + +This code of conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by opening an issue or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the +[Contributor Covenant](http://contributor-covenant.org), version 1.2.0, +available at http://contributor-covenant.org/version/1/2/0/. +raphf +Michael Wallner +# Doxyfile 1.8.10 + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- +DOXYFILE_ENCODING = UTF-8 +PROJECT_NAME = "Resource and persistent handle factory API" +PROJECT_NUMBER = +PROJECT_BRIEF = "A facility to manage possibly persistent resources with a comprehensible API. Provides simliar functionality like the zend_list API, but with more flexiblity and freedom." +PROJECT_LOGO = raphf.png +OUTPUT_DIRECTORY = +CREATE_SUBDIRS = NO +ALLOW_UNICODE_NAMES = NO +OUTPUT_LANGUAGE = English +BRIEF_MEMBER_DESC = YES +REPEAT_BRIEF = YES +ABBREVIATE_BRIEF = +ALWAYS_DETAILED_SEC = NO +INLINE_INHERITED_MEMB = NO +FULL_PATH_NAMES = YES +STRIP_FROM_PATH = +STRIP_FROM_INC_PATH = +SHORT_NAMES = NO +JAVADOC_AUTOBRIEF = YES +QT_AUTOBRIEF = NO +MULTILINE_CPP_IS_BRIEF = NO +INHERIT_DOCS = YES +SEPARATE_MEMBER_PAGES = NO +TAB_SIZE = 4 +ALIASES = +TCL_SUBST = +OPTIMIZE_OUTPUT_FOR_C = YES +OPTIMIZE_OUTPUT_JAVA = NO +OPTIMIZE_FOR_FORTRAN = NO +OPTIMIZE_OUTPUT_VHDL = NO +EXTENSION_MAPPING = no_extension=md +MARKDOWN_SUPPORT = YES +AUTOLINK_SUPPORT = YES +BUILTIN_STL_SUPPORT = NO +CPP_CLI_SUPPORT = NO +SIP_SUPPORT = NO +IDL_PROPERTY_SUPPORT = YES +DISTRIBUTE_GROUP_DOC = NO +GROUP_NESTED_COMPOUNDS = NO +SUBGROUPING = YES +INLINE_GROUPED_CLASSES = NO +INLINE_SIMPLE_STRUCTS = YES +TYPEDEF_HIDES_STRUCT = NO +LOOKUP_CACHE_SIZE = 0 +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- +EXTRACT_ALL = YES +EXTRACT_PRIVATE = NO +EXTRACT_PACKAGE = NO +EXTRACT_STATIC = NO +EXTRACT_LOCAL_CLASSES = NO +EXTRACT_LOCAL_METHODS = NO +EXTRACT_ANON_NSPACES = NO +HIDE_UNDOC_MEMBERS = NO +HIDE_UNDOC_CLASSES = NO +HIDE_FRIEND_COMPOUNDS = NO +HIDE_IN_BODY_DOCS = NO +INTERNAL_DOCS = NO +CASE_SENSE_NAMES = YES +HIDE_SCOPE_NAMES = NO +HIDE_COMPOUND_REFERENCE= NO +SHOW_INCLUDE_FILES = YES +SHOW_GROUPED_MEMB_INC = NO +FORCE_LOCAL_INCLUDES = NO +INLINE_INFO = YES +SORT_MEMBER_DOCS = YES +SORT_BRIEF_DOCS = NO +SORT_MEMBERS_CTORS_1ST = NO +SORT_GROUP_NAMES = NO +SORT_BY_SCOPE_NAME = NO +STRICT_PROTO_MATCHING = NO +GENERATE_TODOLIST = YES +GENERATE_TESTLIST = YES +GENERATE_BUGLIST = YES +GENERATE_DEPRECATEDLIST= YES +ENABLED_SECTIONS = +MAX_INITIALIZER_LINES = 30 +SHOW_USED_FILES = YES +SHOW_FILES = YES +SHOW_NAMESPACES = YES +FILE_VERSION_FILTER = +LAYOUT_FILE = +CITE_BIB_FILES = +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- +QUIET = NO +WARNINGS = YES +WARN_IF_UNDOCUMENTED = YES +WARN_IF_DOC_ERROR = YES +WARN_NO_PARAMDOC = NO +WARN_FORMAT = "$file:$line: $text" +WARN_LOGFILE = +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- +INPUT = README.md CONTRIBUTING.md php_raphf.h src +INPUT_ENCODING = UTF-8 +FILE_PATTERNS = +RECURSIVE = NO +EXCLUDE = +EXCLUDE_SYMLINKS = NO +EXCLUDE_PATTERNS = +EXCLUDE_SYMBOLS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = +EXAMPLE_RECURSIVE = NO +IMAGE_PATH = +INPUT_FILTER = +FILTER_PATTERNS = +FILTER_SOURCE_FILES = NO +FILTER_SOURCE_PATTERNS = +USE_MDFILE_AS_MAINPAGE = README.md +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- +SOURCE_BROWSER = NO +INLINE_SOURCES = NO +STRIP_CODE_COMMENTS = YES +REFERENCED_BY_RELATION = YES +REFERENCES_RELATION = NO +REFERENCES_LINK_SOURCE = YES +SOURCE_TOOLTIPS = YES +USE_HTAGS = NO +VERBATIM_HEADERS = YES +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- +ALPHABETICAL_INDEX = YES +COLS_IN_ALPHA_INDEX = 5 +IGNORE_PREFIX = +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- +GENERATE_HTML = YES +HTML_OUTPUT = . +HTML_FILE_EXTENSION = .html +HTML_HEADER = +HTML_FOOTER = +HTML_STYLESHEET = +HTML_EXTRA_STYLESHEET = +HTML_EXTRA_FILES = BUGS CONTRIBUTING.md LICENSE THANKS TODO +HTML_COLORSTYLE_HUE = 220 +HTML_COLORSTYLE_SAT = 100 +HTML_COLORSTYLE_GAMMA = 80 +HTML_TIMESTAMP = NO +HTML_DYNAMIC_SECTIONS = NO +HTML_INDEX_NUM_ENTRIES = 100 +GENERATE_DOCSET = NO +DOCSET_FEEDNAME = "Doxygen generated docs" +DOCSET_BUNDLE_ID = org.doxygen.Project +DOCSET_PUBLISHER_ID = org.doxygen.Publisher +DOCSET_PUBLISHER_NAME = Publisher +GENERATE_HTMLHELP = NO +CHM_FILE = +HHC_LOCATION = +GENERATE_CHI = NO +CHM_INDEX_ENCODING = +BINARY_TOC = NO +TOC_EXPAND = NO +GENERATE_QHP = NO +QCH_FILE = +QHP_NAMESPACE = org.doxygen.Project +QHP_VIRTUAL_FOLDER = doc +QHP_CUST_FILTER_NAME = +QHP_CUST_FILTER_ATTRS = +QHP_SECT_FILTER_ATTRS = +QHG_LOCATION = +GENERATE_ECLIPSEHELP = NO +ECLIPSE_DOC_ID = org.doxygen.Project +DISABLE_INDEX = NO +GENERATE_TREEVIEW = YES +ENUM_VALUES_PER_LINE = 4 +TREEVIEW_WIDTH = 250 +EXT_LINKS_IN_WINDOW = NO +FORMULA_FONTSIZE = 10 +FORMULA_TRANSPARENT = YES +USE_MATHJAX = NO +MATHJAX_FORMAT = HTML-CSS +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest +MATHJAX_EXTENSIONS = +MATHJAX_CODEFILE = +SEARCHENGINE = YES +SERVER_BASED_SEARCH = NO +EXTERNAL_SEARCH = NO +SEARCHENGINE_URL = +SEARCHDATA_FILE = searchdata.xml +EXTERNAL_SEARCH_ID = +EXTRA_SEARCH_MAPPINGS = +#--------------------------------------------------------------------------- +# Configuration options related to the LaTeX output +#--------------------------------------------------------------------------- +GENERATE_LATEX = NO +LATEX_OUTPUT = latex +LATEX_CMD_NAME = latex +MAKEINDEX_CMD_NAME = makeindex +COMPACT_LATEX = NO +PAPER_TYPE = a4 +EXTRA_PACKAGES = +LATEX_HEADER = +LATEX_FOOTER = +LATEX_EXTRA_STYLESHEET = +LATEX_EXTRA_FILES = +PDF_HYPERLINKS = YES +USE_PDFLATEX = YES +LATEX_BATCHMODE = NO +LATEX_HIDE_INDICES = NO +LATEX_SOURCE_CODE = NO +LATEX_BIB_STYLE = plain +#--------------------------------------------------------------------------- +# Configuration options related to the RTF output +#--------------------------------------------------------------------------- +GENERATE_RTF = NO +RTF_OUTPUT = rtf +COMPACT_RTF = NO +RTF_HYPERLINKS = NO +RTF_STYLESHEET_FILE = +RTF_EXTENSIONS_FILE = +RTF_SOURCE_CODE = NO +#--------------------------------------------------------------------------- +# Configuration options related to the man page output +#--------------------------------------------------------------------------- +GENERATE_MAN = NO +MAN_OUTPUT = man +MAN_EXTENSION = .3 +MAN_SUBDIR = +MAN_LINKS = NO +#--------------------------------------------------------------------------- +# Configuration options related to the XML output +#--------------------------------------------------------------------------- +GENERATE_XML = NO +XML_OUTPUT = xml +XML_PROGRAMLISTING = YES +#--------------------------------------------------------------------------- +# Configuration options related to the DOCBOOK output +#--------------------------------------------------------------------------- +GENERATE_DOCBOOK = NO +DOCBOOK_OUTPUT = docbook +DOCBOOK_PROGRAMLISTING = NO +#--------------------------------------------------------------------------- +# Configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- +GENERATE_AUTOGEN_DEF = NO +#--------------------------------------------------------------------------- +# Configuration options related to the Perl module output +#--------------------------------------------------------------------------- +GENERATE_PERLMOD = NO +PERLMOD_LATEX = NO +PERLMOD_PRETTY = YES +PERLMOD_MAKEVAR_PREFIX = +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = YES +EXPAND_ONLY_PREDEF = NO +SEARCH_INCLUDES = YES +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +PREDEFINED = DOXYGEN \ + TSRMLS_C= \ + TSRMLS_D= \ + TSRMLS_CC= \ + TSRMLS_DC= \ + PHP_RAPHF_API= +EXPAND_AS_DEFINED = +SKIP_FUNCTION_MACROS = YES +#--------------------------------------------------------------------------- +# Configuration options related to external references +#--------------------------------------------------------------------------- +TAGFILES = +GENERATE_TAGFILE = +ALLEXTERNALS = NO +EXTERNAL_GROUPS = YES +EXTERNAL_PAGES = YES +PERL_PATH = /usr/bin/perl +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- +CLASS_DIAGRAMS = YES +MSCGEN_PATH = +DIA_PATH = +HIDE_UNDOC_RELATIONS = YES +HAVE_DOT = YES +DOT_NUM_THREADS = 0 +DOT_FONTNAME = Helvetica +DOT_FONTSIZE = 10 +DOT_FONTPATH = +CLASS_GRAPH = NO +COLLABORATION_GRAPH = YES +GROUP_GRAPHS = YES +UML_LOOK = NO +UML_LIMIT_NUM_FIELDS = 10 +TEMPLATE_RELATIONS = NO +INCLUDE_GRAPH = YES +INCLUDED_BY_GRAPH = YES +CALL_GRAPH = YES +CALLER_GRAPH = YES +GRAPHICAL_HIERARCHY = YES +DIRECTORY_GRAPH = YES +DOT_IMAGE_FORMAT = png +INTERACTIVE_SVG = NO +DOT_PATH = +DOTFILE_DIRS = +MSCFILE_DIRS = +DIAFILE_DIRS = +PLANTUML_JAR_PATH = +PLANTUML_INCLUDE_PATH = +DOT_GRAPH_MAX_NODES = 50 +MAX_DOT_GRAPH_DEPTH = 0 +DOT_TRANSPARENT = NO +DOT_MULTI_TARGETS = NO +GENERATE_LEGEND = YES +DOT_CLEANUP = YES +Copyright (c) 2013, Michael Wallner . +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# provide headers in builddir, so they do not end up in /usr/include/ext/raphf/src + +PHP_RAPHF_HEADERS := $(addprefix $(PHP_RAPHF_BUILDDIR)/,$(PHP_RAPHF_HEADERS)) + +$(PHP_RAPHF_BUILDDIR)/%.h: $(PHP_RAPHF_SRCDIR)/src/%.h + @cat >$@ <$< + +$(all_targets): raphf-build-headers +clean: raphf-clean-headers + +.PHONY: raphf-build-headers +raphf-build-headers: $(PHP_RAPHF_HEADERS) + +.PHONY: raphf-clean-headers +raphf-clean-headers: + -rm -f $(PHP_RAPHF_HEADERS) +# ext-raphf + +[![Build Status](https://travis-ci.org/m6w6/ext-raphf.svg?branch=master)](https://travis-ci.org/m6w6/ext-raphf) + +The "Resource and Persistent Handle Factory" extension provides facilities to manage those in a convenient manner. + +## Documentation + +See the [online markdown reference](https://mdref.m6w6.name/raphf). + +Known issues are listed in [BUGS](./BUGS) and future ideas can be found in [TODO](./TODO). + +## Installing + +### PECL + + pecl install raphf + +### PHARext + +Watch out for [PECL replicates](https://replicator.pharext.org?raphf) +and pharext packages attached to [releases](./releases). + +### Checkout + + git clone github.com:m6w6/ext-raphf + cd ext-raphf + /path/to/phpize + ./configure --with-php-config=/path/to/php-config + make + sudo make install + +## ChangeLog + +A comprehensive list of changes can be obtained from the +[PECL website](https://pecl.php.net/package-changelog.php?package=raphf). + +## License + +ext-raphf is licensed under the 2-Clause-BSD license, which can be found in +the accompanying [LICENSE](./LICENSE) file. + +## Contributing + +All forms of contribution are welcome! Please see the bundled +[CONTRIBUTING](./CONTRIBUTING.md) note for the general principles followed. + +The list of past and current contributors is maintained in [THANKS](./THANKS). +Thanks go to the following people, who have contributed to this project: + +Anatol Belski +Remi Collet +* TTL +sinclude(config0.m4) +ARG_ENABLE("raphf", "for raphf support", "no"); + +if (PHP_RAPHF == "yes") { + var PHP_RAPHF_HEADERS=glob("src/*.h"), PHP_RAPHF_SOURCES=glob("src/*.c"); + + EXTENSION("raphf", PHP_RAPHF_SOURCES); + PHP_INSTALL_HEADERS("ext/raphf", "php_propro.h"); + for (var i=0; i + + raphf + pecl.php.net + Resource and persistent handles factory + A reusable split-off of pecl_http's persistent handle and resource factory API. + + Michael Wallner + mike + mike@php.net + yes + + 2015-12-01 + + 2.0.0RC1 + 2.0.0 + + + beta + stable + + BSD, revised + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 7.0.0 + + + 1.4.0 + + + + raphf + + +/* + +--------------------------------------------------------------------+ + | PECL :: raphf | + +--------------------------------------------------------------------+ + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the conditions mentioned | + | in the accompanying LICENSE file are met. | + +--------------------------------------------------------------------+ + | Copyright (c) 2013, Michael Wallner | + +--------------------------------------------------------------------+ +*/ + +#ifndef PHP_RAPHF_H +#define PHP_RAPHF_H + +extern zend_module_entry raphf_module_entry; +#define phpext_raphf_ptr &raphf_module_entry + +#define PHP_RAPHF_VERSION "2.0.0RC1" + +#ifdef PHP_WIN32 +# define PHP_RAPHF_API __declspec(dllexport) +#elif defined(__GNUC__) && __GNUC__ >= 4 +# define PHP_RAPHF_API extern __attribute__ ((visibility("default"))) +#else +# define PHP_RAPHF_API extern +#endif + +#ifdef ZTS +# include "TSRM.h" +#endif + +#include "php_raphf_api.h" + +#endif /* PHP_RAPHF_H */ + + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ +/* + +--------------------------------------------------------------------+ + | PECL :: raphf | + +--------------------------------------------------------------------+ + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the conditions mentioned | + | in the accompanying LICENSE file are met. | + +--------------------------------------------------------------------+ + | Copyright (c) 2014, Michael Wallner | + +--------------------------------------------------------------------+ +*/ + +#include + +struct user_cb { + zend_fcall_info fci; + zend_fcall_info_cache fcc; +}; + +struct raphf_user { + struct user_cb ctor; + struct user_cb copy; + struct user_cb dtor; + struct { + struct user_cb dtor; + zval data; + } data; +}; + +static inline void user_cb_addref(struct user_cb *cb) +{ + Z_ADDREF(cb->fci.function_name); + if (cb->fci.object) { + Z_ADDREF_P((zval *) cb->fci.object); + } +} + +static inline void user_cb_delref(struct user_cb *cb) +{ + if (cb->fci.object) { + Z_DELREF_P((zval *) cb->fci.object); + } +} + +static void raphf_user_dtor(void *opaque) +{ + struct raphf_user *ru = opaque; + + zend_fcall_info_argn(&ru->data.dtor.fci, 1, &ru->data.data); + zend_fcall_info_call(&ru->data.dtor.fci, &ru->data.dtor.fcc, NULL, NULL); + zend_fcall_info_args_clear(&ru->data.dtor.fci, 1); + user_cb_delref(&ru->data.dtor); + zend_fcall_info_args_clear(&ru->ctor.fci, 1); + user_cb_delref(&ru->ctor); + zend_fcall_info_args_clear(&ru->copy.fci, 1); + user_cb_delref(&ru->copy); + zend_fcall_info_args_clear(&ru->dtor.fci, 1); + user_cb_delref(&ru->dtor); + memset(ru, 0, sizeof(*ru)); + efree(ru); +} + +static void *user_ctor(void *opaque, void *init_arg TSRMLS_DC) +{ + struct raphf_user *ru = opaque; + zval *zinit_arg = init_arg, *retval = ecalloc(1, sizeof(*retval)); + + zend_fcall_info_argn(&ru->ctor.fci, 2, &ru->data.data, zinit_arg); + zend_fcall_info_call(&ru->ctor.fci, &ru->ctor.fcc, retval, NULL); + zend_fcall_info_args_clear(&ru->ctor.fci, 0); + + return retval; +} + +static void *user_copy(void *opaque, void *handle TSRMLS_DC) +{ + struct raphf_user *ru = opaque; + zval *zhandle = handle, *retval = ecalloc(1, sizeof(*retval)); + + zend_fcall_info_argn(&ru->copy.fci, 2, &ru->data.data, zhandle); + zend_fcall_info_call(&ru->copy.fci, &ru->copy.fcc, retval, NULL); + zend_fcall_info_args_clear(&ru->copy.fci, 0); + + return retval; +} + +static void user_dtor(void *opaque, void *handle TSRMLS_DC) +{ + struct raphf_user *ru = opaque; + zval *zhandle = handle, retval; + + ZVAL_UNDEF(&retval); + zend_fcall_info_argn(&ru->dtor.fci, 2, &ru->data.data, zhandle); + zend_fcall_info_call(&ru->dtor.fci, &ru->dtor.fcc, &retval, NULL); + zend_fcall_info_args_clear(&ru->dtor.fci, 0); + if (!Z_ISUNDEF(retval)) { + zval_ptr_dtor(&retval); + } +} + +static php_resource_factory_ops_t user_ops = { + user_ctor, + user_copy, + user_dtor +}; + +static int raphf_user_le; + +static void raphf_user_res_dtor(zend_resource *res TSRMLS_DC) +{ + php_resource_factory_free((void *) &res->ptr); +} + +static PHP_FUNCTION(raphf_provide) +{ + struct raphf_user *ru; + char *name_str; + size_t name_len; + zval *zdata; + + ru = ecalloc(1, sizeof(*ru)); + + if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sfffzf", + &name_str, &name_len, + &ru->ctor.fci, &ru->ctor.fcc, + &ru->copy.fci, &ru->copy.fcc, + &ru->dtor.fci, &ru->dtor.fcc, + &zdata, + &ru->data.dtor.fci, &ru->data.dtor.fcc)) { + efree(ru); + return; + } + + user_cb_addref(&ru->ctor); + user_cb_addref(&ru->copy); + user_cb_addref(&ru->dtor); + user_cb_addref(&ru->data.dtor); + + ZVAL_COPY(&ru->data.data, zdata); + + if (SUCCESS != php_persistent_handle_provide(name_str, name_len, + &user_ops, ru, raphf_user_dtor)) { + RETURN_FALSE; + } + RETURN_TRUE; +} + +static PHP_FUNCTION(raphf_conceal) +{ + zend_string *name; + + if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "S", &name)) { + return; + } + + RETURN_BOOL(FAILURE != zend_hash_del(&PHP_RAPHF_G->persistent_handle.hash, name)); +} + +static PHP_FUNCTION(raphf_concede) +{ + char *name_str, *id_str; + size_t name_len, id_len; + php_persistent_handle_factory_t *pf; + php_resource_factory_t *rf; + php_resource_factory_ops_t *ops; + + if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", + &name_str, &name_len, &id_str, &id_len)) { + return; + } + + ops = php_persistent_handle_get_resource_factory_ops(); + pf = php_persistent_handle_concede(NULL, name_str, name_len, id_str, id_len, + NULL, NULL TSRMLS_CC); + if (!pf) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, + "Could not locate persistent handle factory '%s'", name_str); + RETURN_FALSE; + } + rf = php_resource_factory_init(NULL, ops, pf, + (void(*)(void*)) php_persistent_handle_abandon); + if (!rf) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, + "Could not create resource factory " + "for persistent handle factory '%s'", name_str); + RETURN_FALSE; + } + + zend_register_resource(return_value, rf, raphf_user_le); +} + +static PHP_FUNCTION(raphf_dispute) +{ + zval *zrf; + + if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zrf)) { + return; + } + + RETURN_BOOL(SUCCESS == zend_list_close(Z_RES_P(zrf))); +} + +static PHP_FUNCTION(raphf_handle_ctor) +{ + zval *zrf, *zrv, *zinit_arg; + + if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rz", + &zrf, &zinit_arg)) { + return; + } + + zrv = php_resource_factory_handle_ctor(Z_RES_VAL_P(zrf), zinit_arg); + RETVAL_ZVAL(zrv, 0, 0); + efree(zrv); +} + +static PHP_FUNCTION(raphf_handle_copy) +{ + zval *zrf, *zrv, *zhandle; + + if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rz", + &zrf, &zhandle)) { + return; + } + + zrv = php_resource_factory_handle_copy(Z_RES_VAL_P(zrf), zhandle); + RETVAL_ZVAL(zrv, 0, 0); + efree(zrv); +} + +static PHP_FUNCTION(raphf_handle_dtor) +{ + zval *zrf, *zhandle; + + if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rz", + &zrf, &zhandle)) { + return; + } + + php_resource_factory_handle_dtor(Z_RES_VAL_P(zrf), zhandle); +} + +static PHP_MINIT_FUNCTION(raphf_test) +{ + zend_register_long_constant(ZEND_STRL("RAPHF_TEST"), PHP_RAPHF_TEST, CONST_CS|CONST_PERSISTENT, module_number); + raphf_user_le = zend_register_list_destructors_ex(raphf_user_res_dtor, NULL, + "raphf_user", module_number); + return SUCCESS; +} + +static PHP_MSHUTDOWN_FUNCTION(raphf_test) +{ + php_persistent_handle_cleanup(ZEND_STRL("test"), NULL, 0 TSRMLS_CC); + return SUCCESS; +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ +‰PNG + + IHDRÙlç¹°gAMA± üabKGDùC» pHYs  šœtIMEÝ 'É=)… IDATxÚì½GÜùu5|*çœsWçfhr˜&hFÒ(YòH ËÛðÆ6¼´—¸ñð'0 m´²$À0Ù3$8$;‡ê®œsÎõ.Fç¢z,ùµ¤ç}k£Ñ YááÞsÏ9Wñÿð‹Éd¯×‹J¥½^N‡gϞÉ?‡CÌf3, ôû}¨Õj4 ¼öÚkP©TÈd2è÷ûX,°Ûí8<<Äîî.ªÕ*>÷¹ÏáääƒÁNV«+++°X,8;;C¹\†ÛíÆh4Ât:E§ÓÅbA¯×Ãöö64 ž={§Ó »ÝH§Óp:0›Íè÷û Ÿ ­V Ýn7nÜÀ|>‡Ëå‚F£A6›…Ãá€ÇãA©TÂùù9VVV0ŸÏ±²²‚|>x<ŽF£~¿ñxŒñxŒ›7oâää*• +'''hµZxóÍ71ŸÏ‡¡R©ÐjµÉdÐn·Ç11Náv»Q©Tðüùs ‡Cܺu N§Ϟ=ƒÉdB,Ã`0€R©ÄÖÖ +…^ÆãŊ‡ê7ÞxØét R©p||Œn·‹H$Fƒ`0ˆÑh„F£N‡ÑhÇðûý‡¸¸¸€F£ÅbÕjE¥RA(Âb±€ÃáÀ³gÏ°X, Õj¡Õj¡Óé`4Q­V¡Ñh P(Ðjµ0¡ÓéÐjµ`·Ûáóù T*Ñn·a0`2™ T*¡P(0P«Õ`2™‰D`6› Ñl61›Ípÿþ}ŒÇc”ËeD"( +L§S¬®®¢×ëa2™æó9ö÷÷Ñn·±³³ƒÙl†jµ +‹Å—Ë…x<Žóós ‡Clooc8¢\.c>ŸÜn7l6:t:, NNNÐh4àt:±X, R©>Ÿz½*• +NívÑhÓéÍfõz/ãñbÅCõÎ;ï<ôx<¸¸¸Àl6ƒÁ`Àb±€ÕjE£Ñ€Á`Àh4‚ÇãÃáÀp8„Éd‚ÅbA2™„ÍfƒÍfC³ÙD£ÑÀh4B$ÍfC»Ý†^¯G³ÙD:F$J¥Âh4B»ÝF¯×ƒB¡€Á`@¯×ƒZ­†ßïÇx<–€šL&x< ‚×땓´Z-ìv;Úí6jµz½Ìf3¦Ó)4 æó9L&†Ã!b±Òé´üÎ^¯‡t:˜Íf¼ÿþûP(¸~ý:†Ã!ªÕ*úý>ìv;¦Ó)‰‹nÞ¼ ¯× N‡L&ƒZ­›Í†••Yl*• +NF^¯ƒÁ³Ù v»V«Ýn­V ‘HãñÉdív6› /ãñbÅCõÕ¯~õa>Ÿ‡Ãá€Éd’Sp4áÃ?Ä`0À͛7Q«ÕP(°¹¹ Fƒn·‹N§FƒÅb‹Å‚ápÇƒÑh„ããc ‡Ch4øý~( +˜Íf, ŒÇcÀjµB£ÑÀl6Ãn·C­VL&@§Óa±X`8b4A¡P@­VC¯×C«ÕÂb±Àãñ ßïc:Ê"Ðëõ˜ÏçrÂL&èõzôû}8Àh4‚Á`@(’ÓÐjµ¢^¯Ãáp`±XÈ{6›MìììÀåra:ÊßU©TÐëõ˜N§˜L&ø裏àñxàñx`µZ‘J¥`³ÙÍf¡Ñh ×ëáp8ptt„\.£Ñˆ`0³ÙŒD"`0¥R‰—ñx±â¡ú¾ðp}}¥R ƒAv`«Õ‚ÇãÓé„R©Äb±€ÍfÃb±@µZ…B¡€ÏçC­VÃ|>‡^¯‡Éd‚V«E³ÙD¿ßG·Û…Á`€ÝnÇÎΚÍ&ƒªÕ*¬V+ü~?F£l6›œÍf*• +F£‹Å³Ù ÍfóùF£QN¦*ÓéG>3—ËÁ`0 V«Ál6C­VòCU*L&(•J(•Jx<¨Õj(•JÌçs8ܺu Z­jµZ­J¥jµý~:õz^¯óùN•J^¯ñxrºµÛm8NèõzŒF#ÌçslllƒºÝ.l6êõ:ŠÅ"Õj5¬V+”J%Òé4NNNðꫯB©TÂívK:’Ï祈n·ÛÐét˜Ïç¨×ë éŽÏçC£Ñ€Ýn‡Ñh”‡Ì‚<ŸÏc:B­Vc8Âív£V«Áëõb8b±X@­VˏÏçóÇp»ÝÐëõ¨×ë0™L°Ùl‡¨×ëðûýh6›èv»ˆÅbH$r"`p8‚zõû}ƒA¨T*är9B¡Z­†Ã!æó¹, ¢Ñ(†Ã! +.//a41NaµZQ(°X,àr¹­‰ÇãÐjµ8::B£ÑÁ`0@£ÑH +Ñív¡Óé T*%]á ÂÜ»V«ÉÉ`4Q¯×a4&|<ŸÏ¥ðÖh4‡èõzršÙl6h4YÓé&“ N‡FÒ&ötôz=šÍ¦¤>ƒÁ¥R óùƒóùÍfFŠz‡ÃŸÏ‡\.‡N§ƒÁ€[·n¡Ñh P(Àf³Áëõ"‹áìì …BANüƒƒ¼ŒÇ‹՟þéŸ>ÜÞކZ­†N§C³ÙÄt:E·Û•7è÷û è÷û(•JP(è÷ûP*•‡ÃP*•0°Ùl¸¼¼Äññ1ôz=|>ŸäÊ*• +J¥½^ý~óùN§S +O…BÁ`€Á`µZ-péÆƆ¼/¡`…B…B½^‹Å‚J¥"¹;¿«ÝnG2™Ä|>‡ÏçÃt:•E“W«Õb2™ ßï£ÕjA§Ó¡\.C§ÓIÏh4Éop¥À‡°X,èv»0›Íp8òJ¥jµÖ××áõz‘N§%àÁ`årÿöoÿ†ét +§Ó‰““hµZ¬®®âe<^¬x¨~ÿ÷ÿá`0þF³Ù„N§“^F§ÓA*•B¥R‘ëy8ÂårÁh4"¢ÕjI—›»7#“É  Âét +RÅ¢ÈéÂff4ˆçx<Æp8„R©Äd2DI§ÓIóq8¢T*ÉIY.—Ç…-`6›¥ð/‹Â(•J’2¹\.éó$ x½^Øív( +~€Ô ÌáY_°Q*•ðù|rKðÏp!=zôV«UXìóX­V¼ŒÇ‹Õ×¾öµ‡…Bççç˜Ïçr‚E" ‡CÔj5Ôj5, ˜ÍfA© +Ôj5Z­â ’sW*Ìf3ôû}ù{>ŸÐëõ0NFÑíva±Xàp8Ðjµ¤°œN§( +òÃY€v:D"Ìçsôû}øý~´Z-Äb1L&”Ëeܽ{årívãñkkkÈårÐëõÇP©TW~^¯G«Õ‚ÏçC·Û•ßçó ˆÀ÷q8Ðjµ¸¸¸~lôÚl¶+HÓ$öÆã1F£‘¤7/ãñbÅCõ;¿ó;m6Òé4Úí¶ô9:<b±¼^/&“‰49É׺¼¼D­V$‡á(—Ë(—ËX__—ÞÆd2‘¦¥ÓéD¯×“­Ùl"“É`:Âl6C¥R¡\.£ßïÃ`0Àf³Áï÷ E¦ÑhHJsyy)?P£Ñ P(`}}]`èr¹Œp8Œ­­-i’‡V*•N§¤Ø&S‚§¿^¯‡Ñh«ÝnÃápt~qq!ÏÂãñ ^¯#‘HÁß\«ÕP©T°ºº +«Õ*,‹—ñx±â¡úæ7¿ùhQ8F @¹\†R©DµZªL €ÅbZL£Ñ@·Û…J¥‚Ãá€ÅbL§Sá‡17w¹\d¦ÃᇍFC˜T«UéG°°e¨Õja:Ân·£Ûíb6›áüü‹‹“É‹ÅN§Sd±X`·ÛÑét„‡æt:¡ÑhÐëõ Õjqzz +³Ù ‹Å‚D"!E~¯×ƒÅbÁúú:òù<*• +:Ž@Ç$ΦÓi¨ÕjiŽ^^^¢Óé`6›ÉŸ{'ªû÷ï?œÍf0ÒÁ¯×ëršL&d³Yèõz„Ãa4›M ‡C€ÕjÅx<Æd2Á`0(´Ûí" +! ‚ï_­VÑëõ„±= àr¹„®²Œb t»]Aʍ†Ã!¼^¯ü¹v» ·Ûét*9??‡F£Úd2a>Ÿc0l6¦Ó)¦Ó)z½žð×Æã1ÔjµÐfx‹EL&!Ôò$eo&‰ Ýnc4!ÃápH1΂˜ý$6‚ÙÄt»Ý0™L‚¾µZ-¼ŒÇ‹՛o¾ù]óÉdµZ-Ô~…B¥R‰B¡N'4£Ñ(½›Í&ù1ósµZ “É$y6™ÕF£:n·[zäÅ- ÌçséY$ h4I[x“vc±Xý2™LH&“Èårøù|ŽápN­V‹B¡€x<³Ù …B!iÒb±€ßïG¹\Æh4’n¿V«…F£f¶J¥‚Õjä¨ÑhÀb±`ccC>Ïçóa±XàôôZ­>ŸOè@ϟ?G¿ßG­VC4…Z­†B¡Àp8ôN­V£Ûíâe<^¬x¨¾ýío?$lÉ¢¯V«Áétb8¢X," +A¡PH7ž'›N§Ãt:…Ëå’kx4a4É)zyy‰ápˆx<µZñx ƒÁ l‚L&#hV.—Ãx<–“‘‹…žÅb!'´Ùl–bX¡P Ýnc8¢Ñh²¦P(Ðét„JCé†Ãᐞ +åÃáÝnZ­V´C\h ˜b©T*‘It:ÉōF#òù÷¹‡l®±×P,Ñjµ ×ëa6›«««è÷ûÒq',\($÷e‘MÂËËKÉUÙ×étÒmµZÒ姬 ÕjÁår]y?’B‰åóyáÔ± °X,h4R”ûý~Io”J%f³t:ŠÅ"\.t:t:ºÝ.úý>L&f³aµZár¹îµX,P(H¥R0›Í²8Ʉp:˜ÏçÇ‡Ã‚Pñy2Îf3¸Ýnôz=är9L&¸Ýn¸ÝnÄãqÔëu¼ŒÇ‹ÕÛo¿ýÐï÷˕Üëõ0¥síp8àt:qyyy¥%9”'N«Õ‚V«¶v£Ñ@(’^›‰üaz½^Цv»X,&Wr³ÙD8–Þ ¹nÌߙ‚Ôëuh©ª­Õj˜L&ØÚÚÂb±@¯×‘`£Ñ aµZ¥‡@(C&“IÒ²"f³Ìf³œ® +…B×n·ù|`6›eqž‰þˆiåóù±X Ãá¹\‹ù| +…/ãñbÅCõå/ùa0„N§Ãéé)t:ÎÏÏá÷û¡×ë‘Íf¥eÎʞÀd2—BAµZ`0(?„ªS½^Á`€B¡£Ñ(ª]’P«Õ*\.Ôj5²Ù,:ìv;f³™À©£ÑHȬ̙ÉÈårÐh4…B˜Íf˜ÏçH&“P«Õ˜Ïç(—ËØÙÙZUÀ à2*g2™„²3%àBR}LÎû:äãY,èõzèõz¸\.ôû}á¼ÅãqA¢ìv;*• +l6^ÆãŊ‡ê«_ýêCþæœ<í´Z-ÎÏÏát: 1ŸÏá÷ûQ«Õ„Z‹EÄtÁ`PÐjlòù¼¤NGh3kkkh4èt:0øðÃáÑh4899‘‚÷îÝ»P©TøøãE»£V«¥ÉÈ^…ÕjÅh4’š$ +%‡Œvéو%¬Ûï÷%¿¦èp: +›Àl6Ã`0ˆ¬a<Kss>ŸÃjµ¢ÕjÉÉ;›Íàñx$=S*•"'!° P(°ººŠÑh„—ñx±â¡zýõ×úý~ôz=á|ñdªV«0™LX]]E«ÕBµZ…V«…Ûí†B¡âu0H…=¥R)_Šâ<´ô€¨V«˜ÏçR0gv»Ý¢!r¹\P(BFP*•’÷×j5øý~Ìf3„Ãa 8ù=ô£ Èn<K2ŸÏa6›Ñh4®4c™"‘r´X,‰D„\ËÞÉ«f³“É~¿étZH·z½^ +~¨T*p¹\¨Õjèt:ƒp8H¥R°X,è÷ûèt:x+ªx<þÐl6c{{‡*•J®nƒh4èõzÂIëõzh4ÒùW(ò÷˜†å "ÎcŸ¤Ýn m‡M@æø.— Éd•JjµZÐ,•ŒF#èõzÌf3T*lmmÉ©ùôéS‘@¬¯¯c8~Òqÿ9¥F¯×K_*•Ðëõ`4Eë¤Óé ×ëÑëõ®, +­V ƒÁÇ#é‚,¢©Áâ‚S«ÕÈårR‘%Þï÷a41 DêO1âññ1*• +^ÆãŊ‡êÿðMâÕKo‡ÕÕUi¼QÁÊ^‹V«E.—“æ‰CɃÕj…ÅbA§ÓÏçC¡P)û7v»]±ìߍF¹þ{½Z­Ìf3”J¥ð֔J%²Ù¬¤1N‰D:ëëë0 ¨T*(•JÒ±ŸL&"ê;>>–f$õO@@ <›$Æò{) +Ôj5)¬—û5ü-Íf&“IôY.—KD‘H:N™L±X Íf“ÉÑh/ãñ‚ÅãÞ½{—¯}—Ë…““Aa +…ìv»Øk©T*´Ûm)î‰úý>¬V«@ºZ­+++ØÛۃÛíÆd2A£ÑÀd2A»Ý†B¡8˜’­V “É$Ww±X„R©”^Êd2A(†ËåB¯×ւÛí†ÙlÆÚÚ²Ù,ž>}ŠÝÝ]ôû}9¹‰ö¸Ýn û4Ká©W©T R©`±Xí¢c›“v»]ôU#º\.Éùçó9r¹\.— i‹EŒnjµ4ô±2™Œ¤u/ãñâÄCI©4O¿‹‹ øý~QÕRÇ"”]{î|RGÎÎΤÎ×úú:2™Œô/t:œN§¸±ï Ñh`µZ…Œêñx ×ë…5¾œ¿›L&Qâa +…B…Bx÷ÝwÑï÷ñÆo`8ŠÌÜjµÂf³ Ê5›Í„¡NvÀh4B«Õ ÓÆÆ:F£, 2™ŒÀ0Eêt:¨V«¨×ë¢Çj·Ûh4¢ébQM½S¿ß¿@ °¹×ëÅËx¼xñP}ùË_~8 F1ŸÏ¹¡ÄVXÌÉm6†|A³ÙŒz½.×&)þ¥RIòvž—”Z¦^¯‡p8Œµµ54›M +1ôÇÐjµ(—ËXYYÁÖ֖]®¯¯‹‹,šŒF#F£‘ôMØíçŸaaìr¹¤ïC¿?—˳ٌ³³3hµZ¬­­‰ˆ’Ìô—ñx±â¡úË¿üˇJ¥årY<õìv;€äµ»»»èv»¨V«˜Íf¢”-‹‚ªÐNù•W^'ØH$«ÕŠÉd‚b±(ð¦ÏçC¹\–œ×jµ"™LÂï÷Ãçóa<#‘HH#”ýö]HµÛíÈf³§¾ùæ›"_ŸÍf‡ƒˆF£¨ÕjòïhGV­Vj4RÔËeFÄãqѱ?”Àd2ÁjµŠï^­V–g¦Ó)Âá° cN§^¯ù|ÑhëëëÒ,e:CC͗ñxqâ¡øÞ÷¾·˜L&èv»øàƒðÙÏ~V])»¦4a>Ÿ‹¥3;í½^O¸Z‘HD®g:Á²7떦ü¡PH¤Âñä#|œÍf1qÿþ}±å¢¯{*•‚Á`@«Õ’G£Qa)”Ëe4 lnn"ŸÏK~ìv»át:]#šf±XÄ*šÀÙ””³·²¹¹‰V«·Û-§ål66ŒÈXg_Š ð@ èµLÑhTNýñxŒ^¯‡>øo½õ–訣Ñ(ñ H‘ñà þ‹âA¸ýWÁLÿÿŒG¿ßób±(ñ Læÿëxý›ìÕ·¿ýí‡ì“¼ù曣Җ‹½ â½Ç“|²ž)ž£¬B£ÑA5H/D«ÕJ߆ü/."þýL&ÇÐh4H&“X]]…ËåÂÙÙvvv cÁËàP±k·Û‘ÉdÐívåïrÃ( +T*8N §‡°¯”ÍfÅՈÄXÊ?Hl¥ÄA£Ñˆ Òf³I³—Jòýl6jµš€ ~¿‡Íf¹\N +No¼ñ ²Ù,æó¹, n¢z½.µ†^¯íãqvv‹Å“É$ú«ét +¯×‹`0(ñÐét˜Ífp¹\âÞËŠñH¥Rðz½ËËK¬¬¬ÀétþÒxt:˜ÍfIm6Òé4ºÝ.âñ¸X¶¡,—Ëp8².šÍæ¨>—ËawwWå*•JPQ­V+·3)_Œ='™&šÍæ_9¿êþXŽ‡êßøÆÃ÷Þ{>ŸO‚AÒ#Œ¤–èõz(•JØl6éV¥'ÙӕJ +…âŠáÈh4ÓM…B!A¦¿:¡dÂÏf³¡PH8p888@8Æáá¡ÀÄÕjÁ`BÌ\[[C§ÓSÌF£!t"vÿN'¦Ó)ªÕª°h\IÔl<#Êûv»]Ù8¥RéŠò—RýeOv¥R)¶Ö˘Ýn°€l¦rï½÷œN§,öˆúý> +…ºÝ®¸ùr¡¨ÕjÔëu)¾'“‰¨˜—{m6›@ç<èH®V«"YžPÂþ’Á`@ Ó~}}GGG…B8>>–ú¦Z­Âï÷ãàà@œœ–Ð-¸^¯#›Í¢ÑhÈçsQRKF¤R©” ;ÐëõäÖµZ­0ÂŽ_ž8c4¡P(¤åá4NåÐ!€A=Z Ѓÿ'?ù ¼^¯0Iþßö‡Ýn‡F£‘g®øîw¿» `8Š?‚ÙlF­VC©T¶3U´¸‘÷Öï÷?!BþÜfŒèt:…^¯(™¾LqÈz惡ù%­¸<H +B¡ôvø°Ÿ={&vÉn·[z9Åb~¿Z­çççWXÛäóQÚÐëõ„Y@V™&“I\j3™Œøý•ËeaeeE‚±ºº +•J…'OžÀl6c6›! + £œ‚E +I\m4‡ÃÈårƒò]È)äæfäfÏçrÐðp Ÿ>dåðæ IDATF±XD"‘Àp8L§ÓÁn·#£R©ˆ ‘"EÖ0¤9œœœ  J*I_ˆÓÓS\\\ P(HCöoOê­X{Pf´œ–ÐÎÚn·Ë" +p¹\¢¦ç­jµ†Ã!=z$߃§;k–Åb!‡á}ƒÁ«Õ +ƒÁ€­­-ܾ}[€ŠñxŒÏ|æ3x÷Ýw…ÂÄÙ`\p´ ôŸk©R©ˆEÁ`€Ïça©ÏçC¥RÁéé©@êô5ämÍú”‡:™L+™fsSÑ^f³™4t¬¢öíõ×_Çb±LÍì_¶?˜½q¨†J¥‚úæ͛Èår888üýøøXN”ÕÕUÔëuôz=x<™^H²æ£GÏç%íãb!x±üâ‰Á^þw´cŠÄÑ5£Ñ‰DB†Èííí¡Ýncmm J¥ÿñÿ!Ž­Ùl7oޔSŠSêŒL&“XD³Þ##áøøP­V±··'´ ét +ƒÁ€·Þz n·ûûûP*•ƒâ—ÁÏbJC•0g{±Fk6›8;;ÃÓ§Oq~~.llÆþ¢ŸÏ§Ÿÿy6›ÉÍe0ÄÄ4•JáÞ½{²¸9—#}ø;©€æëŎŸÇz<‰Èj2™°¹¹ …BÿøDz÷÷÷‘J¥p~~.©Ú/{o¾?­àƒß¸qCêçt:d2)ö/ZgLÙçóZþsüoü>T\/ iÇc¬¯¯ãúõë¨ÕjØÛÛû_íl6‹n·+Ö©T +ꋋ ”J%‘˜s‚ÅÆÆêõ:ŽŽŽàt:‹ÅM¢¨×ëÉIÌT€@¶Ÿ~x„S ˜°žXN‹(`!Ûn·±¹¹‰\.‡J¥«ÕŠõõuhµZ¤Ói¹®9Ń> Bà ƒè÷ûH$( +p8˜ÏçX__Ç|>—|}:¢R©HzI³¦§¹\NØv»] +îÁ` µǛò´^NõÚíö=k†ét*J¸x»saŒàmÃFñd2‚5Ó­Ùl†7nÀl6ÃårÁétJêƦ-oåŹü=>½Áx{˜L&<þápׯ_Ù›ÉlX^ø\ÐË/ÖM•Ôï÷Q,ñÎ;ïˆt„ô)ڇú}ب&Iš¿‰ŸÉõIô‘ ×ðò‹1Îçó¨×ëâñÈÃñÚd™ †OHÂÛÛÛùÅÈóûý2?¸Ó鈅Ñö(è< +…°²²ƒÁ¿ß/hV«•tÌf³auu‡¡P.—K–ÏçÃÖ֖,\Šô†Ã¡Ð`h +…àóùP¯×Õq¹\Rƒ) +¹U)¡gï†ßm±XÀ`0 a:òä Æ•ßKð†ô!¯×+4{=Ì@B2»ÉÕ«V«8;;y·Ûk×® Ôn0ĨÅh4ÂápÀjµbss7oޔ´Q¥Raeen·^¯›››rCqÜk%„9˙P>'£p1‹ çÏy‚d*p“Ó$Õn·ãÁƒØÜ܄R©ÄŸÿùŸcwwñx\@ Zº¹Ýn‘Õ,è£T†^‰tãu82Έ’“?û³?ƒÙl–‚‘˹̬}¨(°Z­Ò÷óûý²Îâñ¸LµÛíXYY‘45„Ïær8†Ïç»â @¿ÿÓþ˜L&0™L(‹Ÿ”F+++¨T*RË05a‡œÁ¢ ët:•<Øív# +¡V«‰çGÔP¤·ŒL½þúë¸}û¶:‰Qð·¿¿/6˜æÑï÷Ñl6¥ÓϚÅ`0 _ñô£¢Õl6£ÝnË÷äìß7nH*Õh4Yâ¨ÕZ­†r¹,§û1¼-hriµZÅq—(ɤï;=y V«UlooË9zgg———Fò¼9.ÕëõâßøÂá0Þ}÷]S(Q¡=öææ&~úӟb±Xœ+ÎSÞØؐzË`0ˆ¯Å½{÷P.—¡ÕjåæN¥RÂlw»Ýâ)Oòî›o¾‰@ ˋ‹ ‡C¬­­]ËÃá°è´Íçs|üñÇ2³™Y †{÷îÁëõ +÷ñôôF<@¡P@¡P€V«•ÚŽ0;3›Í†o~ó›²ykµ¬V« á¼í“É$¼^¯8qU*$ að +|ç;߁×ës!ڃÿOûƒé3Ùÿ@à“>™Åb‘“ V«É(š‚ØívádÑÅU£ÑH1ÈùLdp€œB¡ÀÖ֖ twîÜÆ3eޑHDd’ÍބÑh`a>Ÿ‹Á?ƒ§ÓéÄv«T*ÁívKŠÐh4dáðtÕh48::B·ÛÅÚښܰårYƟòvæÉÄ[nssSÜfkµ´Z­Èèù`kµš,¨f³)·2{DÜ<ô0 h4(‹(•J’ŽÆb1„Ãa¬¬¬  Âh4bssS€`0(–ÕL·].—ÜRn·[Ð4öé0‹Åäû²¦"û­šÊX­VAhý~?~÷w_ûÚ×àñx°¶¶†ÍÍM$“IhµZ±Œ#c¤\.# +ÉÁÄvE“”ÖÐçîÝ»ø“?ù¬¯¯£Ýn#‰ +yãÆ ifÓъ>ûÝnWD¤lZß»wOØ[[[2mfÙ΀Ïßn·£Z­¢Z­"ŸÏËaʲ€ë—ëvyÔÓ/ÚÌ4¨ ”™LFNjr˜JqÊ;=û6›MI‡¡Òû½2”…sFQQ>‡Ãb±(‹Âår! ‘”ÓWWWáóùp~~.-nN6Yg°ÐfŸƒ½+‚´†&§P(°¶¶†½½=q„eNÎ x<Ñb1 œMÅiív>ŸgggÈd2¢Âå¼*šÎМ¥ßïãàà@`a¶h<£Õj%ä ®®® +0ÀC…z*Ë#Ãô.‰ Ñh V«áòò?ýéOÅR› ‰ÍfÃîî.B¡òù<²Ù¬pü‚Á +…ªÕªÔ‰ñxz½‡‡‡h·ÛhµZˆF£X,°ÛíâQ*•„¢¤R©„´Ì¾$×]Š···át:ñ…/|ï¿ÿ>Úí¶l`ŸˆD"2X}OöCÃá°¤Ú½^·nÝB6›EµZ…×ë†Ñh„ÙlF,“zh53:W©T +½^ï½?è Â6J¥‚Òçó¡Õj¡ÙlJ·»X,J±~çΡ™¤Ói‘4 +I™¾â¤Þˆ‚¿gϞá‡?ü!t:|>"‘ÎÎÎpyy §Ó)SÉ"áµl6›%E`Z7N1›Í Ñh°¹¹)´ö%\.—°¸):œÏçÂøv»Ýxã7 P(ž®V«â‹Á¥ ‡‡‡˜ÏçÈf³"AçxÔ\.'è!OM¡PHü6šÍ¦Œý)•JB"e}I‰øÚÚNOO1Éd°½½-N·§§§W†ì1McZH„‹ðu,ƒN§Ãþþ>Þ}÷]èõzƒAiK”ËeY¼¬'‰ÄòPËårxÿý÷ñïÿþïøøãÅ¥‰›o6›I=N»*‘Ûí¶l:²(\.>ÿùϋ6K­V#•JáîÝ»rYCïúÁ` ŒhF£J¥Rê%ZàÑÀ”`Y@ét———2W› +kª§Õ[4•rãWÙ\Ó&“ Êjµz…:ÃüÈÈÑё )ƒ}-")²Z­"N ¬LNÓ­;wî`4áÑ£GˆD"2ö”¬ ·Ûd2‰n·‹ëׯË&èv»RT/í¡x!›ÍŠÅ™F£Ëåðƒð*A +‹Å"º&ª}Ë岤wz½Gxƒô¤5óp8Äd2Ýn¾Ú|>'Y»Ý.3É|1ò[蛱µµ%-¢±t;28<<Äl6õkפqúüùsäóyär91eo†VÛ4æ<>>†ÃáÀ½{÷D)­×ë±X,pëÖ-Ìf3<þ¡PGÆÖÈév»(‹¸ÿ¾€ +z½ûûû8==E"‘ÀÖ֖¨†‰Øy½^d³YA$U*•|7ŽM"#Ÿ)^­V“ÅÌt‹ ^‹Å">ˆ´XF°É¹dÉBÒðññ±x–”J%ŒF#1we[€ÙѲ·äb±À׿þu1Q%ô«îÅbñ‰† ´ƒƒI/ªÕª,Šeêϵk×dt ùxD$Yè25"Æԇsª666°··‡z½ŽT*“É$H­½ØØäUn6›±±±! jž’¬Êå²q4!Êț££#looË ãt:廯T*ù+ +„B!¼óÎ;èõzxòä‰Ü²ì›1ãTG»Ý.¬tö &“ r¹"‘ˆL£$=Š ‚u +af¢•Óéûûûðz½p:²ˆ …‚4ó;vvv$ƒ³Ù GGGr"sü,[-LÍidêñx$ŏÇ( +˜L&ò]x#år9ôû}cwwWZ(³ÙLšÚìv:¡¤ ‡C¡¥•J%¡¦q!2I&“²†ø¾GGGŠÅb&žžÊš\~f„ã{½vwwe +&AFƒl6{%´Î#-¯ÛíJ“Üëõ¢ßïËgìïïÃf³!ÿÊûCI›b¯× ¯×‹b±(ˆ:»Ý.›ÍJ^}qq­V+}1¦Š´ +Ëd2(•JÐëõØØظâdËÁ ¤1 ™dB ¦˜ôF§±èh4’÷åɹ̶`‰ †^¯a Ãᐱ>‹EžM§ÓÁöö¶‘Ëå²ô¹ ûý>Âá°*• +ÉdÃáÛÛÛØßß¿’‰Ìçsi½îõz¥ôx<Ðjµxþü¹øÇollàþýû8::’[z4!•JI¯0QåÅb!ó–766$ÍnµZh·Û¸¸¸ÀÊʊÔBìi-?3Òôü~¿üVn¬z½ŽZ­†@ p%TH“?ËAíÄ)®_¿ŽŸüä'èt:‚püùUö‡’¨?¬X,¢^¯Ãn·KMÃ>;ê„My’ŽÇc4 øýþ+' S4•J%iûZ­f³Â$“€Œ æíä@6 œžžâéÓ§xë­·pûöm¨T*œžž"£V«‰"÷•W^A³ÙD­V“qÌf3œžžJ <…wÊ´³Ë–×ÇèªT*Ù°T…ü²x°>å\l¶¨Ú.‹Bçä›_g(¯]»&(T·ÛE*•’æE~œÈøìÙ3ä…ÃaL§S¤Y°.ÿx¢€¤¹F¼òÊ+¢"­V«R¼s$)›™$Åò¤âB'SºÙlÊúÕÕU™Ùí???‡ÇãÁÖÖ†Ã!ö÷÷a6›‘Ïç¥???G:–ÏaŽN§!"¤$¸ +1oá¦%û€ Ï`0`ss«««R P/ÅTh,g~-¿ôz½0ê[­‰ŽŽŽÏçÿÇxÏ´˜7!¬—ž©McVÁßS.—ñ³Ÿý «««rÈüºûCI\6³Ù,4ƒÁ ƒ§IybqHõg,Ã`0Àáá¡öø"4:›ÍP.—¥‘Ûjµp||ŒP($Œr +ŽŽŽäÇòE6…ÏçÿøEÌf3qFp»Ýøҗ¾—Ë…ÓÓSlmmassS +T¿ßgϞ¡Ñhˆ}—Ñh”[ŒµM¿ßG4•T€c_ ÙÅbR©¥R‰ëׯ õ‡{ggG¨8ü~ÍfSŒE­V«ôÏ8_xù`"A­ 79âè—Ń½F +yú§R)ܸqëëëò½©Xfm™H$¤¶[îv»]ìííÉâÞÛۓæ/¥T\d³YŸ–ãqvv†x<.¼}†¬£`0ˆÝÝ]Aü(-—ËÒ 8Â6ÑrºH2Ô:88€Ïçû¥ñ`M­R©¤óx<˜N§(—Ëxíµ×¤ÕÍfíý¡ænãàîP($^rppp€7n ‘Hˆ% ø~¿/jÖ¯ýëxþüù•“ÊZ±p´ŒÉdÈxY—N§ås©>]&t’›ÈAãgggðx<(•J"ìõzÂçÛÛۓæ$óir"§Ó©Pv–OÃ/}éKWb¹P§Ó© ûÙÏ~†»wïâòò³Ù +++Ò'#•‰í“É$Ú(ŠS3™ŒP3™Ì•MFíÁ–û÷ï£R©È ó_¯»Ý.’Éä•l‚,ŒýèGðx<ø‹¿ø éÕí#·ðӄ[Ž6â¼d¿ß/ršB¡ 4;ZÉ]^^"‹Ó¾µµ5!•óf ˆSb8àB¡Pàþýûxüø±¬Çét*¶Ô=òFdí8™LN§¡Õjñ­o}K¼BR©Ô•x°Í6@:ò@4E±X„Ãá€Ïç•D.—ûö‡²Ñh N‹›Q"‘€Ùl†Ãá~Z*•’ü•BÊB¡ ©Ä`0@³ÙÄÚÚڕšŒ©âÞÞšÍ&´Z-l6îܹ#ðs¹œðçó9R©”ËiË`0¦§&^¿~]]3™ ¶··±³³#f/Ÿ—›gù”§D4g§½½=iÎZ­V\»vM”Á”øj·ÛrÐÄb1ܸq?úяL&‘ÉdÍfà¢ü…sü^/Ö××±¹¹yÅ.€ƒ:TAd³Y¬­­a±X`ggG¦g’^W¯×‘ÏçŇ9]d©P($Åfl–E»dïS!°··‡½½=”Ëe<þ\ìܚÍ&NOOQ¯×ãý¡ÜÜÜŸÃá@¡PÀl6ÊÊîî.Âá0¢Ñ(|>Ÿì~Ne¤áH0¼rR-lŠÅ"~ðƒ +…ÖÖÖ°±±[·na8âñãÇBy:99¹lææwîܑ<š ßJ¥‚íímapVç÷j4q)›R©„½½=¡ÉÐ׏òw¦[„çé£Á‘«ì©ñ&[„MoƒÁ |Èv» §Ó‰ÕÕU™ˆrëÖ-Pn·Û%•á3³ÙlÐëõ°X,²ˆS©šÍ&nݺu%½^©T +*• +'''âu²|[î¿wïúý>¶¶¶J¥ðOÿôOÒzˆÅb⸼x™>F"Ôëu|÷»ßߔ@ €V«%ÈaµZE*•ºYùOŸ>[®ZÐÆâèèü±ÔÕl•ôz=É.ØD_Feys/$œNãóù`0P*•¤ ‚?Æññ1Êå²XÂ9N„B!ißüßØj·Û×_{{{úàE"™ÙDp•J%ƒ Øí¾ÿ¾8ú,çôlÔíììÈ¿?==•Ñ£„QYèÿä'?Áññ1.//¯œÄìU)•JüÝßýòù<ÎÏÏ‹ÅP©Tpyy)€›Éd;w°²²"Sz`áÁ˜\´ßû½ßC$A Àóçϱ½½-`9…$ƒîíí!àââ6›Mê¾Yõ4éaÀ—O`Jb–{‹FÈ­*• +_ýêW…º½½-ua4 òßÿ}œŸŸ_I³ }þóŸÇ‡~ˆ¯|å+¸ÿ>šÍ&ÎÏÏqqq!VjD&—ãǙeôÅ BúéÓ§"¥aëv»1ðäɹ¡™MðöàáI ˆ[8±ÎÎ΄¾¦ÑhP,±µµ%ƒû–y¦Ô+N§Sá·~ë·¤n&!¹×ëÁl6‹•µoäd’ƒ‰DDÇ¹Ï¿éþPw»]iĺÝnÒ‡¦4©TJè>jµét»»»P*•ø×ýWÄb11ç_²V«ÅÏ~ö3˜Íf|éK__‡G ª¨ÑhÄ3ƒ|<Âf³‰ì# +R‹ÅËåpvv&ý*ÇƒD"!'e¡P> y”œ#Ì[ŒßÓjµ"`0àüü\¬"‘r¹œÔ”‰D¯½öšÈ83™t*ÒÌh°É†&‰Æ­VKÒ +³ÙŒL&s%Å&ÐB/‘z½‹Å›Í†Á` NOÉdRdô“Éûûû{óE6y¿ßÇéé)þê¯þ +Íf?þñÑívñöÛo ³ÿôôÍfó +jÇø)\__Çåå%NOO¥õÀZ•‡èòMÅ ÄZo™AÁf0oŽ|>Ç›Í†>úf³Yüé¹c±˜¸Z-?3ʳ¸ñ˜:Ïf3µD‹À[:F*•’¿ ±³³#ޒìÙrâo²?Ô¼n)<Fb–ÂJ¹\¾b&ât:áñxÐl6Q*•àñxÄpeùE§ZjÁÈí+ +H$RR¯³|:qÁ²/‰`G~P·ÛÅÊʊèšhj³Œn>yòN§7oÞÄþþ>åÁÑ:Œ‹+ "NÃëõ +Á€òć0 Âh¿~ýºlb2U8µÓ\ZËQ.Do“å]¤X –Ëe‘Y(•J +X­Vq­âB …(šÚX­VT«U$“I|å+_AµZÅÿù?ÿGäz’y¿Ìø àb±Xpxx((){ˆtcìI[¶àÿ2]d å÷û¯ØK0ýe”ýÍjµ*©éåå¥Ô¬Ë/Nz¹¼¼Äõë×ÅA*•J¡ÓéÈ÷#ВÏçeÓ³¥aµZáp8„0@äù7Ýj$›ÍJqIò-eޔ·sÇSR>±²²‚••$‰+ÖøbξººŠv»ÓÓS‘•ÐzëÓþjµ@@ÆýÜ¿ßùÎwP.—åôyüø1>ûÙÏ +»áÚµk8??½k'ª¶Éãã ÄáñxwïޕïÁô‹°ð²)ŠÕjåu½^Çúúº¤|TýR:Ab)Õœöa·Û%0¿ÈۃñX[[ …†§¼9éV­VñôéS\y—Ë…`0ˆ@ »ÝŽoûÛèõz(‹899Íf³΄ŽÇãW6g#¯¬¬È­;NñÆo X,Šø•Eÿl6C0D§ÓÁx<– Búo%n`ZPºÂM¿³³ƒçϟ w’¾õl{,›:-³dˆ ŽF#ñ!mkÙ_d9=çaÎÍÍõÛï÷áóùpyyùï5{1šÍü´R©\ܱxä蝋‹ i–ËeL—<ٍ™LF¨E<¥>ý°X§Äb1!y¾óÎ;¸}û6NOOát:ñ¹Ï}ßûÞ÷D¨HnQ3*«kµÅZŽ~¹\–¡ÝL©t:¶··Å²ž„î9a„¹ør:DfÁêêªØYºg;ƒü¾ÍÍMQ~ói? ópÔì`0€R©ÄÉɉ¸óv»]ôû}I{i…À öh4 +Fƒ?ú£?ú„C§Vãý÷ßG©T” [ö.)ñà­T(àt:qíÚ5ìîî +dÿýï¸}û6Þ{ï=ñwd£ž“Åb}ëoúxF#¡N§›Í&Ýjµ*h%‘ÜN§#³Ÿ—7OF™Z³œš.±Ù®àå÷žL&xe³Y„B!üßØjœÐv$A­VÃêê*†Ã¡xA«vtt$b>½^/1AŒåS‚Å?5I\MÂ0sýe^£ÑˆP(„·ß~÷îݓ¹¾¾ŽT*…üàB²e h7@û3ׯ½öæó9úý¾<øåF&9pkkkÂE¬T*’JFܽ{™LÅbñŠ-¹ÍfC<Ý×ññ±˜ö0˜Ïç(‹ÂvÉçóðù|¢îV«Õøàƒ®Ô*¬ÉȓT«Õxòä‰h 8M’òšå°X,†x<“É„/~ñ‹Â`/‹Ò¬w»Ý°Ùl¸¸¸Ù¾×ëýoé"Ä +…þöoÿNGê§B¡€Ñh„?þã?Æp8”´Z¯×KíI¿G:Ÿ!—ËáââápXâV«…·Þz ƒÁ[[[Øßߗøòwa“<þüJª¨P(„äëõzqrr‚h4ŠN§s%í£ºšœUÖ~ñx\tuõz]ÔÝÝnWÔ¿îþP–äµ9 Ç¥'A×Ør¹ •J%j\.NûX6ž\þñÅb¯¾ú*Âá0n߯–& IDAT¾étŠGÉàÿøÇ¢\žL&XYYÁüÁ  + ªöꫯJšDuíêêªþ·Z-!»ŽF#lmm! +a6›!™L"ŸÏÃjµ"•J]éq@^,“áuÝJÙ>{läÑQ¤JR±XÄÙٙ Ácó™T 6j9c+•JI¾NÁà§)Bd}8Q“yÀCŒMf…B! +nzgºÝn¼ýöÛðx<‡Ãè÷û¢1£â—Œ‹Å‚D"¯×+ úåC’é¢×ëÆÌo¼@ |M4ívétZ4bOÞ¸q{{{x÷Ýw‘L&…3Øï÷EþÔét`2™DûÅþ']†Ãa, ©å?Í]díùúë¯ãÁƒ’5ðÙQû×ívQ.—Q«Õppp ZC¶ŠàääDÌ}˜ùüÚûƒ­„à™¿rî/;õ$„r’ ÙçdqP†¾|º¢5™LBÁùÆ7¾ ŸÏãââ·oßÆÑÑ +"‘¶¶¶ðÏÿüÏbÖòÚk¯áìì ÉdRš€‘HOŸ>ŠõW+++÷’Çæõz¥®zòäÉ£ +<)Ž,•J8??¿"6eÚțƒ·>ÿ™ô7ÞxCܱXøó&bnyJ ½E–©cË2ÊDŽežý<Ȥ™N§R¤ƒA1+b¯‹Òétâðð———0›Í¢Ã#âóùD·|H’SÈÚëöíÛøìg?‹b±ˆóós‰G4•1K¸>þp:’BôÑGâ§È>×l6ÃG}‹Å‚ñx,uk\Þ<€çϟËùet‘1& u43(–&óù\²ápˆÍÍM”ËeܺuKRQ¦³üÿ¿éþP“Ä»ì=žH$®8Q&Ïi‚$¶Ò#‘éÚòD滄¾™k3ƒ¢Cóx<ÂõbÁúà‡?ü¡äõù|ÿò/ÿ"´£ƒƒ8ܽ{ÑhT +S‚cqNOO¯˜x²QKGZš‘rEq&óxJ)8„·¬Á`q=Ëu&å0³Ù n·[Ná½½=iz//’åúb™Áð7ó7ØßßÇ÷¿ÿ}looˈ£¯|å+âFT“uH0D2™„Á`@¡P2‰HàÉ°§X–àÍ2]‰Äh4;w ññÇ‹MœÉdÂÉÉ ?~,-Š>úN§ׯ_—  »V«I¯Œ5æT*u…©â÷û1ŸÏRO$â±ÉóòM6¥eÃì€1ãÉxUòøñcÇ8¤ƒSs‚Á ŽŽŽ’ÿMö‡šìú ƒh·Û˜L&²H:r¹œ°)R©”(K}>Ÿ°+–ƒ¤×ë…SF X,ŠE×l6“éö‰D+++ÂuËår²èÊûþûï ¨ÛíâöíÛ 0™Lâ7o±Xp~~.'R>ŸG"‘@6›½Ro®3 „ŠåóùP«ÕD`j·ÛÑn·áv»¥%@_½Z­§Ó)è%½þ írr +‘/§Ó)Dgҝ(åù4]©Tpýúué÷üõ_ÿµ ÊS(ˆF£bJD.•JI­Kç䋋 ¤Óilllu*“ÉHL ÖÐ\v¦ÔŸñ(•JR§ñ;>~üf³ÛÛÛèt:ØÝݕxð÷x<KÂ~&“ nܸ!Ên >ŸétZ@,ö5].ž>}z…ô@^+¹L º]^^Ân·‹·?g5°ßåt:dy°X,‡¥¶üMö‡: ›Í +»¡X,â3Ÿù ’ɤäç×®]çY^rpª_t“qÁìîîÂd2ɬ^zø-ç¯øMÊÔb±@:F(’ÓÔl6ceeEЦeÿs +!«Õª è÷ûˆÅb8??G2™£¦n@@,íŒF£¤UG<™rµZ­OF“þºÏç^ÐÎí·û·ú5™L’š’˜|~~•J¯×+sèÀ^®ù̕J%ñ­o}K¸xjµ¯¼ò +’ɤ¬é‡á÷û…ÅÂÙ\´WcÚÅѬ¼)³Ù¬X#}Ú®›Ï–õ7u‡œ³LíÓjº(—J%!7Óä‡ ™¤^~'Xä4Òº`_ HF£<ßgϞý7ôÖÖæó¹hÜÖ××Eâ¤×ëq~~~ås鵇¥ÇÈç•J¥„:F£_w¨¹k94W -½®]»&·MµZÅÚÚ¢Ñ(2™ŒðÀ8³‰Þ{|Ñä…óÏø y’ü?íYSÛé™öobЊ$$@ƒñ†ín·S§&NW¥jªf¦æd²U–“|¾A*‡ù"ÉA*©¤;®ôô¤Ûv³X€¬]BB BìzÞù]%œdÞtú=¢ðQ¯¶Ðóÿ?ÏýÜ÷uý.jbæ?´¬‡ÍÏÏ["‘°_ýêW¶¼¼lóóóHrÒ|hfvi=ü~¿Æð;Øx|>ŸÆ ‘HDšÑ££#٘ü®á¤zÓ´‰¨wyyYœM QlÅP݇B!EI=}úT´+”úT _õýpüøÇ?^Íçó—r¶À¯ŸŸ×fãv»56ù[ëö ·ÒÙÜÜ´f³iËË˚±ñÒÐlà3ãà&ƒ¬÷N®y4àÝ ü¢Ú€Â¨àððPò1bj¿êûџN§eÁ =…¥!‡mnnN"–mNZÊLÝ{ÂÞ›¦Ói5.€bÞ¾}ÛÂá°:@xŒFFFlmmÍJ¥’ýö·¿ÕΊŒ¡",F”„HàSë»\.k·Û–H$. ¢{[¶˜ý¸Çäóy+•Jvrrb›››2B &L{ ‰DdˆÅÊ–ú¿·TäÄ!–•õ@ÝM) +…*­×ëb% ˆ¦Ä¬n||ÜÆÇÇ­Ñh¨s:22¢î"âçÅÅE•÷üB5??oñxÜ&''í£>²õõuÛØØ\hppÐjµšÖƒ\jփTP^ÜÞ¸Ñï~÷;EYMMM™×ë•A—áX¼Þ_N§Sw9þ=(žÃ`0hù|^ +փ,ìb±x Ýpvvfÿ?ޏvÞW¯^i—&Êív[,ÓîóùÔaCPÊüÀétÊÌØûƒ³±¸$h”J%í(N§S`Ô±±1iÔÎÎÎ,ÛÙٙ•J%ÕĔę҉k·ÛºÄ·Z-5$(_Ù­#‘ˆÍÎÎ +§Ì †ZÃívkþ·¿¿oápØÖ××ÍétÚ½{÷d΄`Ûn·•2I3ÀëõÚÔԔ(K +Šò"râ¿ùkssSJ·Ûmù|ÞÂá° ÿ¯õàI&“"CE"1JºÝ®0ÝtÏÞtÓlB­Aö6/{¡P°ééi½œ¨aÊå²Ý½{×Tbñàõ6Å°ñ‡B! ™Ýn·†Ê”á̹`N}Ó´‰^pppÐ^¾|)[ +ùxŸÏ€Œ§œL­VËb±˜† ëëëò°Q~Ñγ{÷îi¦Ó{z0T><<´Ç›Óé´z½.Ç.˜7×N"<6‚½½==Hx¹Ó°› +=½•Èéé©mllèŸ3À¦Œs8šsmmmÙáá¡P ñx\0ÑÞö=φËåX––;Š÷óósÉ´zטRïݟ± +˜AHb„òðÛÙÙ•Šþ³Z·Ûm+++šâOû*ïëÑ?;;k[[[æt:-‹i·Åb–L&ÕR/•JÂjÑí"ûɛ6Ôì´¾IsAè٠觃599i‘HDÌ<” Á`Pª"l+•ŠvlÇc[[[Öh44: áÁé477§ShrrR ¾ RVÚí¶Íü·”P(͙ót»] {ùË_ênùÙgŸY©T2§Ó©Ÿóüü\.m.Ͻs20i³³³’nÍÎÎÚææ¦Z__Ÿ•J%ÜÉnÇk‡ª‚4¸NG%Z$Ѭ¨P(\’+áóûýò3óÊår–L&5ô†çQ©T$4ðûý’U“ë½N0òƒj߇B!¡¿éNCñe{Sô@W‘n/–\Ð¥RIÅ/^È×Ƚ½ÛíJȀ§ŒÍý}?z×£Œ6í`EÍfÓnܸ!hã͛7Íív[6›µl6k>ŸOe.dù½¿PࣂïÇ ;;ÆÉ`0h>ŸÏ\.—°c”(wîÜ1§Ói}ô‘vóããc[XX°n·k¯^½RÐ@žÞÝÎívÛüǘËå²7nX©TÚ›M³Ù¼Ôbž7>>n¯_¿V{†󚽽=™)£Ñ¨²­¡d}öÙg2.,,Øøø¸ýñ@³·YD÷æ·Ûµl6k¡PH;ø‚<^(8z!±”2Ìuô]Äz´Z-k·Ûz1z…·l€”êÒҒœœX:õybbBÐÙ­­-Å`õ"Ø،¹#“F‰ˆ’‚çn?X+½¿xø!G§R)K¥RRœüùÏ։åv»UØòò²MMMٟÿügUŒ6þÑ÷£w=`ÞÑmÁÔH4vì"½š°z½n.—˒ɤµZ-K$2U²H~¿_¥b/Ñ‚R__ŸE£QQ_Ab³ Œ©u\.—­ÛíÊbÂωÑëõZ2™´t:métúñ + ÕîËeµéÏÏÏ-JÝl6e’d8‹ öääD TÒAã€¾µµeÃÃòƒ`‘Á$é÷û-›ÍÚÎΎ +-Jï%ž».É0X*âñ¸fZ”J¼ d5ûý~Ù<<år9´7n\Šx¢B@Ñ+=덷­Õj–H$¬¿¿ß²Ù¬:y¢T¥R)óûýq€:Ïd2J²U÷š\o8âòupp qL.—»ôÑ½½yó¦¼w¬ ê½zU̔gggòmË8 ^¯k~÷eߏ7×c ‹ÙgŸ}f‡‡‡ +…ìáǖH$„Ñ¢”á®@Ë·ëþðͯzUÔô}}}Òye³Y8¢Éۚ˜˜PûøèèÈîÝ»g©TʊŢMOO[¹\V§,r>Ÿ7§Ó©Å£>N¥R—fO”–¥RIò™?üPô½{÷TwS.î€l«× +“H$¤yÓ6ƒÄgjjÊ666Ô ‡ÃÒ +f³Y{ñâÅ_@:qjg2±™™s»ÝöâÅ u7éàú|> ƒ¢bqÇèÈ]T@/½¦jú—/_Z©TºtcýèÇãqk4–ËåÔЈF£RÏ3·Tî6á|kkk²!õ~_$UÆb1Ù_¶·· "„Âápˆ¸½½-Fïïåt:­X,*•'›Í^zIãñ¸}ñÅ*Açææ”8va||\ž³¥¥%k·Ûö¼D{±Ž[·n­ Ù‚ŒŒX¥R±ÝÝ]Ío˜}y<ÛÜܔ>+•JY©T²µµ5ÛØظôÀÑ!óx<²iËÅÀ–/w †€Ì0Pàƒ¢ì!yü,Œt:ý‹‰D´Ðh4”Cˆ!wF~Næ]ü.—ËööölßþøÇ?Z2™¼T®€#ácxxXFIû ÏÏÏíùóçöêÕ«¿Øgx<¥—¼xñÂ^¼x¡q­ï™™+‹¢ë +²p8¬!.ÆS,ŒH­I¥RöñÇÿ5¥\ 0Çcù|^ó*Æ+4@òù¼Z„³Ù¬ýéOÒÙ+kC|Ôu$ºZ­Jqr0—ËÙÚÚÚ%W;ê :z|xÈèXE˟ 'êþª¯V«e;;;öeÞÔ=ù|^ë1@§fvvVü§OŸênïýøøØâñ¸°}}}¶¾¾.–n·k£££Z|èTGGGJ$ ‡ÃÖjµleeEI“ÐiA—J%›žž‘™æHßñxÜ^¼xa_ûÚפ ¨ÕjæñxtBòbÞºuëR¶u¹\ž€Y +»'‚h4*åÿþþ¾Œxœ¨4`’`ù¨V« mggG³¼MÌjh¢°À‡Ã¦¦¦Ìãñؓ'OdÏùÏÿüOûä“OÅåeeE6 Ô6©TÊB¡6‰b±x oÆÅû 9ÖR¿àS‹F£ìîîÚ[o½¥Nr¿-//[4MÌ^¹\VìÒÙٙMLLˆ‡áñxô¼„Ãaóz½699©—ŒT¡L&c·oߖ¢(•J]8ÓÈà4"ó€ö‡jäCC…® b‚l6+d›†ÌT*¥´Ò/ó~°™òYR©”9~úӟ®NLLØÇl‡CmmŽÞ`0(é’'¾¨jµª{§–ÇãQª&;<÷­““Eðt»]«V«¶°° ™öjèÑÑQiÿ0-F"‘K0ö/..ì­·Þ²b±(‰N,³±±1]èévñ°‚ï^\\T›øõë×xCf£9@®ðÔԔPe$¢„B!)_¿~­&w„Ÿüä'Ößßo‰DBJ³×ëµÁÁA•t{{{:Aéüö–ß$µ’˜‰î±V«™×ëµÅÅEѾFGGíóÏ?·\.g vxx(|Ò¾³³3¶••{ùò¥}™÷ƒÆ§ùÅŅ9nß¾½Úét4`ˆFc‚Á%ìz˜$\°3¼õÖ[v÷î]»¸¸°¥¥%»sçŽår9ã8]ŽŽŽlkkË<<:årYÁ {{{ÇÕ¤”›™™Ñ‘WŒÏ…ä†Ùð>; Õ‹‹ ‹Åbr.OOOÛÑё”åøˆ°%ì­ÓéØþþ¾ƒA‘ª@•ÑU}çwìââÂö÷÷u!¥“ÙÐää¤ÿ½ÙØKKKò5‘á i ¿„-îR4~þÚzT*»yó¦5›M JyáäÞ»œô˜Ri&0 s8š}"Øm·Ûö駟ڻᆱ{Ûÿ¶˜1‘â@/•Jò÷Ä| Á8 ™m=¸~0°>>>¶Ç [7==mÝn÷¯®Ç?ò~ô®‡ãɓ'«üM¹\¶ÃÃCåf¡ºFÝqtt¤K"`âRÛí¶ìú¹\Îîß¿¯Ë*ô&äÿP‘Úí¶0Ù^¯W¤')e1ÀÕëuI”B¡B顨xöì™ [6›•âbppP‹†M¦7ëøø¸% Qˆé^ÑiŠF£¶»»kív[§®Ï瓉!, I0Ø<’ɤÅãqóù|öêÕ+»uë–.ô€e(ÅQƒ€³kµZÇ…F@Q©T„sèS`LÌçóöàÁƒK˜pdeÃÃò֠å㞊•a:P$²˜Q¹ ¤§‰‚5ɳgÏlddäïZéàÜn·Ö·2°ßïWb£‰¿µccc6::*$ÖëׯõŒommÙòòò% ª/û~ô®‡ã?øÁêÚښáæççՙ +…B²œ÷֘øjðQkÎ:==µX,¦öf«Õҋ‚ÎÃâ^·0¡z¢¸tú|>Í>°VÐ%üàƒÔ­CkÈðüZ¥R•ùRµZU{˜[NeþÝÄĄJ +.Û|”a4isʏY4Uøß͛7mmmͦ§§m}}Ý|>ŸTù‘HÄÖÖÖTÎý­õh4Ò>b¶d=賌-€ïÐðøßփv>.3Ì^êoïz  ¥ùÓív¿òz€` „SçW]z‹‹‹¶¾¾®õðûýj¸°_öýè]Çw¿ûÝU ‰maaAG4júJ¥b‡‡‡ + †cŽˆÙ5/AÖ¨“3™ŒMMM©•ÇÍårÙÚښëÈ200 »\¿$Wù|Þ"‘ˆ2±ˆ2=99‘à“ ¯¤%üD½ßՁ8ÀށøââB-|JšL&cwîܱóós5-@°£Á„÷x<¶¼¼lµZMߕËå²Ï?ÿ\vy†Ù×ëquÖÃ199¹ŠQìàà ÂÀ}>ŸôrÝn×~ýë_K~Ã.¨™ÆÕIDATÐÍëõŠîK‡…úždLZ»dôâqBõžN§U6ré$B”ŤnO¥R:žéƒAk6› +xcøMH]<؂½¡ñØ€s2sAÉ.ˆyx×jµªpAÔÌ©PŒ ¦ ښ…R©d»»»æp8ìÙ³g¶¶¶¦Ü³ëõ¸:ëáøÆ7¾±zpp`7oÞà‘#–äp^­VKR§ÅÅEé™± Qr¹\R«ß¸qü^¯Ž\”äyÑ=±‰‰ ‰‚Ùˆ‚©NšQ¿ÝºuK^ µµ5 A³Ù¬þߙ™]¦=æ^½æ>\ÙápXêï³³3•’K{ñ¸[Âqìt:–ËålqqÑnÞ¼i}ô‘Ô/[[[º˜'“I«T*6;;k>ŸÏ>ùäá®×ãj­‡ã»ßýîj/”|0´ééiù­Ø ;ŽÍÏÏ[__ŸKõ^™ >Lò´¦¢¦ÀƁÿ‰‹ÿá᡾,À$0ïP6›M)E- +’f%“I«Õj‰Dìøøø’¶òòñ›¹ÃÔøÐ`ý~¿2€{Cé€_â$@–lggGƒÐjµjñxÜ&&&ì¿þë¿ìèèÈâñ¸4tç°Á\¯ÇÕYÇw¾óUZäänÁt§LÀJ¢ÑhX©T’‚–‘¢ Èår +Å]«ÕäÇ¡³„ݝݶCZˆºLóù¼ÍÍÍÙÌ̌J$[•JŶ··íƍâ‚`íGغ³³£ðt´et¥ÊY8V}Ïð¼ÓéHU͔ŸîW4µv»­NXî±±1ÛÞÞÖ]¤¿¿ßÆÇÇíððPˆ¸¡¡!\àgU‡-åz=®Îz8ž>}ºê÷ûUcÖëuiܘO9NÛØØ°ƒƒ!Ԙ“¸Ýn)’00 {@¯8õôôT¿7_2–J5Ç£Yäb†»ããã +’»^«³Žÿ÷_­×ë’Ó RÙË4$g7‹©Ì˜žž¶Ï>ûÌFFF,HlI}Mö1ÆG šÔøÁ`PÙYÌ'P5c〥xrr"z®Û햤ˆ.£¨¨÷öö,‹É͊ÀJ1Ÿ› j‡b±hÙlÖÊå²ÍÍÍɲ¿ ýd±X‚®¤,Z×£££æt:¥&èÍQÛÃr¼^«³Žý×]å>??×Àb¤ÓiÙB…P·Ã«p»Ý644d…BÁFGGíààÀb±˜h=gggŠ6eC; 4^¢HŠÎð™ +…‚Õëu›™™‘L†¬âF£aÇÇǍFE=Bƒ·´´¤äÏD"!fæóyµ—Q>…O‹¼/Ï̬P(X$уË}¨Ûí*õ£ÕjY«Õ’Ï ˜ ì‹ëõ¸:ëáxÿý÷W1!âP˜˜!µ<‹‹ÅÌáp(/ ܾœíím”cl£s}‰<+v D¥ØÒq`÷š8É8æR wèSZÐcccr`%á³ãØ4ƒ£ÜZ>Ÿ7·Ûm"á|mµZ +…„7s»ÝÖét,N+ vúýû÷¥(²½½=K¥RŠiÂAÌŠ-ãëõ¸Zëáx÷ÝwWÙÝ:Ž¥R)±+ø ìf_¿~m‘HDA১§V«Õ¡v¦Cû-e :;f )'&&d7sÅy·Û•G«^¯[<·r¹,a1¨m>7ž) ¨ÌgÍÎΊx +"¦FhkµZUÍ jÎ<ùññ±,<b‘$ q(|>Ÿ~Žëõ¸ZëáøḚÉdlwwWrb±(`ðþýûV¯×ÅJàH„C»jnŽZ”Ø|q`¾¼^¯lX.\.—.½ü>ÃÃò͓Õ íÜßßWZýÑё˜ Þ°«“ƒª» BU,Ü 0!òsPhHK›Ðsî(иÎÎÎìÝl6-*Ša)ÿ}:¶H$b×ëqµÖÃñäɓÕ\.'U@2™´`0(¼×Ö֖þšé;"Êóós햄RÓ¶ÅóÃ̑Nˆ9󗓓µmÐPÎà?#èûLPp;;;Ë øN§ÓÖh4t™6›Í*Œ$özœ¼õzÝæçç•f‚º«G8S±^¯Ëå÷û­R©X$ƒ‡ùüü\UýP›hg³Y»^«µŽï|ç;«·nÝcáöíÛr·f2›˜˜° î0£¥Ói+ +Š "œv&íM¢ˆ(èÈD£Qk4ò…Ãa[XXPÈD¯€‹ËåÓæü ½J¤œ ÀFxJîï½{÷l}}]vvKêê±±1Ëd2ÔÀÂh4 +êBJè:,óóós;;;“Ö5H4ÈL\ÔI]á3ÀŠՒò# Z,³ßÿþ÷ffV*•”ê922¢ÈXÑ×ëqµÖÃñ½ï}o•YC>Ÿ—}š8"Ó蟷‘‘u¤èXa$A%üß<ßÿz<[YYQÇhppP*¬ôÀ¡U* ƒÇ-™LjwëÅi#²ñ •Ü,hÀï¼óŽ×ëqµÖÃñoÿöo«;;;‚uîííÙúúº¹Ýn¥g0ÔD&S©T´s`ý&*>")333ff–H$´H'''ò7Qÿf2ï‘w¼»»kvãÆ á¢¡ø²«–J%ÙÒ].—>/‰,\äA(cV¤íœL&ÍápÈUKH*pf6ÙlÖNNN¤0@žÔn·-‘HØÒҒˆÅ@V¹ƒµž˜˜°íím¶¯ýërâ’4Ã\æz=®Özôýüç?ïÂ-8??חð\¢Ä5›M»}û¶‹Ek4aW€©W¯×-“ÉØ«W¯ìɓ'Ößßo~¿_åž'j~ÂêHí¤Ü™ššRkÚåréKæB^(¤#cÒOØs\³p'ì [­V“ØùN(RÖñìì¬íììhG¤Á@ô-ô‘HćÐkƒƒƒ6==mûûûb­ó]ƒ¤¦Ä¶f³i×ëqµÖÃñÞ{ï­ö’„°O×j5ËçóB “ŠQ©T¤Ì†¼…¤ çŠÅ¢•Ëe›˜˜°ùùy)ÄÝn·hF쀔ކ††¤gCKÇ•º¯¯O‰†Ð„HžžžZ4Y í._¯×+Í"¨jZߝNGVy8¸l ;@ +ôüùsóz½ +°óz½655%5w&“[ãôôTv¹¹9ùµ &_¯ÇÕZÿdDÿÚ³{VIEND®B`‚#!/usr/bin/env php +# autogenerated file; do not edit +sudo: false +language: c + +addons: + apt: + packages: + - php5-cli + - php-pear + +env: + matrix: + ["master"], + "enable_debug", + "enable_maintainer_zts", +]); +foreach ($env as $e) { + printf(" - %s\n", $e); +} + +?> + +before_script: + - make -f travis/pecl/Makefile php + - make -f travis/pecl/Makefile ext PECL=raphf + +script: + - make -f travis/pecl/Makefile test +/* + +--------------------------------------------------------------------+ + | PECL :: raphf | + +--------------------------------------------------------------------+ + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the conditions mentioned | + | in the accompanying LICENSE file are met. | + +--------------------------------------------------------------------+ + | Copyright (c) 2013, Michael Wallner | + +--------------------------------------------------------------------+ +*/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include "php.h" +#include "php_ini.h" +#include "ext/standard/info.h" +#include "php_raphf.h" + +#ifndef PHP_RAPHF_TEST +# define PHP_RAPHF_TEST 0 +#endif + +struct php_persistent_handle_globals { + ulong limit; + HashTable hash; +}; + +ZEND_BEGIN_MODULE_GLOBALS(raphf) + struct php_persistent_handle_globals persistent_handle; +ZEND_END_MODULE_GLOBALS(raphf) + +#ifdef ZTS +# define PHP_RAPHF_G ((zend_raphf_globals *) \ + (*((void ***) tsrm_get_ls_cache()))[TSRM_UNSHUFFLE_RSRC_ID(raphf_globals_id)]) +#else +# define PHP_RAPHF_G (&raphf_globals) +#endif + +ZEND_DECLARE_MODULE_GLOBALS(raphf) + +#ifndef PHP_RAPHF_DEBUG_PHANDLES +# define PHP_RAPHF_DEBUG_PHANDLES 0 +#endif +#if PHP_RAPHF_DEBUG_PHANDLES +# undef inline +# define inline +#endif + +php_resource_factory_t *php_resource_factory_init(php_resource_factory_t *f, + php_resource_factory_ops_t *fops, void *data, void (*dtor)(void *data)) +{ + if (!f) { + f = emalloc(sizeof(*f)); + } + memset(f, 0, sizeof(*f)); + + memcpy(&f->fops, fops, sizeof(*fops)); + + f->data = data; + f->dtor = dtor; + + f->refcount = 1; + + return f; +} + +unsigned php_resource_factory_addref(php_resource_factory_t *rf) +{ + return ++rf->refcount; +} + +void php_resource_factory_dtor(php_resource_factory_t *f) +{ + if (!--f->refcount) { + if (f->dtor) { + f->dtor(f->data); + } + } +} + +void php_resource_factory_free(php_resource_factory_t **f) +{ + if (*f) { + php_resource_factory_dtor(*f); + if (!(*f)->refcount) { + efree(*f); + *f = NULL; + } + } +} + +void *php_resource_factory_handle_ctor(php_resource_factory_t *f, void *init_arg) +{ + if (f->fops.ctor) { + return f->fops.ctor(f->data, init_arg); + } + return NULL; +} + +void *php_resource_factory_handle_copy(php_resource_factory_t *f, void *handle) +{ + if (f->fops.copy) { + return f->fops.copy(f->data, handle); + } + return NULL; +} + +void php_resource_factory_handle_dtor(php_resource_factory_t *f, void *handle) +{ + if (f->fops.dtor) { + f->fops.dtor(f->data, handle); + } +} + +php_resource_factory_t *php_persistent_handle_resource_factory_init( + php_resource_factory_t *a, php_persistent_handle_factory_t *pf) +{ + return php_resource_factory_init(a, + php_persistent_handle_get_resource_factory_ops(), pf, + (void(*)(void*)) php_persistent_handle_abandon); +} + +zend_bool php_resource_factory_is_persistent(php_resource_factory_t *a) +{ + return a->dtor == (void(*)(void *)) php_persistent_handle_abandon; +} + +static inline php_persistent_handle_list_t *php_persistent_handle_list_init( + php_persistent_handle_list_t *list) +{ + if (!list) { + list = pemalloc(sizeof(*list), 1); + } + list->used = 0; + zend_hash_init(&list->free, 0, NULL, NULL, 1); + + return list; +} + +static int php_persistent_handle_apply_stat(zval *p, int argc, va_list argv, + zend_hash_key *key) +{ + php_persistent_handle_list_t *list = Z_PTR_P(p); + zval zsubentry, *zentry = va_arg(argv, zval *); + + array_init(&zsubentry); + add_assoc_long_ex(&zsubentry, ZEND_STRL("used"), list->used); + add_assoc_long_ex(&zsubentry, ZEND_STRL("free"), + zend_hash_num_elements(&list->free)); + if (key->key) { + add_assoc_zval_ex(zentry, key->key->val, key->key->len, &zsubentry); + } else { + add_index_zval(zentry, key->h, &zsubentry); + } + return ZEND_HASH_APPLY_KEEP; +} + +static int php_persistent_handle_apply_statall(zval *p, int argc, va_list argv, + zend_hash_key *key) +{ + php_persistent_handle_provider_t *provider = Z_PTR_P(p); + HashTable *ht = va_arg(argv, HashTable *); + zval zentry; + + array_init(&zentry); + + zend_hash_apply_with_arguments(&provider->list.free, + php_persistent_handle_apply_stat, 1, &zentry); + + if (key->key) { + zend_hash_update(ht, key->key, &zentry); + } else { + zend_hash_index_update(ht, key->h, &zentry); + } + + return ZEND_HASH_APPLY_KEEP; +} + +static int php_persistent_handle_apply_cleanup_ex(zval *p, void *arg) +{ + php_resource_factory_t *rf = arg; + void *handle = Z_PTR_P(p); + +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "DESTROY: %p\n", handle); +#endif + php_resource_factory_handle_dtor(rf, handle); + return ZEND_HASH_APPLY_REMOVE; +} + +static int php_persistent_handle_apply_cleanup(zval *p, void *arg) +{ + php_resource_factory_t *rf = arg; + php_persistent_handle_list_t *list = Z_PTR_P(p); + + zend_hash_apply_with_argument(&list->free, + php_persistent_handle_apply_cleanup_ex, rf); + if (list->used) { + return ZEND_HASH_APPLY_KEEP; + } + zend_hash_destroy(&list->free); +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "LSTFREE: %p\n", list); +#endif + pefree(list, 1); + return ZEND_HASH_APPLY_REMOVE; +} + +static inline void php_persistent_handle_list_dtor( + php_persistent_handle_list_t *list, + php_persistent_handle_provider_t *provider) +{ +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "LSTDTOR: %p\n", list); +#endif + zend_hash_apply_with_argument(&list->free, + php_persistent_handle_apply_cleanup_ex, &provider->rf); + zend_hash_destroy(&list->free); +} + +static inline void php_persistent_handle_list_free( + php_persistent_handle_list_t **list, + php_persistent_handle_provider_t *provider) +{ + php_persistent_handle_list_dtor(*list, provider); +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "LSTFREE: %p\n", *list); +#endif + pefree(*list, 1); + *list = NULL; +} + +static int php_persistent_handle_list_apply_dtor(zval *p, void *provider) +{ + php_persistent_handle_list_t *list = Z_PTR_P(p); + + php_persistent_handle_list_free(&list, provider ); + ZVAL_PTR(p, NULL); + return ZEND_HASH_APPLY_REMOVE; +} + +static inline php_persistent_handle_list_t *php_persistent_handle_list_find( + php_persistent_handle_provider_t *provider, zend_string *ident) +{ + php_persistent_handle_list_t *list; + zval *zlist = zend_symtable_find(&provider->list.free, ident); + + if (zlist && (list = Z_PTR_P(zlist))) { +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "LSTFIND: %p\n", list); +#endif + return list; + } + + if ((list = php_persistent_handle_list_init(NULL))) { + zval p, *rv; + zend_string *id; + + ZVAL_PTR(&p, list); + id = zend_string_init(ident->val, ident->len, 1); + rv = zend_symtable_update(&provider->list.free, id, &p); + zend_string_release(id); + + if (rv) { +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "LSTFIND: %p (new)\n", list); +#endif + return list; + } + php_persistent_handle_list_free(&list, provider); + } + + return NULL; +} + +static int php_persistent_handle_apply_cleanup_all(zval *p, int argc, + va_list argv, zend_hash_key *key) +{ + php_persistent_handle_provider_t *provider = Z_PTR_P(p); + zend_string *ident = va_arg(argv, zend_string *); + php_persistent_handle_list_t *list; + + if (ident && ident->len) { + if ((list = php_persistent_handle_list_find(provider, ident))) { + zend_hash_apply_with_argument(&list->free, + php_persistent_handle_apply_cleanup_ex, + &provider->rf); + } + } else { + zend_hash_apply_with_argument(&provider->list.free, + php_persistent_handle_apply_cleanup, &provider->rf); + } + + return ZEND_HASH_APPLY_KEEP; +} + +static void php_persistent_handle_hash_dtor(zval *p) +{ + php_persistent_handle_provider_t *provider = Z_PTR_P(p); + + zend_hash_apply_with_argument(&provider->list.free, + php_persistent_handle_list_apply_dtor, provider); + zend_hash_destroy(&provider->list.free); + php_resource_factory_dtor(&provider->rf); + pefree(provider, 1); +} + +ZEND_RESULT_CODE php_persistent_handle_provide(zend_string *name, + php_resource_factory_ops_t *fops, void *data, void (*dtor)(void *)) +{ + php_persistent_handle_provider_t *provider = pemalloc(sizeof(*provider), 1); + + if (php_persistent_handle_list_init(&provider->list)) { + if (php_resource_factory_init(&provider->rf, fops, data, dtor)) { + zval p, *rv; + zend_string *ns; + +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "PROVIDE: %p %s\n", PHP_RAPHF_G, name_str); +#endif + + ZVAL_PTR(&p, provider); + ns = zend_string_init(name->val, name->len, 1); + rv = zend_symtable_update(&PHP_RAPHF_G->persistent_handle.hash, ns, &p); + zend_string_release(ns); + + if (rv) { + return SUCCESS; + } + php_resource_factory_dtor(&provider->rf); + } + } + + return FAILURE; +} + + +php_persistent_handle_factory_t *php_persistent_handle_concede( + php_persistent_handle_factory_t *a, + zend_string *name, zend_string *ident, + php_persistent_handle_wakeup_t wakeup, + php_persistent_handle_retire_t retire) +{ + zval *zprovider = zend_symtable_find(&PHP_RAPHF_G->persistent_handle.hash, name); + + if (zprovider) { + zend_bool free_a = 0; + + if ((free_a = !a)) { + a = emalloc(sizeof(*a)); + } + memset(a, 0, sizeof(*a)); + + a->provider = Z_PTR_P(zprovider); + a->ident = zend_string_copy(ident); + a->wakeup = wakeup; + a->retire = retire; + a->free_on_abandon = free_a; + } else { + a = NULL; + } + +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "CONCEDE: %p %p (%s) (%s)\n", PHP_RAPHF_G, + a ? a->provider : NULL, name->val, ident->val); +#endif + + return a; +} + +void php_persistent_handle_abandon(php_persistent_handle_factory_t *a) +{ + zend_bool f = a->free_on_abandon; + +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "ABANDON: %p\n", a->provider); +#endif + + zend_string_release(a->ident); + memset(a, 0, sizeof(*a)); + if (f) { + efree(a); + } +} + +void *php_persistent_handle_acquire(php_persistent_handle_factory_t *a, void *init_arg) +{ + int key; + zval *p; + zend_ulong index; + void *handle = NULL; + php_persistent_handle_list_t *list; + + list = php_persistent_handle_list_find(a->provider, a->ident); + if (list) { + zend_hash_internal_pointer_end(&list->free); + key = zend_hash_get_current_key(&list->free, NULL, &index); + p = zend_hash_get_current_data(&list->free); + if (p && HASH_KEY_NON_EXISTENT != key) { + handle = Z_PTR_P(p); + if (a->wakeup) { + a->wakeup(a, &handle); + } + zend_hash_index_del(&list->free, index); + } else { + handle = php_resource_factory_handle_ctor(&a->provider->rf, init_arg); + } +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "CREATED: %p\n", handle); +#endif + if (handle) { + ++a->provider->list.used; + ++list->used; + } + } + + return handle; +} + +void *php_persistent_handle_accrete(php_persistent_handle_factory_t *a, void *handle) +{ + void *new_handle = NULL; + php_persistent_handle_list_t *list; + + new_handle = php_resource_factory_handle_copy(&a->provider->rf, handle); + if (handle) { + list = php_persistent_handle_list_find(a->provider, a->ident); + if (list) { + ++list->used; + } + ++a->provider->list.used; + } + + return new_handle; +} + +void php_persistent_handle_release(php_persistent_handle_factory_t *a, void *handle) +{ + php_persistent_handle_list_t *list; + + list = php_persistent_handle_list_find(a->provider, a->ident); + if (list) { + if (a->provider->list.used >= PHP_RAPHF_G->persistent_handle.limit) { +#if PHP_RAPHF_DEBUG_PHANDLES + fprintf(stderr, "DESTROY: %p\n", handle); +#endif + php_resource_factory_handle_dtor(&a->provider->rf, handle); + } else { + if (a->retire) { + a->retire(a, &handle); + } + zend_hash_next_index_insert_ptr(&list->free, handle); + } + + --a->provider->list.used; + --list->used; + } +} + +void php_persistent_handle_cleanup(zend_string *name, zend_string *ident) +{ + php_persistent_handle_provider_t *provider; + php_persistent_handle_list_t *list; + + if (name) { + zval *zprovider = zend_symtable_find(&PHP_RAPHF_G->persistent_handle.hash, + name); + + if (zprovider && (provider = Z_PTR_P(zprovider))) { + if (ident) { + list = php_persistent_handle_list_find(provider, ident); + if (list) { + zend_hash_apply_with_argument(&list->free, + php_persistent_handle_apply_cleanup_ex, + &provider->rf); + } + } else { + zend_hash_apply_with_argument(&provider->list.free, + php_persistent_handle_apply_cleanup, + &provider->rf); + } + } + } else { + zend_hash_apply_with_arguments( + &PHP_RAPHF_G->persistent_handle.hash, + php_persistent_handle_apply_cleanup_all, 1, ident); + } +} + +HashTable *php_persistent_handle_statall(HashTable *ht) +{ + if (zend_hash_num_elements(&PHP_RAPHF_G->persistent_handle.hash)) { + if (!ht) { + ALLOC_HASHTABLE(ht); + zend_hash_init(ht, 0, NULL, ZVAL_PTR_DTOR, 0); + } + zend_hash_apply_with_arguments( + &PHP_RAPHF_G->persistent_handle.hash, + php_persistent_handle_apply_statall, 1, ht); + } else if (ht) { + ht = NULL; + } + + return ht; +} + +static php_resource_factory_ops_t php_persistent_handle_resource_factory_ops = { + (php_resource_factory_handle_ctor_t) php_persistent_handle_acquire, + (php_resource_factory_handle_copy_t) php_persistent_handle_accrete, + (php_resource_factory_handle_dtor_t) php_persistent_handle_release +}; + +php_resource_factory_ops_t *php_persistent_handle_get_resource_factory_ops(void) +{ + return &php_persistent_handle_resource_factory_ops; +} + +ZEND_BEGIN_ARG_INFO_EX(ai_raphf_stat_persistent_handles, 0, 0, 0) +ZEND_END_ARG_INFO(); +static PHP_FUNCTION(raphf_stat_persistent_handles) +{ + if (SUCCESS == zend_parse_parameters_none()) { + object_init(return_value); + if (php_persistent_handle_statall(HASH_OF(return_value))) { + return; + } + zval_dtor(return_value); + } + RETURN_FALSE; +} + +ZEND_BEGIN_ARG_INFO_EX(ai_raphf_clean_persistent_handles, 0, 0, 0) + ZEND_ARG_INFO(0, name) + ZEND_ARG_INFO(0, ident) +ZEND_END_ARG_INFO(); +static PHP_FUNCTION(raphf_clean_persistent_handles) +{ + zend_string *name = NULL, *ident = NULL; + + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS(), "|S!S!", &name, &ident)) { + php_persistent_handle_cleanup(name, ident); + } +} + +#if PHP_RAPHF_TEST +# include "php_raphf_test.c" +#endif + +static const zend_function_entry raphf_functions[] = { + ZEND_NS_FENTRY("raphf", stat_persistent_handles, + ZEND_FN(raphf_stat_persistent_handles), + ai_raphf_stat_persistent_handles, 0) + ZEND_NS_FENTRY("raphf", clean_persistent_handles, + ZEND_FN(raphf_clean_persistent_handles), + ai_raphf_clean_persistent_handles, 0) +#if PHP_RAPHF_TEST + ZEND_NS_FENTRY("raphf", provide, ZEND_FN(raphf_provide), NULL, 0) + ZEND_NS_FENTRY("raphf", conceal, ZEND_FN(raphf_conceal), NULL, 0) + ZEND_NS_FENTRY("raphf", concede, ZEND_FN(raphf_concede), NULL, 0) + ZEND_NS_FENTRY("raphf", dispute, ZEND_FN(raphf_dispute), NULL, 0) + ZEND_NS_FENTRY("raphf", handle_ctor, ZEND_FN(raphf_handle_ctor), NULL, 0) + ZEND_NS_FENTRY("raphf", handle_copy, ZEND_FN(raphf_handle_copy), NULL, 0) + ZEND_NS_FENTRY("raphf", handle_dtor, ZEND_FN(raphf_handle_dtor), NULL, 0) +#endif + {0} +}; + +PHP_INI_BEGIN() + STD_PHP_INI_ENTRY("raphf.persistent_handle.limit", "-1", PHP_INI_SYSTEM, + OnUpdateLong, persistent_handle.limit, zend_raphf_globals, + raphf_globals) +PHP_INI_END() + +static HashTable *php_persistent_handles_global_hash; + +static PHP_GINIT_FUNCTION(raphf) +{ + raphf_globals->persistent_handle.limit = -1; + + zend_hash_init(&raphf_globals->persistent_handle.hash, 0, NULL, + php_persistent_handle_hash_dtor, 1); + if (php_persistent_handles_global_hash) { + zend_hash_copy(&raphf_globals->persistent_handle.hash, + php_persistent_handles_global_hash, NULL); + } +} + +static PHP_GSHUTDOWN_FUNCTION(raphf) +{ + zend_hash_destroy(&raphf_globals->persistent_handle.hash); +} + +PHP_MINIT_FUNCTION(raphf) +{ + php_persistent_handles_global_hash = &PHP_RAPHF_G->persistent_handle.hash; + +#if PHP_RAPHF_TEST + PHP_MINIT(raphf_test)(INIT_FUNC_ARGS_PASSTHRU); +#endif + + REGISTER_INI_ENTRIES(); + return SUCCESS; +} + +PHP_MSHUTDOWN_FUNCTION(raphf) +{ +#if PHP_RAPHF_TEST + PHP_MSHUTDOWN(raphf_test)(SHUTDOWN_FUNC_ARGS_PASSTHRU); +#endif + + UNREGISTER_INI_ENTRIES(); + php_persistent_handles_global_hash = NULL; + return SUCCESS; +} + +static int php_persistent_handle_apply_info_ex(zval *p, int argc, + va_list argv, zend_hash_key *key) +{ + php_persistent_handle_list_t *list = Z_PTR_P(p); + zend_hash_key *super_key = va_arg(argv, zend_hash_key *); + char used[21], free[21]; + + slprintf(used, sizeof(used), "%u", list->used); + slprintf(free, sizeof(free), "%d", zend_hash_num_elements(&list->free)); + + php_info_print_table_row(4, super_key->key->val, key->key->val, used, free); + + return ZEND_HASH_APPLY_KEEP; +} + +static int php_persistent_handle_apply_info(zval *p, int argc, + va_list argv, zend_hash_key *key) +{ + php_persistent_handle_provider_t *provider = Z_PTR_P(p); + + zend_hash_apply_with_arguments(&provider->list.free, + php_persistent_handle_apply_info_ex, 1, key); + + return ZEND_HASH_APPLY_KEEP; +} + +PHP_MINFO_FUNCTION(raphf) +{ + php_info_print_table_start(); + php_info_print_table_header(2, + "Resource and persistent handle factory support", "enabled"); + php_info_print_table_row(2, "Extension version", PHP_RAPHF_VERSION); + php_info_print_table_end(); + + php_info_print_table_start(); + php_info_print_table_colspan_header(4, "Persistent handles in this " +#ifdef ZTS + "thread" +#else + "process" +#endif + ); + php_info_print_table_header(4, "Provider", "Ident", "Used", "Free"); + zend_hash_apply_with_arguments( + &PHP_RAPHF_G->persistent_handle.hash, + php_persistent_handle_apply_info, 0); + php_info_print_table_end(); + + DISPLAY_INI_ENTRIES(); +} + +zend_module_entry raphf_module_entry = { + STANDARD_MODULE_HEADER, + "raphf", + raphf_functions, + PHP_MINIT(raphf), + PHP_MSHUTDOWN(raphf), + NULL, + NULL, + PHP_MINFO(raphf), + PHP_RAPHF_VERSION, + ZEND_MODULE_GLOBALS(raphf), + PHP_GINIT(raphf), + PHP_GSHUTDOWN(raphf), + NULL, + STANDARD_MODULE_PROPERTIES_EX +}; +/* }}} */ + +#ifdef COMPILE_DL_RAPHF +ZEND_GET_MODULE(raphf) +#endif + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ +/* + +--------------------------------------------------------------------+ + | PECL :: raphf | + +--------------------------------------------------------------------+ + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the conditions mentioned | + | in the accompanying LICENSE file are met. | + +--------------------------------------------------------------------+ + | Copyright (c) 2013, Michael Wallner | + +--------------------------------------------------------------------+ +*/ + +#ifndef PHP_RAPHF_API_H +#define PHP_RAPHF_API_H + +#include "php_raphf.h" + +/** + * A resource constructor. + * + * @param opaque is the \a data from php_persistent_handle_provide() + * @param init_arg is the \a init_arg from php_resource_factory_init() + * @return the created (persistent) handle + */ +typedef void *(*php_resource_factory_handle_ctor_t)(void *opaque, void *init_arg); + +/** + * The copy constructor of a resource. + * + * @param opaque the factory's data + * @param handle the (persistent) handle to copy + */ +typedef void *(*php_resource_factory_handle_copy_t)(void *opaque, void *handle); + +/** + * The destructor of a resource. + * + * @param opaque the factory's data + * @param handle the handle to destroy + */ +typedef void (*php_resource_factory_handle_dtor_t)(void *opaque, void *handle); + +/** + * The resource ops consisting of a ctor, a copy ctor and a dtor. + * + * Define this ops and register them with php_persistent_handle_provide() + * in MINIT. + */ +typedef struct php_resource_factory_ops { + /** The resource constructor */ + php_resource_factory_handle_ctor_t ctor; + /** The resource's copy constructor */ + php_resource_factory_handle_copy_t copy; + /** The resource's destructor */ + php_resource_factory_handle_dtor_t dtor; +} php_resource_factory_ops_t; + +/** + * The resource factory. + */ +typedef struct php_resource_factory { + /** The resource ops */ + php_resource_factory_ops_t fops; + /** Opaque user data */ + void *data; + /** User data destructor */ + void (*dtor)(void *data); + /** How often this factory is referenced */ + unsigned refcount; +} php_resource_factory_t; + +/** + * Initialize a resource factory. + * + * If you register a \a dtor for a resource factory used with a persistent + * handle provider, be sure to call php_persistent_handle_cleanup() for your + * registered provider in MSHUTDOWN, else the dtor will point to no longer + * available memory if the extension has already been unloaded. + * + * @param f the factory to initialize; if NULL allocated on the heap + * @param fops the resource ops to assign to the factory + * @param data opaque user data; may be NULL + * @param dtor a destructor for the data; may be NULL + * @return \a f or an allocated resource factory + */ +PHP_RAPHF_API php_resource_factory_t *php_resource_factory_init( + php_resource_factory_t *f, php_resource_factory_ops_t *fops, void *data, + void (*dtor)(void *data)); + +/** + * Increase the refcount of the resource factory. + * + * @param rf the resource factory + * @return the new refcount + */ +PHP_RAPHF_API unsigned php_resource_factory_addref(php_resource_factory_t *rf); + +/** + * Destroy the resource factory. + * + * If the factory's refcount reaches 0, the \a dtor for \a data is called. + * + * @param f the resource factory + */ +PHP_RAPHF_API void php_resource_factory_dtor(php_resource_factory_t *f); + +/** + * Destroy and free the resource factory. + * + * Calls php_resource_factory_dtor() and frees \a f if the factory's refcount + * reached 0. + * + * @param f the resource factory + */ +PHP_RAPHF_API void php_resource_factory_free(php_resource_factory_t **f); + +/** + * Construct a resource by the resource factory \a f + * + * @param f the resource factory + * @param init_arg for the resource constructor + * @return the new resource + */ +PHP_RAPHF_API void *php_resource_factory_handle_ctor(php_resource_factory_t *f, + void *init_arg); + +/** + * Create a copy of the resource \a handle + * + * @param f the resource factory + * @param handle the resource to copy + * @return the copy + */ +PHP_RAPHF_API void *php_resource_factory_handle_copy(php_resource_factory_t *f, + void *handle); + +/** + * Destroy (and free) the resource + * + * @param f the resource factory + * @param handle the resource to destroy + */ +PHP_RAPHF_API void php_resource_factory_handle_dtor(php_resource_factory_t *f, + void *handle); + +/** + * Persistent handles storage + */ +typedef struct php_persistent_handle_list { + /** Storage of free resources */ + HashTable free; + /** Count of acquired resources */ + ulong used; +} php_persistent_handle_list_t; + +/** + * Definition of a persistent handle provider. + * Holds a resource factory an a persistent handle list. + */ +typedef struct php_persistent_handle_provider { + /** + * The list of free handles. + * Hash of "ident" => array(handles) entries. Persistent handles are + * acquired out of this list. + */ + php_persistent_handle_list_t list; + + /** + * The resource factory. + * New handles are created by this factory. + */ + php_resource_factory_t rf; +} php_persistent_handle_provider_t; + +typedef struct php_persistent_handle_factory php_persistent_handle_factory_t; + +/** + * Wakeup the persistent handle on re-acquisition. + */ +typedef void (*php_persistent_handle_wakeup_t)( + php_persistent_handle_factory_t *f, void **handle); +/** + * Retire the persistent handle on release. + */ +typedef void (*php_persistent_handle_retire_t)( + php_persistent_handle_factory_t *f, void **handle); + +/** + * Definition of a persistent handle factory. + * + * php_persistent_handle_concede() will return a pointer to a + * php_persistent_handle_factory if a provider for the \a name has + * been registered with php_persistent_handle_provide(). + */ +struct php_persistent_handle_factory { + /** The persistent handle provider */ + php_persistent_handle_provider_t *provider; + /** The persistent handle wakeup routine; may be NULL */ + php_persistent_handle_wakeup_t wakeup; + /** The persistent handle retire routine; may be NULL */ + php_persistent_handle_retire_t retire; + + /** The ident for which this factory manages resources */ + zend_string *ident; + + /** Whether it has to be free'd on php_persistent_handle_abandon() */ + unsigned free_on_abandon:1; +}; + +/** + * Register a persistent handle provider in MINIT. + * + * Registers a factory provider for \a name_str with \a fops resource factory + * ops. Call this in your MINIT. + * + * A php_resource_factory will be created with \a fops, \a data and \a dtor + * and will be stored together with a php_persistent_handle_list in the global + * raphf hash. + * + * A php_persistent_handle_factory can then be retrieved by + * php_persistent_handle_concede() at runtime. + * + * @param name the provider name, e.g. "http\Client\Curl" + * @param fops the resource factory ops + * @param data opaque user data + * @param dtor \a data destructor + * @return SUCCESS/FAILURE + */ +PHP_RAPHF_API ZEND_RESULT_CODE php_persistent_handle_provide( + zend_string *name, php_resource_factory_ops_t *fops, + void *data, void (*dtor)(void *)); + +/** + * Retrieve a persistent handle factory at runtime. + * + * If a persistent handle provider has been registered for \a name, a new + * php_persistent_handle_factory creating resources in the \a ident + * namespace will be constructed. + * + * The wakeup routine \a wakeup and the retire routine \a retire will be + * assigned to the new php_persistent_handle_factory. + * + * @param a pointer to a factory; allocated on the heap if NULL + * @param name the provider name, e.g. "http\Client\Curl" + * @param ident the subsidiary namespace, e.g. "php.net:80" + * @param wakeup any persistent handle wakeup routine + * @param retire any persistent handle retire routine + * @return \a a or an allocated persistent handle factory + */ +PHP_RAPHF_API php_persistent_handle_factory_t *php_persistent_handle_concede( + php_persistent_handle_factory_t *a, + zend_string *name, zend_string *ident, + php_persistent_handle_wakeup_t wakeup, + php_persistent_handle_retire_t retire); + +/** + * Abandon the persistent handle factory. + * + * Destroy a php_persistent_handle_factory created by + * php_persistent_handle_concede(). If the memory for the factory was allocated, + * it will automatically be free'd. + * + * @param a the persistent handle factory to destroy + */ +PHP_RAPHF_API void php_persistent_handle_abandon( + php_persistent_handle_factory_t *a); + +/** + * Acquire a persistent handle. + * + * That is, either re-use a resource from the free list or create a new handle. + * + * If a handle is acquired from the free list, the + * php_persistent_handle_factory::wakeup callback will be executed for that + * handle. + * + * @param a the persistent handle factory + * @param init_arg the \a init_arg for php_resource_factory_handle_ctor() + * @return the acquired resource + */ +PHP_RAPHF_API void *php_persistent_handle_acquire( + php_persistent_handle_factory_t *a, void *init_arg); + +/** + * Release a persistent handle. + * + * That is, either put it back into the free list for later re-use or clean it + * up with php_resource_factory_handle_dtor(). + * + * If a handle is put back into the free list, the + * php_persistent_handle_factory::retire callback will be executed for that + * handle. + * + * @param a the persistent handle factory + * @param handle the handle to release + */ +PHP_RAPHF_API void php_persistent_handle_release( + php_persistent_handle_factory_t *a, void *handle); + +/** + * Copy a persistent handle. + * + * Let the underlying resource factory copy the \a handle. + * + * @param a the persistent handle factory + * @param handle the resource to accrete + */ +PHP_RAPHF_API void *php_persistent_handle_accrete( + php_persistent_handle_factory_t *a, void *handle); + +/** + * Retrieve persistent handle resource factory ops. + * + * These ops can be used to mask a persistent handle factory as + * resource factory itself, so you can transparently use the + * resource factory API, both for persistent and non-persistent + * ressources. + * + * Example: + * \code{.c} + * php_resource_factory_t *create_my_rf(zend_string *persistent_id) + * { + * php_resource_factory_t *rf; + * + * if (persistent_id) { + * php_persistent_handle_factory_t *pf; + * php_resource_factory_ops_t *ops; + * zend_string *ns = zend_string_init("my", 2, 1); + * + * ops = php_persistent_handle_get_resource_factory_ops(); + * pf = php_persistent_handle_concede(NULL, ns, persistent_id, NULL, NULL); + * rf = php_persistent_handle_resource_factory_init(NULL, pf); + * zend_string_release(ns); + * } else { + * rf = php_resource_factory_init(NULL, &myops, NULL, NULL); + * } + * return rf; + * } + * \endcode + */ +PHP_RAPHF_API php_resource_factory_ops_t * +php_persistent_handle_get_resource_factory_ops(void); + +/** + * Create a resource factory for persistent handles. + * + * This will create a resource factory with persistent handle ops, which wraps + * the provided reource factory \a pf. + * + * @param a the persistent handle resource factory to initialize + * @param pf the resource factory to wrap + */ +PHP_RAPHF_API php_resource_factory_t * +php_persistent_handle_resource_factory_init(php_resource_factory_t *a, + php_persistent_handle_factory_t *pf); + +/** + * Check whether a resource factory is a persistent handle resource factory. + * + * @param a the resource factory to check + */ +PHP_RAPHF_API zend_bool php_resource_factory_is_persistent( + php_resource_factory_t *a); + +/** + * Clean persistent handles up. + * + * Destroy persistent handles of provider \a name and in subsidiary + * namespace \a ident. + * + * If \a name is NULL, all persistent handles of all providers with a + * matching \a ident will be cleaned up. + * + * If \a identr is NULL all persistent handles of the provider will be + * cleaned up. + * + * Ergo, if both, \a name and \a ident are NULL, then all + * persistent handles will be cleaned up. + * + * You must call this in MSHUTDOWN, if your resource factory ops hold a + * registered php_resource_factory::dtor, else the dtor will point to + * memory not any more available if the extension has already been unloaded. + * + * @param name the provider name; may be NULL + * @param ident the subsidiary namespace name; may be NULL + */ +PHP_RAPHF_API void php_persistent_handle_cleanup(zend_string *name, + zend_string *ident); + +/** + * Retrieve statistics about the current process/thread's persistent handles. + * + * @return a HashTable like: + * \code + * [ + * "name" => [ + * "ident" => [ + * "used" => 1, + * "free" => 0, + * ] + * ] + * ] + * \endcode + */ +PHP_RAPHF_API HashTable *php_persistent_handle_statall(HashTable *ht); + +#endif /* PHP_RAPHF_API_H */ + + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ +--TEST-- +pecl/http-v2 - general and stat +--SKIPIF-- + +--FILE-- +enqueue(new http\Client\Request("GET", "http://php.net")); +} while (count($c) < 3); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + +unset($c); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + +?> +Done +--EXPECTF-- +Test +array(2) { + ["http\Client\Curl"]=> + array(0) { + } + ["http\Client\Curl\Request"]=> + array(0) { + } +} +array(2) { + ["http\Client\Curl"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(1) + ["free"]=> + int(0) + } + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(3) + ["free"]=> + int(0) + } + } +} +array(2) { + ["http\Client\Curl"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(1) + } + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(3) + } + } +} +Done +--TEST-- +pecl/http-v2 - clean with name and id +--SKIPIF-- + +--FILE-- +enqueue(new http\Client\Request("GET", "http://php.net")); +} while (count($c) < 3); + +unset($c); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + + +raphf\clean_persistent_handles("http\\Client\\Curl"); +raphf\clean_persistent_handles("http\\Client\\Curl\\Request", "php.net:80"); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + +?> +Done +--EXPECTF-- +Test +array(2) { + ["http\Client\Curl"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(1) + } + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(3) + } + } +} +array(2) { + ["http\Client\Curl"]=> + array(0) { + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(0) + } + } +} +Done +--TEST-- +pecl/http-v2 - clean with id only +--SKIPIF-- + +--FILE-- +enqueue(new http\Client\Request("GET", "http://php.net")); +} while (count($c) < 3); + +unset($c); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + +raphf\clean_persistent_handles(null, "php.net:80"); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + +?> +Done +--EXPECTF-- +Test +array(2) { + ["http\Client\Curl"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(1) + } + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(3) + } + } +} +array(2) { + ["http\Client\Curl"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(0) + } + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(0) + } + } +} +Done +--TEST-- +pecl/http-v2 - partial clean +--SKIPIF-- + +--FILE-- +enqueue(new http\Client\Request("GET", "http://php.net")); + $c2->enqueue(new http\Client\Request("GET", "http://php.net")); +} while (count($c) < 3); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + +unset($c); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + +raphf\clean_persistent_handles(); + +$h = (array) raphf\stat_persistent_handles(); +var_dump(array_intersect_key($h, array_flip(preg_grep("/^http/", array_keys($h))))); + +?> +Done +--EXPECTF-- +Test +array(2) { + ["http\Client\Curl"]=> + array(0) { + } + ["http\Client\Curl\Request"]=> + array(0) { + } +} +array(2) { + ["http\Client\Curl"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(2) + ["free"]=> + int(0) + } + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(6) + ["free"]=> + int(0) + } + } +} +array(2) { + ["http\Client\Curl"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(1) + ["free"]=> + int(1) + } + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(3) + ["free"]=> + int(3) + } + } +} +array(2) { + ["http\Client\Curl"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(1) + ["free"]=> + int(0) + } + } + ["http\Client\Curl\Request"]=> + array(1) { + ["php.net:80"]=> + array(2) { + ["used"]=> + int(3) + ["free"]=> + int(0) + } + } +} +Done +--TEST-- +raphf test +--SKIPIF-- + +--INI-- +raphf.persistent_handle.limit=0 +--FILE-- + +--EXPECTF-- +## call provide: +bool(true) +## call concede: +resource(4) of type (raphf_user) +## call handle_ctor: +### back 'ctor': +#### arg 0: string(10) "data value" +#### arg 1: int(1) +array(2) { + [0]=> + string(10) "data value" + [1]=> + int(1) +} +## call handle_copy: +### back 'copy': +#### arg 0: string(10) "data value" +#### arg 1: array(2) { + [0]=> + string(10) "data value" + [1]=> + int(1) +} +array(2) { + [0]=> + string(10) "data value" + [1]=> + array(2) { + [0]=> + string(10) "data value" + [1]=> + int(1) + } +} +object(stdClass)#%d (1) { + ["test"]=> + array(1) { + [1]=> + array(2) { + ["used"]=> + int(2) + ["free"]=> + int(0) + } + } +} +## call handle_dtor: +### back 'dtor': +#### arg 0: string(10) "data value" +#### arg 1: array(2) { + [0]=> + string(10) "data value" + [1]=> + int(1) +} +NULL +object(stdClass)#%d (1) { + ["test"]=> + array(1) { + [1]=> + array(2) { + ["used"]=> + int(1) + ["free"]=> + int(0) + } + } +} +## call handle_dtor: +### back 'dtor': +#### arg 0: string(10) "data value" +#### arg 1: array(2) { + [0]=> + string(10) "data value" + [1]=> + array(2) { + [0]=> + string(10) "data value" + [1]=> + int(1) + } +} +NULL +object(stdClass)#%d (1) { + ["test"]=> + array(1) { + [1]=> + array(2) { + ["used"]=> + int(0) + ["free"]=> + int(0) + } + } +} +## cleanup: +bool(true) +resource(4) of type (Unknown) +### back 'data_dtor': +#### arg 0: string(10) "data value" +bool(true) +bool(false) +"› +¬ÅT9GÊ7­ðâü©ýOGBMB \ No newline at end of file diff --git a/travis/raphf-phpng.ext.phar b/travis/raphf-phpng.ext.phar deleted file mode 100755 index b226eb0..0000000 Binary files a/travis/raphf-phpng.ext.phar and /dev/null differ