/**
     * Test that the reading is successful.
     *
     * @return void
     *
     * @dataProvider testReadingFlagsProvider
     */
    public function testReading($compression, $signatureName, $signatureFlag)
    {
        $pharfile = $this->getTempFile('temp.phar');
        $phar = new \Phar($pharfile, 0, 'temp.phar');
        $phar->startBuffering();
        $phar->addFromString('/bin/script', $fileData = <<<EOF
#!/usr/bin/php
<?php
echo 'hello world';
EOF
);
        $phar->setDefaultStub('/bin/script', '/web/index');
        $phar->stopBuffering();
        $phar->setSignatureAlgorithm($signatureFlag);
        if ($compression !== \Phar::NONE) {
            $phar->compressFiles($compression);
        }
        unset($phar);
        $reader = new PharReader();
        $phar = $reader->load($pharfile);
        $this->assertEquals('temp.phar', $phar->getAlias());
        $this->assertTrue($phar->isSigned());
        $this->assertEquals($signatureName, $phar->getSignatureAlgorithm());
        $files = $phar->getFiles();
        $this->assertEquals('bin/script', $files[0]->getFilename());
        $this->assertEquals($fileData, $files[0]->getContent());
    }
 public function compile()
 {
     if (file_exists('symfony.phar')) {
         unlink('symfony.phar');
     }
     $phar = new \Phar('symfony.phar', 0, 'Symfony');
     $phar->setSignatureAlgorithm(\Phar::SHA1);
     $phar->startBuffering();
     // Files
     foreach ($this->getFiles() as $file) {
         $path = str_replace(__DIR__ . '/', '', $file);
         if (false !== strpos($file, '.php')) {
             $content = Kernel::stripComments(file_get_contents($file));
         } else {
             $content = file_get_contents($file);
         }
         $phar->addFromString($path, $content);
     }
     // Stubs
     $phar['_cli_stub.php'] = $this->getCliStub();
     $phar['_web_stub.php'] = $this->getWebStub();
     $phar->setDefaultStub('_cli_stub.php', '_web_stub.php');
     $phar->stopBuffering();
     //$phar->compressFiles(\Phar::GZ);
     unset($phar);
 }
Example #3
0
function buildModulePhar($name, $format = Phar::PHAR, $compression = Phar::NONE, $executable = true, $fake = false)
{
    echo "Building {$name}...\t";
    $glob = glob($name.'.*');
    if (count($glob) > 0) {
        foreach ($glob as $file) {
            if (!is_dir($file)) {
                unlink($file);
            }   
        }
    }
    $filename = $name . '.phar';
    $phar = new Phar($filename);
    if ($fake) {
        $phar['Module.php'] = '<?php //no class here';
    } else {
        $phar['Module.php'] = "<?php \n\nnamespace $name;\n\nclass Module\n{}";
    }
    if (false === $executable) {
        $phar->convertToData($format, $compression);
    } else {
        $phar->setDefaultStub('Module.php', 'Module.php');
        if ($format !== Phar::PHAR || $compression !== Phar::NONE) {
            $phar->convertToExecutable($format, $compression);
        }
    }
    if ($format !== Phar::PHAR || $compression !== Phar::NONE) {
        unlink($filename);
    }
    echo "Done!\n";
}
Example #4
0
 public function compile($pharFile = 'goutte.phar')
 {
     if (file_exists($pharFile)) {
         unlink($pharFile);
     }
     $phar = new \Phar($pharFile, 0, 'Goutte');
     $phar->setSignatureAlgorithm(\Phar::SHA1);
     $phar->startBuffering();
     // CLI Component files
     foreach ($this->getFiles() as $file) {
         $path = str_replace(__DIR__ . '/', '', $file);
         $phar->addFromString($path, file_get_contents($file));
     }
     // Stubs
     $phar['_cli_stub.php'] = $this->getCliStub();
     $phar['_web_stub.php'] = $this->getWebStub();
     $phar->setDefaultStub('_cli_stub.php', '_web_stub.php');
     $phar->stopBuffering();
     // $phar->compressFiles(\Phar::GZ);
     unset($phar);
 }
Example #5
0
 public function compile($pharFile = 'silex.phar')
 {
     if (file_exists($pharFile)) {
         unlink($pharFile);
     }
     $phar = new \Phar($pharFile, 0, 'Silex');
     $phar->setSignatureAlgorithm(\Phar::SHA1);
     $phar->startBuffering();
     $finder = new Finder();
     $finder->files()->name('*.php')->exclude('tests')->in(__DIR__ . '/..');
     foreach ($finder as $file) {
         $path = str_replace(realpath(__DIR__ . '/../..') . '/', '', realpath($file));
         $content = Kernel::stripComments(file_get_contents($file));
         $phar->addFromString($path, $content);
     }
     // Stubs
     $phar['_cli_stub.php'] = $this->getStub();
     $phar['_web_stub.php'] = $this->getStub();
     $phar->setDefaultStub('_cli_stub.php', '_web_stub.php');
     $phar->stopBuffering();
     // $phar->compressFiles(\Phar::GZ);
     unset($phar);
 }
Example #6
0
 /**
  * Build and configure Phar object.
  *
  * @return Phar
  */
 private function buildPhar()
 {
     $phar = new Phar($this->destinationFile);
     if (!empty($this->stubPath)) {
         $phar->setStub(file_get_contents($this->stubPath));
     } else {
         if (!empty($this->cliStubFile)) {
             $cliStubFile = $this->cliStubFile->getPathWithoutBase($this->baseDirectory);
         } else {
             $cliStubFile = null;
         }
         if (!empty($this->webStubFile)) {
             $webStubFile = $this->webStubFile->getPathWithoutBase($this->baseDirectory);
         } else {
             $webStubFile = null;
         }
         $phar->setDefaultStub($cliStubFile, $webStubFile);
     }
     if ($this->metadata === null) {
         $this->createMetaData();
     }
     if ($metadata = $this->metadata->toArray()) {
         $phar->setMetadata($metadata);
     }
     if (!empty($this->alias)) {
         $phar->setAlias($this->alias);
     }
     return $phar;
 }
<?php

$fname = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.phar';
$phar = new Phar($fname);
$phar['a.php'] = '<php echo "this is a\\n"; ?>';
$phar['b.php'] = '<php echo "this is b\\n"; ?>';
$phar->setDefaultStub();
$phar->stopBuffering();
var_dump($phar->getStub());
echo "============================================================================\n";
echo "============================================================================\n";
$phar->setDefaultStub('my/custom/thingy.php');
$phar->stopBuffering();
var_dump($phar->getStub());
echo "============================================================================\n";
echo "============================================================================\n";
$phar->setDefaultStub('my/custom/thingy.php', 'the/web.php');
$phar->stopBuffering();
var_dump($phar->getStub());
echo "============================================================================\n";
echo "============================================================================\n";
try {
    $phar->setDefaultStub(str_repeat('a', 400));
    $phar->stopBuffering();
    var_dump(strlen($phar->getStub()));
    $phar->setDefaultStub(str_repeat('a', 401));
    $phar->stopBuffering();
    var_dump(strlen($phar->getStub()));
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
Example #8
0
<?php

set_error_handler(function ($num, $msg, $file, $line) {
    throw new Exception($msg, 0, $num, $file, $line);
});
$targetDirPath = __DIR__ . '/target';
if (!file_exists($targetDirPath)) {
    mkdir($targetDirPath);
}
$phar = new Phar($targetDirPath . '/lightship.phar', 0, 'lightship.phar');
$phar->buildFromDirectory(__DIR__ . '/src/Lightship/Bin/lightship/');
$phar->setDefaultStub('lightship.php');
Example #9
0
<?php

## Создание PHAR-архива с заглушкой.
try {
    $phar = new Phar('./autopager.phar', 0, 'autopager.phar');
    // Для записи директив phar.readonly конфигурационного
    // файла php.ini должна быть установлена в 0 или Off
    if (Phar::canWrite()) {
        // Буферизация записи, ничего не записывается, до
        // тех пор, пока не будет вызван метод stopBuffering()
        $phar->startBuffering();
        // Добавление всех файлов из компонента ISPager
        $phar->buildFromIterator(new DirectoryIterator(realpath('../composer/pager/src/ISPager')), '../composer/pager/src');
        // Добавляем автозагрузчик в архив
        $phar->addFromString('autoloader.php', file_get_contents('autoloader.php'));
        // Назначаем автозагрузчик в качестве файла-заглушки
        $phar->setDefaultStub('autoloader.php', 'autoloader.php');
        // Сохранение результатов на жесткий диск
        $phar->stopBuffering();
    } else {
        echo 'PHAR-архив не может быть бы записан';
    }
} catch (Exception $e) {
    echo 'Невозможно открыть PHAR-архив: ', $e;
}
<?

$sLibraryPath = 'lib/SampleLibrary.phar';

// we will build library in case if it not exist
if (! file_exists($sLibraryPath)) {
    ini_set("phar.readonly", 0); // Could be done in php.ini

    $oPhar = new Phar($sLibraryPath); // creating new Phar
    $oPhar->setDefaultStub('index.php', 'classes/index.php'); // pointing main file which require all classes
    $oPhar->buildFromDirectory('classes/'); // creating our library using whole directory

    $oPhar->compress(Phar::GZ); // plus - compressing it into gzip
}

// when library already compiled - we will using it
require_once('phar://'.$sLibraryPath.'.gz');

// demonstration of work
$oClass1 = new SampleClass();
echo $oClass1->getAnyContent();
echo '<pre>';
print_r($oClass1);
echo '</pre>';

$oClass2 = new SampleClass2();
echo $oClass2->getAnyContent();
echo $oClass2->getContent2();
echo '<pre>';
print_r($oClass2);
echo '</pre>';
Example #11
0
<?php

$fname = dirname(__FILE__) . '/tempmanifest2.phar.php';
$pname = 'phar://' . $fname;
$phar = new Phar($fname);
$phar->setDefaultStub();
$phar->setAlias('fred');
$phar['file1.txt'] = 'hi';
$phar['file2.txt'] = 'hi2';
$phar['subdir/ectory/file.txt'] = 'hi3';
$phar->mount($pname . '/mount2', __FILE__);
$phar->addEmptyDir('one/level');
$phar->extractTo(dirname(__FILE__) . '/extract2', 'mount2');
$phar->extractTo(dirname(__FILE__) . '/extract2');
$out = array();
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname(__FILE__) . '/extract2', 0x3000), RecursiveIteratorIterator::CHILD_FIRST) as $path => $file) {
    $extracted[] = $path;
}
sort($extracted);
foreach ($extracted as $out) {
    echo "{$out}\n";
}
?>
===DONE===
<?php 
@unlink(dirname(__FILE__) . '/tempmanifest2.phar.php');
$dir = dirname(__FILE__) . '/extract2/';
@unlink($dir . 'file1.txt');
@unlink($dir . 'file2.txt');
@unlink($dir . 'subdir/ectory/file.txt');
@rmdir($dir . 'subdir/ectory');
Example #12
0
<?php

## Хранение бинарных файлов.
try {
    $phar = new Phar('./gallery.phar', 0, 'gallery.phar');
    // Для записи директив phar.readonly конфигурационного
    // файла php.ini должна быть установлена в 0 или Off
    if (Phar::canWrite()) {
        // Буферизация записи, ничего не записывается, до
        // тех пор, пока не будет вызван метод stopBuffering()
        $phar->startBuffering();
        // Добавление всех файлов из папки photos
        foreach (glob('../composer/photos/*') as $jpg) {
            $phar[basename($jpg)] = file_get_contents($jpg);
        }
        // Назначаем файл-заглушку
        $phar['show.php'] = file_get_contents('show.php');
        $phar->setDefaultStub('show.php', 'show.php');
        // Сохранение результатов на жесткий диск
        $phar->stopBuffering();
    } else {
        echo 'PHAR-архив не может быть бы записан';
    }
} catch (Exception $e) {
    echo 'Невозможно открыть PHAR-архив: ', $e;
}
Example #13
0
 /**
  * Build and configure Phar object.
  *
  * @return Phar
  */
 private function buildPhar()
 {
     $phar = new Phar($this->destinationFile);
     $phar->setSignatureAlgorithm($this->signatureAlgorithm);
     if (isset($this->stubPath)) {
         $phar->setStub(file_get_contents($this->stubPath));
     } else {
         $phar->setDefaultStub($this->cliStubFile->getPathWithoutBase($this->baseDirectory), $this->webStubFile->getPathWithoutBase($this->baseDirectory));
     }
     if ($metadata = $this->metadata->toArray()) {
         $phar->setMetadata($metadata);
     }
     if (!empty($this->alias)) {
         $phar->setAlias($this->alias);
     }
     return $phar;
 }
Example #14
0
<?php

$sLibraryPath = '../CompiledPHAR/SecurityCheck_compiled.phar';
if (file_exists($sLibraryPath)) {
    @unlink($sLibraryPath);
}
if (file_exists($sLibraryPath . ".gz")) {
    @unlink($sLibraryPath . ".gz");
}
if (!file_exists($sLibraryPath)) {
    ini_set("phar.readonly", 0);
    // Could be done in php.ini
    $oPhar = new Phar($sLibraryPath);
    // creating new Phar
    $oPhar->setDefaultStub('index.php', '../SecurityCheck/index.php');
    // pointing main file which require all classes
    $oPhar->buildFromDirectory('../SecurityCheck/');
    // creating our library using whole directory
    $oPhar->compress(Phar::GZ);
    // plus - compressing it into gzip
}
    /**
     * Test that the writing of a loaded phar results in an equal file.
     *
     * @return void
     *
     * @dataProvider testWritingFlagsProvider
     */
    public function testWriteLoaded($compression, $signatureFlag)
    {
        $pharfile = $this->getTempFile('temp.phar');
        $phar = new \Phar($pharfile, 0, 'temp.phar');
        $phar->startBuffering();
        $phar->addFromString('/bin/script', $fileData = <<<EOF
#!/usr/bin/php
<?php
echo 'hello world';
EOF
);
        $phar->setDefaultStub('/bin/script', '/web/index');
        $phar->stopBuffering();
        if (0 !== $signatureFlag) {
            $phar->setSignatureAlgorithm($signatureFlag);
        }
        if ($compression !== \Phar::NONE) {
            $phar->compress($compression);
        }
        unset($phar);
        $reader = new PharReader();
        $phar = $reader->load($pharfile);
        $pharfile2 = $this->getTempFile('temp.phar');
        $writer = new PharWriter();
        $writer->save($phar, $pharfile2);
        unset($writer);
        $this->assertFileEquals($pharfile, $pharfile2);
    }
 /**
  * Build and configure Phar object.
  *
  * @return Phar
  */
 private function buildPhar()
 {
     $phar = new Phar($this->destinationFile);
     if ($this->signatureAlgorithm == Phar::OPENSSL) {
         // Load up the contents of the key
         $keyContents = file_get_contents($this->key);
         // Attempt to load the given key as a PKCS#12 Cert Store first.
         if (openssl_pkcs12_read($keyContents, $certs, $this->keyPassword)) {
             $private = openssl_pkey_get_private($certs['pkey']);
         } else {
             // Fall back to a regular PEM-encoded private key.
             // Setup an OpenSSL resource using the private key
             // and tell the Phar to sign it using that key.
             $private = openssl_pkey_get_private($keyContents, $this->keyPassword);
         }
         $phar->setSignatureAlgorithm(Phar::OPENSSL, $private);
         // Get the details so we can get the public key and write that out
         // alongside the phar.
         $details = openssl_pkey_get_details($private);
         file_put_contents($this->destinationFile . '.pubkey', $details['key']);
     } else {
         $phar->setSignatureAlgorithm($this->signatureAlgorithm);
     }
     if (!empty($this->stubPath)) {
         $phar->setStub(file_get_contents($this->stubPath));
     } else {
         if (!empty($this->cliStubFile)) {
             $cliStubFile = $this->cliStubFile->getPathWithoutBase($this->baseDirectory);
         } else {
             $cliStubFile = null;
         }
         if (!empty($this->webStubFile)) {
             $webStubFile = $this->webStubFile->getPathWithoutBase($this->baseDirectory);
         } else {
             $webStubFile = null;
         }
         $phar->setDefaultStub($cliStubFile, $webStubFile);
     }
     if ($this->metadata === null) {
         $this->createMetaData();
     }
     if ($metadata = $this->metadata->toArray()) {
         $phar->setMetadata($metadata);
     }
     if (!empty($this->alias)) {
         $phar->setAlias($this->alias);
     }
     return $phar;
 }
Example #17
0
     info("Build From: {$base_dir}");
     if ($regex) {
         info("Filter: {$regex}");
     }
     $p->buildFromDirectory($base_dir, $regex);
 }
 if (!empty($files)) {
     foreach (explode(',', $files) as $file) {
         info("Add File: {$file}");
         $p->addFile($file, basename($file));
     }
 }
 if ($index && $webindex) {
     info("Index: {$index}");
     info("Web Index: {$webindex}");
     $p->setDefaultStub($index, $webindex);
 } else {
     if ($index) {
         info("Index: {$index}");
         $p->setDefaultStub($index);
     } else {
         if ($webindex) {
             info("Web Index: {$webindex}");
             $p->setDefaultStub(null, $webindex);
         }
     }
 }
 if ($stub) {
     info("Stub: {$stub}");
     if (is_file($stub)) {
         $stub = file_get_contents($stub);
Example #18
0
 /**
  * Build and configure Phar object.
  *
  * @return Phar
  */
 private function buildPhar()
 {
     $phar = new Phar($this->destinationFile);
     $phar->setSignatureAlgorithm($this->signatureAlgorithm);
     /*
      * File compression, if needed.
      */
     if (Phar::NONE != $this->compression) {
         $phar->compressFiles($this->compression);
     }
     $phar->setDefaultStub($this->cliStubFile, $this->webStubFile);
     if ($metadata = $this->metadata->toArray()) {
         $phar->setMetadata($metadata);
     }
     return $phar;
 }
Example #19
0
<?php

$phar = new Phar('dbsync.phar');
$phar->buildFromDirectory('phar');
$phar->setDefaultStub('index.php');
$signatures = Phar::getSupportedSignatures();
$phar->setSignatureAlgorithm(PHAR::SHA512);
$phar->extractTo('pharTest');
Example #20
0
 /**
  * Build and configure Phar object.
  *
  * @return Phar
  */
 private function buildPhar()
 {
     $phar = new Phar($this->destinationFile, 0, $this->alias);
     $phar->setSignatureAlgorithm($this->signatureAlgorithm);
     /*
      * File compression, if needed.
      */
     if (Phar::NONE != $this->compression) {
         $phar->compressFiles($this->compression);
     }
     if (isset($this->customStubPath)) {
         $phar->setStub(file_get_contents($this->customStubPath));
     } else {
         $phar->setDefaultStub($this->cliStubFile, $this->webStubFile);
     }
     if ($metadata = $this->metadata->toArray()) {
         $phar->setMetadata($metadata);
     }
     if (!empty($this->alias)) {
         $phar->setAlias($this->alias);
     }
     return $phar;
 }
<?php

$fname = dirname(__FILE__) . '/' . basename(__FILE__, '.php') . '.phar.zip';
$phar = new Phar($fname);
$phar['a.php'] = '<php echo "this is a\\n"; ?>';
$phar['b.php'] = '<php echo "this is b\\n"; ?>';
$phar->setStub('<?php echo "Hello World\\n"; __HALT_COMPILER(); ?>');
var_dump($phar->getStub());
echo "============================================================================\n";
echo "============================================================================\n";
try {
    $phar->setDefaultStub();
    $phar->stopBuffering();
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
var_dump($phar->getStub());
echo "============================================================================\n";
echo "============================================================================\n";
try {
    $phar->setDefaultStub('my/custom/thingy.php');
    $phar->stopBuffering();
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
var_dump($phar->getStub());
echo "============================================================================\n";
echo "============================================================================\n";
try {
    $phar->setDefaultStub('my/custom/thingy.php', 'the/web.php');
    $phar->stopBuffering();
    echo $e->getMessage() . "\n";
}
try {
    $b->setStub('oops');
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
ini_set('phar.readonly', 0);
$a->setStub(array());
ini_set('phar.readonly', 1);
try {
    $b->setDefaultStub('oops');
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
$a->setDefaultStub(array());
try {
    $a->setDefaultStub('oops');
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
try {
    $a->setSignatureAlgorithm(Phar::MD5);
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
$a->compress(array());
try {
    $a->compress(1);
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
<?php

$p = new Phar(__FILE__);
var_dump($p->getStub());
$p2 = new Phar(__FILE__);
$p->setDefaultStub();
echo strlen($p2->getStub()), "\n";
echo "ok\n";
__halt_compiler(); ?>
6test.txtШ∆тH©јПE∂<?php __HALT_COMPILER();Кj?НѕcЂxH¢Вы*Ф}»!У5GBMB
Example #24
0
 /**
  * Build and configure Phar object.
  *
  * @return Phar
  */
 private function buildPhar()
 {
     $phar = new Phar($this->destinationFile);
     if ($this->signatureAlgorithm == Phar::OPENSSL) {
         // Load up the contents of the key
         $keyContents = file_get_contents($this->key);
         // Setup an OpenSSL resource using the private key and tell the Phar
         // to sign it using that key.
         $private = openssl_pkey_get_private($keyContents, $this->keyPassword);
         $phar->setSignatureAlgorithm(Phar::OPENSSL, $private);
         // Get the details so we can get the public key and write that out
         // alongside the phar.
         $details = openssl_pkey_get_details($private);
         file_put_contents($this->destinationFile . '.pubkey', $details['key']);
     } else {
         $phar->setSignatureAlgorithm($this->signatureAlgorithm);
     }
     if (isset($this->stubPath)) {
         $phar->setStub(file_get_contents($this->stubPath));
     } else {
         if (!empty($this->cliStubFile)) {
             $cliStubFile = $this->cliStubFile->getPathWithoutBase($this->baseDirectory);
         } else {
             $cliStubFile = null;
         }
         if (!empty($this->webStubFile)) {
             $webStubFile = $this->webStubFile->getPathWithoutBase($this->baseDirectory);
         } else {
             $webStubFile = null;
         }
         $phar->setDefaultStub($cliStubFile, $webStubFile);
     }
     if ($metadata = $this->metadata->toArray()) {
         $phar->setMetadata($metadata);
     }
     if (!empty($this->alias)) {
         $phar->setAlias($this->alias);
     }
     return $phar;
 }
Example #25
0
 /**
  * Adds the stubs for the CLI and Web interaction to the PHAR archive.
  *
  * @param \Phar $phar
  *
  * @see getCliStub() for the Stub for Command Line Interaction
  * @see getWebStub() for the Stub for Web Interaction
  *
  * @return void
  */
 protected function addStubsToPharArchive($phar)
 {
     $phar['_cli_stub.php'] = $this->getCliStub();
     $phar['_web_stub.php'] = $this->getWebStub();
     $phar->setDefaultStub('_cli_stub.php', '_web_stub.php');
 }
Example #26
0
            echo "   PHIndex[{$fileIndex}] = {$fileName}\n";
        }
    }
}
echo "Now building the phar.\n";
/*
* Now build the archive.
*/
$p->startBuffering();
$p->buildFromIterator(new ArrayIterator($files));
$p->stopBuffering();
/*
* finish up.
*/
//$p->setStub($p->createDefaultStub(substr($stubFile, strlen($sourceLocation))));
$p->setDefaultStub(substr($stubFile, strlen($sourceLocation)));
$p = null;
if (isset($options['v'])) {
    echo count($files) . " files Added to " . $pharFile . "\n";
}
echo "Done.\n";
exit;
function displayHelp()
{
    echo "\n\npachage.php\n";
    echo "  Authors: Cal Evans, John Douglass\n\n";
    echo "  -s The source directory \n";
    echo "  -p The name to give your phar file.\n";
    echo "  --stub The name of your stub file. Will default to stub.php if not passed in.\n";
    echo "  -v verbose mode.\n";
}