getBuildDir() public static method

php(s) could be global, so we use ROOT path.
public static getBuildDir ( )
Example #1
0
 public function execute()
 {
     $args = func_get_args();
     // $currentVersion;
     $root = Config::getPhpbrewRoot();
     $home = Config::getPhpbrewHome();
     $buildDir = Config::getBuildDir();
     $version = getenv('PHPBREW_PHP');
     // XXX: get source dir from current build information
     $sourceDir = $buildDir . DIRECTORY_SEPARATOR . $version;
     $this->logger->info($sourceDir);
     $cmd = new CommandBuilder('ctags');
     $cmd->arg('--recurse');
     $cmd->arg('-a');
     $cmd->arg('-h');
     $cmd->arg('.c.h.cpp');
     $cmd->arg($sourceDir . DIRECTORY_SEPARATOR . 'main');
     $cmd->arg($sourceDir . DIRECTORY_SEPARATOR . 'ext');
     $cmd->arg($sourceDir . DIRECTORY_SEPARATOR . 'Zend');
     foreach ($args as $a) {
         $cmd->arg($a);
     }
     $this->logger->info($cmd->__toString());
     $cmd->execute();
     $this->logger->info("Done");
 }
Example #2
0
 public function arguments($args)
 {
     $args->add('extensions')->suggestions(function () {
         $extdir = Config::getBuildDir() . '/' . Config::getCurrentPhpName() . '/ext';
         return array_filter(scandir($extdir), function ($d) use($extdir) {
             return $d != '.' && $d != '..' && is_dir($extdir . DIRECTORY_SEPARATOR . $d);
         });
     });
 }
Example #3
0
 public function purgeExtension(Extension $ext)
 {
     if ($sourceDir = $ext->getSourceDirectory()) {
         $currentPhpExtensionDirectory = Config::getBuildDir() . '/' . Config::getCurrentPhpName() . '/ext';
         $extName = $ext->getExtensionName();
         $extensionDir = $currentPhpExtensionDirectory . DIRECTORY_SEPARATOR . $extName;
         if (file_exists($extensionDir)) {
             Utils::system("rm -rvf {$extensionDir}");
         }
     }
 }
Example #4
0
    public function execute()
    {
        // $currentVersion;
        $root = Config::getPhpbrewRoot();
        $home = Config::getPhpbrewHome();
        $buildDir = Config::getBuildDir();
        $buildPrefix = Config::getBuildPrefix();
        // $versionBuildPrefix = Config::getVersionBuildPrefix($version);
        // $versionBinPath     = Config::getVersionBinPath($version);
        if (!file_exists($root)) {
            mkdir($root, 0755, true);
        }
        touch($root . DIRECTORY_SEPARATOR . '.metadata_never_index');
        // prevent spotlight index here
        if ($root != $home) {
            touch($home . DIRECTORY_SEPARATOR . '.metadata_never_index');
        }
        if ($this->options->{'config'} !== null) {
            copy($this->options->{'config'}, $root . DIRECTORY_SEPARATOR . 'config.yaml');
        }
        if (!file_exists($home)) {
            mkdir($home, 0755, true);
        }
        if (!file_exists($buildPrefix)) {
            mkdir($buildPrefix, 0755, true);
        }
        if (!file_exists($buildDir)) {
            mkdir($buildDir, 0755, true);
        }
        // write bashrc script to phpbrew home
        file_put_contents($home . '/bashrc', $this->getBashScript());
        echo <<<EOS
Phpbrew environment is initialized, required directories are created under

    {$home}

Paste the following line(s) to the end of your ~/.bashrc and start a
new shell, phpbrew should be up and fully functional from there:

    source {$home}/bashrc

To enable PHP version info in your shell prompt, please set PHPBREW_SET_PROMPT=1
in your `~/.bashrc` before you source `~/.phpbrew/bashrc`

    export PHPBREW_SET_PROMPT=1

For further instructions, simply run `phpbrew` to see the help message.

Enjoy phpbrew at \$HOME!!

EOS;
    }
Example #5
0
 public function execute()
 {
     if ($this->options->{'php'} !== null) {
         $php = Utils::findLatestPhpVersion($this->options->{'php'});
     } else {
         $php = Config::getCurrentPhpName();
     }
     $buildDir = Config::getBuildDir();
     $extDir = $buildDir . DIRECTORY_SEPARATOR . $php . DIRECTORY_SEPARATOR . 'ext';
     // listing all local extensions
     if (version_compare('php-' . phpversion(), $php, '==')) {
         $loaded = array_map('strtolower', get_loaded_extensions());
     } else {
         $this->logger->info('PHP version is different from current active version.');
         $this->logger->info('Only available extensions are listed.');
         $this->logger->info('You will not see which of them are loaded.');
         $loaded = array();
     }
     // list for extensions which are not enabled
     $extensions = array();
     if (is_dir($extDir)) {
         $fp = opendir($extDir);
         if ($fp !== false) {
             while ($file = readdir($fp)) {
                 if ($file === '.' || $file === '..') {
                     continue;
                 }
                 if (is_file($extDir . '/' . $file)) {
                     continue;
                 }
                 $n = strtolower(preg_replace('#-[\\d\\.]+$#', '', $file));
                 if (in_array($n, $loaded)) {
                     continue;
                 }
                 $extensions[] = $n;
             }
             sort($loaded);
             sort($extensions);
             closedir($fp);
         }
     }
     $this->logger->info('Loaded extensions:');
     foreach ($loaded as $ext) {
         $this->logger->info("  [*] {$ext}");
     }
     $this->logger->info('Available extensions:');
     foreach ($extensions as $ext) {
         $this->logger->info("  [ ] {$ext}");
     }
 }
Example #6
0
 public function prepareForVersion($version)
 {
     $home = Config::getPhpbrewRoot();
     $buildDir = Config::getBuildDir();
     $variantsDir = Config::getVariantsDir();
     $buildPrefix = Config::getVersionBuildPrefix($version);
     if (!file_exists($variantsDir)) {
         mkdir($variantsDir, 0755, true);
     }
     if (!file_exists($buildDir)) {
         mkdir($buildDir, 0755, true);
     }
     if (!file_exists($buildPrefix)) {
         mkdir($buildPrefix, 0755, true);
     }
 }
 public function run(Build $build = NULL)
 {
     $dirs = array();
     $dirs[] = Config::getPhpbrewRoot();
     $dirs[] = Config::getPhpbrewHome();
     $dirs[] = Config::getBuildDir();
     $dirs[] = Config::getDistFileDir();
     $dirs[] = Config::getVariantsDir();
     if ($build) {
         $dirs[] = Config::getInstallPrefix() . DIRECTORY_SEPARATOR . $build->getName();
     }
     foreach ($dirs as $dir) {
         if (!file_exists($dir)) {
             $this->logger->debug("Creating directory {$dir}");
             mkdir($dir, 0755, true);
         }
     }
 }
Example #8
0
 public function execute($version)
 {
     if ($this->options->all) {
         $buildDir = Config::getBuildDir() . DIRECTORY_SEPARATOR . $version;
         if (!file_exists($buildDir)) {
             $this->logger->info("Source directory " . $buildDir . " does not exist.");
         } else {
             $this->logger->info("Source directory " . $buildDir . " found, deleting...");
             Utils::recursive_unlink($buildDir, $this->logger);
         }
     } else {
         $make = new MakeTask($this->logger);
         $make->setQuiet();
         $build = new Build($version);
         if ($make->clean($build)) {
             $this->logger->info("Distribution is cleaned up. Woof! ");
         }
     }
 }
Example #9
0
 public function renameSourceDirectory(Extension $ext)
 {
     $currentPhpExtensionDirectory = Config::getBuildDir() . '/' . Config::getCurrentPhpName() . '/ext';
     $extName = $ext->getExtensionName();
     $name = $ext->getName();
     $extensionDir = $currentPhpExtensionDirectory . DIRECTORY_SEPARATOR . $extName;
     $extensionExtractDir = $currentPhpExtensionDirectory . DIRECTORY_SEPARATOR . $name;
     if ($name != $extName) {
         $this->logger->info("===> Rename source directory to {$extensionDir}...");
         $cmds = array("rm -rf {$extensionDir}", "mv {$extensionExtractDir} {$extensionDir}");
         foreach ($cmds as $cmd) {
             $this->logger->debug($cmd);
             Utils::system($cmd);
         }
         // replace source directory to new source directory
         $sourceDir = str_replace($extensionExtractDir, $extensionDir, $ext->getSourceDirectory());
         $ext->setSourceDirectory($sourceDir);
         $ext->setName($extName);
     }
 }
Example #10
0
 public function execute($name)
 {
     switch ($name) {
         case 'home':
             echo Config::getPhpbrewRoot();
             break;
         case 'build':
             echo Config::getBuildDir();
             break;
         case 'bin':
             echo Config::getCurrentPhpBin();
             break;
         case 'include':
             echo Config::getVersionBuildPrefix(Config::getCurrentPhpName()) . DIRECTORY_SEPARATOR . 'include';
             break;
         case 'etc':
             echo Config::getVersionBuildPrefix(Config::getCurrentPhpName()) . DIRECTORY_SEPARATOR . 'etc';
             break;
     }
 }
Example #11
0
 public function execute($version)
 {
     if (!preg_match('/^php-/', $version)) {
         $version = 'php-' . $version;
     }
     $info = PhpSource::getVersionInfo($version, $this->options->old);
     if (!$info) {
         throw new Exception("Version {$version} not found.");
     }
     $prepare = new PrepareDirectoryTask($this->logger);
     $prepare->prepareForVersion($version);
     $buildDir = Config::getBuildDir();
     $dw = new DirectorySwitch();
     $dw->cd($buildDir);
     $download = new DownloadTask($this->logger);
     $targetDir = $download->downloadByVersionString($version, $this->options->old, $this->options->force);
     if (!file_exists($targetDir)) {
         throw new Exception("Download failed.");
     }
     $this->logger->info("Done, please look at: {$buildDir}/{$targetDir}");
     $dw->back();
 }
Example #12
0
 public function execute($versionName = null)
 {
     $args = func_get_args();
     array_shift($args);
     // $currentVersion;
     $root = Config::getRoot();
     $home = Config::getHome();
     if ($versionName) {
         $sourceDir = Config::getBuildDir() . DIRECTORY_SEPARATOR . $versionName;
     } else {
         if (!getenv('PHPBREW_PHP')) {
             $this->logger->error('Error: PHPBREW_PHP environment variable is not defined.');
             $this->logger->error('  This command requires you specify a PHP version from your build list.');
             $this->logger->error("  And it looks like you haven't switched to a version from the builds that were built with PHPBrew.");
             $this->logger->error('Suggestion: Please install at least one PHP with your prefered version and switch to it.');
             return false;
         }
         $sourceDir = Config::getCurrentBuildDir();
     }
     if (!file_exists($sourceDir)) {
         return $this->logger->error("{$sourceDir} does not exist.");
     }
     $this->logger->info('Scanning ' . $sourceDir);
     $cmd = new CommandBuilder('ctags');
     $cmd->arg('-R');
     $cmd->arg('-a');
     $cmd->arg('-h');
     $cmd->arg('.c.h.cpp');
     $cmd->arg($sourceDir . DIRECTORY_SEPARATOR . 'main');
     $cmd->arg($sourceDir . DIRECTORY_SEPARATOR . 'ext');
     $cmd->arg($sourceDir . DIRECTORY_SEPARATOR . 'Zend');
     foreach ($args as $a) {
         $cmd->arg($a);
     }
     $this->logger->debug($cmd->__toString());
     $cmd->execute();
     $this->logger->info('Done');
 }
Example #13
0
 public function testFindLatestPhpVersion()
 {
     $this->markTestSkipped("We should use a virtual file system here (vsfStream)");
     $buildDir = Config::getBuildDir();
     $paths = array();
     $paths[] = $buildDir . DIRECTORY_SEPARATOR . 'php-12.3.4';
     $paths[] = $buildDir . DIRECTORY_SEPARATOR . 'php-12.3.6';
     // Create paths
     foreach ($paths as $path) {
         if (!is_dir($path)) {
             mkdir($path);
         }
     }
     is('12.3.6', Utils::findLatestPhpVersion('12'));
     is('12.3.6', Utils::findLatestPhpVersion('12.3'));
     is('12.3.4', Utils::findLatestPhpVersion('12.3.4'));
     is(false, Utils::findLatestPhpVersion('11'));
     // Cleanup paths
     foreach ($paths as $path) {
         if (is_dir($path)) {
             rmdir($path);
         }
     }
 }
Example #14
0
 public function buildMetaFromName($name)
 {
     $path = Config::getBuildDir() . '/' . Config::getCurrentPhpName() . '/ext/' . $name;
     $xml = $path . '/package.xml';
     $m4 = $path . '/config.m4';
     if (file_exists($xml)) {
         $this->logger->warning("===> Using xml extension meta");
         $meta = new ExtensionMetaXml($xml);
     } elseif (file_exists($m4)) {
         $this->logger->warning("===> Using m4 extension meta");
         $meta = new ExtensionMetaM4($m4);
     } else {
         $this->logger->warning("===> Using polyfill extension meta");
         $meta = new ExtensionMetaPolyfill($name);
     }
     return $meta;
 }
Example #15
0
 public static function lookup($packageName, array $lookupDirectories = array(), $fallback = true)
 {
     if ($fallback) {
         // Always push the PHP source directory to the end of the list for the fallback.
         $lookupDirectories[] = Config::getBuildDir() . '/' . Config::getCurrentPhpName() . '/ext';
     }
     foreach ($lookupDirectories as $lookupDir) {
         if (!file_exists($lookupDir)) {
             continue;
         }
         $extensionDir = $lookupDir . DIRECTORY_SEPARATOR . $packageName;
         if ($ext = self::createFromDirectory($packageName, $extensionDir)) {
             return $ext;
         }
     }
     return new Extension($packageName);
 }
Example #16
0
 public function execute($extName, $version = 'stable')
 {
     if ((preg_match('#^git://#', $extName) || preg_match('#\\.git$#', $extName)) && !preg_match("#github|bitbucket#", $extName)) {
         $pathinfo = pathinfo($extName);
         $repoUrl = $extName;
         $extName = $pathinfo['filename'];
         $extDir = Config::getBuildDir() . DIRECTORY_SEPARATOR . Config::getCurrentPhpName() . DIRECTORY_SEPARATOR . 'ext' . DIRECTORY_SEPARATOR . $extName;
         if (!file_exists($extDir)) {
             passthru("git clone {$repoUrl} {$extDir}", $ret);
             if ($ret != 0) {
                 return $this->logger->error('Clone failed.');
             }
         }
     }
     $extensions = array();
     if (Utils::startsWith($extName, '+')) {
         $config = Config::getConfigParam('extensions');
         $extName = ltrim($extName, '+');
         if (isset($config[$extName])) {
             foreach ($config[$extName] as $extensionName => $extOptions) {
                 $args = explode(' ', $extOptions);
                 $extensions[$extensionName] = $this->getExtConfig($args);
             }
         } else {
             $this->logger->info('Extension set name not found. Have you configured it at the config.yaml file?');
         }
     } else {
         $args = array_slice(func_get_args(), 1);
         $extensions[$extName] = $this->getExtConfig($args);
     }
     $extensionList = new ExtensionList();
     $manager = new ExtensionManager($this->logger);
     foreach ($extensions as $extensionName => $extConfig) {
         $provider = $extensionList->exists($extensionName);
         if (!$provider) {
             throw new Exception("Could not find provider for {$extensionName}.");
         }
         $extensionName = $provider->getPackageName();
         $ext = ExtensionFactory::lookupRecursive($extensionName);
         $always_redownload = $this->options->{'pecl'} || $this->options->{'redownload'} || !$provider->isBundled($extensionName);
         // Extension not found, use pecl to download it.
         if (!$ext || $always_redownload) {
             // not every project has stable branch, using master as default version
             $args = array_slice(func_get_args(), 1);
             if (!isset($args[0]) || $args[0] != $extConfig->version) {
                 $extConfig->version = $provider->getDefaultVersion();
             }
             $extensionDownloader = new ExtensionDownloader($this->logger, $this->options);
             $extensionDownloader->download($provider, $extConfig->version);
             // Reload the extension
             if ($provider->shouldLookupRecursive()) {
                 $ext = ExtensionFactory::lookupRecursive($extensionName);
             } else {
                 $ext = ExtensionFactory::lookup($extensionName);
             }
             if ($ext) {
                 $extensionDownloader->renameSourceDirectory($ext);
             }
         }
         if (!$ext) {
             throw new Exception("{$extensionName} not found.");
         }
         $manager->installExtension($ext, $extConfig->options);
     }
 }
Example #17
0
    public function execute($version)
    {
        if (!preg_match('/^php-/', $version)) {
            $version = 'php-' . $version;
        }
        $version = $this->getLatestMinorVersion($version, $this->options->old);
        $options = $this->options;
        $logger = $this->logger;
        // get options and variants for building php
        $args = func_get_args();
        // the first argument is the target version.
        array_shift($args);
        $name = $this->options->name ?: $version;
        // find inherited variants
        $inheritedVariants = array();
        if ($this->options->like) {
            $inheritedVariants = VariantParser::getInheritedVariants($this->options->like);
        }
        // ['extra_options'] => the extra options to be passed to ./configure command
        // ['enabled_variants'] => enabeld variants
        // ['disabled_variants'] => disabled variants
        $variantInfo = VariantParser::parseCommandArguments($args, $inheritedVariants);
        $info = PhpSource::getVersionInfo($version, $this->options->old);
        if (!$info) {
            throw new Exception("Version {$version} not found.");
        }
        $prepare = new PrepareDirectoryTask($this->logger);
        $prepare->prepareForVersion($version);
        // convert patch to realpath
        if ($this->options->patch) {
            $patchPaths = array();
            foreach ($this->options->patch as $patch) {
                /** @var \SplFileInfo $patch */
                $patchPath = realpath($patch);
                if ($patchPath !== false) {
                    $patchPaths[(string) $patch] = $patchPath;
                }
            }
            // rewrite patch paths
            $this->options->keys['patch']->value = $patchPaths;
        }
        // Move to to build directory, because we are going to download distribution.
        $buildDir = Config::getBuildDir();
        chdir($buildDir);
        $download = new DownloadTask($this->logger);
        $targetDir = $download->downloadByVersionString($version, $this->options->old, $this->options->force);
        if (!file_exists($targetDir)) {
            throw new Exception("Download failed.");
        }
        // Change directory to the downloaded source directory.
        chdir($targetDir);
        $buildPrefix = Config::getVersionBuildPrefix($version);
        if (!file_exists($buildPrefix)) {
            mkdir($buildPrefix, 0755, true);
        }
        // write variants info.
        $variantInfoFile = $buildPrefix . DIRECTORY_SEPARATOR . 'phpbrew.variants';
        $this->logger->debug("Writing variant info to {$variantInfoFile}");
        file_put_contents($variantInfoFile, serialize($variantInfo));
        // The build object, contains the information to build php.
        $build = new Build($version, $name, $buildPrefix);
        $build->setInstallPrefix($buildPrefix);
        $build->setSourceDirectory($targetDir);
        $builder = new Builder($targetDir, $version);
        $builder->logger = $this->logger;
        $builder->options = $this->options;
        $this->logger->debug('Build Directory: ' . realpath($targetDir));
        foreach ($variantInfo['enabled_variants'] as $name => $value) {
            $build->enableVariant($name, $value);
        }
        foreach ($variantInfo['disabled_variants'] as $name => $value) {
            $build->disableVariant($name);
            if ($build->hasVariant($name)) {
                $this->logger->warn("Removing variant {$name} since we've disabled it from command.");
                $build->removeVariant($name);
            }
        }
        $build->setExtraOptions($variantInfo['extra_options']);
        if ($options->clean) {
            $clean = new CleanTask($this->logger);
            $clean->cleanByVersion($version);
        }
        $buildLogFile = Config::getVersionBuildLogPath($version);
        $configure = new \PhpBrew\Tasks\ConfigureTask($this->logger);
        $configure->configure($build, $this->options);
        $buildTask = new BuildTask($this->logger);
        $buildTask->setLogPath($buildLogFile);
        $buildTask->build($build, $this->options);
        if ($options->{'test'}) {
            $test = new TestTask($this->logger);
            $test->setLogPath($buildLogFile);
            $test->test($build, $this->options);
        }
        $install = new InstallTask($this->logger);
        $install->setLogPath($buildLogFile);
        $install->install($build, $this->options);
        if ($options->{'post-clean'}) {
            $clean = new CleanTask($this->logger);
            $clean->cleanByVersion($version);
        }
        /** POST INSTALLATION **/
        $dsym = new DSymTask($this->logger);
        $dsym->patch($build, $this->options);
        // copy php-fpm config
        $this->logger->info("---> Creating php-fpm.conf");
        $phpFpmConfigPath = "sapi/fpm/php-fpm.conf";
        $phpFpmTargetConfigPath = Config::getVersionEtcPath($version) . DIRECTORY_SEPARATOR . 'php-fpm.conf';
        if (file_exists($phpFpmConfigPath)) {
            if (!file_exists($phpFpmTargetConfigPath)) {
                copy($phpFpmConfigPath, $phpFpmTargetConfigPath);
            } else {
                $this->logger->notice("Found existing {$phpFpmTargetConfigPath}.");
            }
        }
        $phpConfigPath = $options->production ? 'php.ini-production' : 'php.ini-development';
        $this->logger->info("---> Copying {$phpConfigPath} ");
        if (file_exists($phpConfigPath)) {
            $targetConfigPath = Config::getVersionEtcPath($version) . DIRECTORY_SEPARATOR . 'php.ini';
            if (file_exists($targetConfigPath)) {
                $this->logger->notice("Found existing {$targetConfigPath}.");
            } else {
                // TODO: Move this to PhpConfigPatchTask
                // move config file to target location
                copy($phpConfigPath, $targetConfigPath);
                // replace current timezone
                $timezone = ini_get('date.timezone');
                $pharReadonly = ini_get('phar.readonly');
                if ($timezone || $pharReadonly) {
                    // patch default config
                    $content = file_get_contents($targetConfigPath);
                    if ($timezone) {
                        $this->logger->info("---> Found date.timezone, patch config timezone with {$timezone}");
                        $content = preg_replace('/^date.timezone\\s*=\\s*.*/im', "date.timezone = {$timezone}", $content);
                    }
                    if (!$pharReadonly) {
                        $this->logger->info("---> Disable phar.readonly option.");
                        $content = preg_replace('/^phar.readonly\\s*=\\s*.*/im', "phar.readonly = 0", $content);
                    }
                    file_put_contents($targetConfigPath, $content);
                }
            }
        }
        $this->logger->info("Initializing pear config...");
        $home = Config::getPhpbrewHome();
        @mkdir("{$home}/tmp/pear/temp", 0755, true);
        @mkdir("{$home}/tmp/pear/cache_dir", 0755, true);
        @mkdir("{$home}/tmp/pear/download_dir", 0755, true);
        system("pear config-set temp_dir {$home}/tmp/pear/temp");
        system("pear config-set cache_dir {$home}/tmp/pear/cache_dir");
        system("pear config-set download_dir {$home}/tmp/pear/download_dir");
        $this->logger->info("Enabling pear auto-discover...");
        system("pear config-set auto_discover 1");
        $this->logger->debug("Source directory: " . $targetDir);
        $this->logger->info("Congratulations! Now you have PHP with {$version}.");
        echo <<<EOT
To use the newly built PHP, try the line(s) below:

    \$ phpbrew use {$version}

Or you can use switch command to switch your default php version to {$version}:

    \$ phpbrew switch {$version}

Enjoy!

EOT;
    }
Example #18
0
    public function execute($version)
    {
        $distUrl = NULL;
        $versionInfo = array();
        $releaseList = ReleaseList::getReadyInstance();
        $versionDslParser = new VersionDslParser();
        $clean = new MakeTask($this->logger, $this->options);
        $clean->setQuiet();
        if ($root = $this->options->root) {
            Config::setPhpbrewRoot($root);
        }
        if ($home = $this->options->home) {
            Config::setPhpbrewHome($home);
        }
        if ('latest' === strtolower($version)) {
            $version = $releaseList->getLatestVersion();
        }
        // this should point to master or the latest version branch yet to be released
        if ('next' === strtolower($version)) {
            $version = "github.com/php/php-src:master";
        }
        if ($info = $versionDslParser->parse($version)) {
            $version = $info['version'];
            $distUrl = $info['url'];
            // always redownload when installing from github master
            // beware to keep this behavior after clean up the TODO below
            $this->options['force']->setValue(true);
        } else {
            // TODO ↓ clean later ↓ d.d.d versions should be part of the DSL too
            $version = preg_replace('/^php-/', '', $version);
            $versionInfo = $releaseList->getVersion($version);
            if (!$versionInfo) {
                throw new Exception("Version {$version} not found.");
            }
            $version = $versionInfo['version'];
            $distUrlPolicy = new DistributionUrlPolicy();
            if ($this->options->mirror) {
                $distUrlPolicy->setMirrorSite($this->options->mirror);
            }
            $distUrl = $distUrlPolicy->buildUrl($version, $versionInfo['filename']);
        }
        // get options and variants for building php
        // and skip the first argument since it's the target version.
        $args = func_get_args();
        array_shift($args);
        // shift the version name
        $semanticOptions = $this->parseSemanticOptions($args);
        $buildAs = isset($semanticOptions['as']) ? $semanticOptions['as'] : $this->options->name;
        $buildLike = isset($semanticOptions['like']) ? $semanticOptions['like'] : $this->options->like;
        // convert patch to realpath
        if ($this->options->patch) {
            $patchPaths = array();
            foreach ($this->options->patch as $patch) {
                /** @var \SplFileInfo $patch */
                $patchPath = realpath($patch);
                if ($patchPath !== false) {
                    $patchPaths[(string) $patch] = $patchPath;
                }
            }
            // rewrite patch paths
            $this->options->keys['patch']->value = $patchPaths;
        }
        // Initialize the build object, contains the information to build php.
        $build = new Build($version, $buildAs);
        $installPrefix = Config::getInstallPrefix() . DIRECTORY_SEPARATOR . $build->getName();
        if (!file_exists($installPrefix)) {
            mkdir($installPrefix, 0755, true);
        }
        $build->setInstallPrefix($installPrefix);
        // find inherited variants
        if ($buildLike) {
            if ($parentBuild = Build::findByName($buildLike)) {
                $build->loadVariantInfo($parentBuild->settings->toArray());
            }
        }
        $msg = "===> phpbrew will now build {$build->getVersion()}";
        if ($buildLike) {
            $msg .= ' using variants from ' . $buildLike;
        }
        if (isset($semanticOptions['using'])) {
            $msg .= ' plus custom variants: ' . join(', ', $semanticOptions['using']);
            $args = array_merge($args, $semanticOptions['using']);
        }
        if ($buildAs) {
            $msg .= ' as ' . $buildAs;
        }
        $this->logger->info($msg);
        if (!empty($args)) {
            $this->logger->debug("---> Parsing variants from command arguments '" . join(' ', $args) . "'");
        }
        // ['extra_options'] => the extra options to be passed to ./configure command
        // ['enabled_variants'] => enabeld variants
        // ['disabled_variants'] => disabled variants
        $variantInfo = VariantParser::parseCommandArguments($args);
        $build->loadVariantInfo($variantInfo);
        // load again
        // assume +default variant if no build config is given and warn about that
        if (!$variantInfo['enabled_variants']) {
            $build->setBuildSettings(new DefaultBuildSettings());
            $this->logger->notice("You haven't set any variant. A default set of extensions will be installed for the minimum requirement:");
            $this->logger->notice('[' . implode(', ', array_keys($build->getVariants())) . ']');
            $this->logger->notice("Please run 'phpbrew variants' for more information.\n");
        }
        if (preg_match('/5\\.3\\./', $version)) {
            $this->logger->notice("PHP 5.3 requires +intl, enabled by default.");
            $build->enableVariant('intl');
        }
        // always add +xml by default unless --without-pear is present
        // TODO: This can be done by "-pear"
        if (!in_array('--without-pear', $variantInfo['extra_options'])) {
            $build->enableVariant('xml');
        }
        $this->logger->info('===> Loading and resolving variants...');
        $removedVariants = $build->loadVariantInfo($variantInfo);
        if (!empty($removedVariants)) {
            $this->logger->debug('Removed variants: ' . join(',', $removedVariants));
        }
        $prepareTask = new PrepareDirectoryTask($this->logger, $this->options);
        $prepareTask->run($build);
        // Move to to build directory, because we are going to download distribution.
        $buildDir = $this->options->{'build-dir'} ?: Config::getBuildDir();
        if (!file_exists($buildDir)) {
            mkdir($buildDir, 0755, true);
        }
        $variantBuilder = new VariantBuilder();
        $variants = $variantBuilder->build($build);
        $distFileDir = Config::getDistFileDir();
        $downloadTask = new DownloadTask($this->logger, $this->options);
        $targetFilePath = $downloadTask->download($distUrl, $distFileDir, isset($versionInfo['md5']) ? $versionInfo['md5'] : NULL);
        if (!file_exists($targetFilePath)) {
            throw new Exception("Download failed, {$targetFilePath} does not exist.");
        }
        unset($downloadTask);
        $extractTask = new ExtractTask($this->logger, $this->options);
        $targetDir = $extractTask->extract($build, $targetFilePath, $buildDir);
        if (!file_exists($targetDir)) {
            throw new Exception("Extract failed, {$targetDir} does not exist.");
        }
        unset($extractTask);
        // Update build source directory
        $this->logger->debug('Source Directory: ' . realpath($targetDir));
        $build->setSourceDirectory($targetDir);
        if (!$this->options->{'no-clean'} && file_exists($targetDir . DIRECTORY_SEPARATOR . 'Makefile')) {
            $this->logger->info("Found existing Makefile, running make clean to ensure everything will be rebuilt.");
            $this->logger->info("You can append --no-clean option after the install command if you don't want to rebuild.");
            $clean->clean($build);
        }
        // Change directory to the downloaded source directory.
        chdir($targetDir);
        // Write variants info.
        $variantInfoFile = $build->getInstallPrefix() . DIRECTORY_SEPARATOR . 'phpbrew.variants';
        $this->logger->debug("Writing variant info to {$variantInfoFile}");
        if (false === $build->writeVariantInfoFile($variantInfoFile)) {
            $this->logger->warn("Can't store variant info.");
        }
        $buildLogFile = $build->getBuildLogPath();
        if (!$this->options->{'no-configure'}) {
            $configureTask = new ConfigureTask($this->logger, $this->options);
            $configureTask->run($build, $variants);
            unset($configureTask);
            // trigger __destruct
        }
        $buildTask = new BuildTask($this->logger, $this->options);
        $buildTask->run($build);
        unset($buildTask);
        // trigger __destruct
        if ($this->options->{'test'}) {
            $testTask = new TestTask($this->logger, $this->options);
            $testTask->run($build);
            unset($testTask);
            // trigger __destruct
        }
        if (!$this->options->{'no-install'}) {
            $installTask = new InstallTask($this->logger, $this->options);
            $installTask->install($build);
            unset($installTask);
            // trigger __destruct
        }
        if ($this->options->{'post-clean'}) {
            $clean->clean($build);
        }
        $dsym = new DSymTask($this->logger, $this->options);
        $dsym->patch($build, $this->options);
        // copy php-fpm config
        $this->logger->info("---> Creating php-fpm.conf");
        $phpFpmConfigPath = "sapi/fpm/php-fpm.conf";
        $phpFpmTargetConfigPath = $build->getEtcDirectory() . DIRECTORY_SEPARATOR . 'php-fpm.conf';
        if (file_exists($phpFpmConfigPath)) {
            if (!file_exists($phpFpmTargetConfigPath)) {
                copy($phpFpmConfigPath, $phpFpmTargetConfigPath);
            } else {
                $this->logger->notice("Found existing {$phpFpmTargetConfigPath}.");
            }
        }
        $this->logger->info("---> Creating php.ini");
        $phpConfigPath = $build->getSourceDirectory() . DIRECTORY_SEPARATOR . ($this->options->production ? 'php.ini-production' : 'php.ini-development');
        $this->logger->info("---> Copying {$phpConfigPath} ");
        if (file_exists($phpConfigPath) && !$this->options->dryrun) {
            $targetConfigPath = $build->getEtcDirectory() . DIRECTORY_SEPARATOR . 'php.ini';
            if (file_exists($targetConfigPath)) {
                $this->logger->notice("Found existing {$targetConfigPath}.");
            } else {
                // TODO: Move this to PhpConfigPatchTask
                // move config file to target location
                copy($phpConfigPath, $targetConfigPath);
            }
            if (!$this->options->{'no-patch'}) {
                $config = parse_ini_file($targetConfigPath, true);
                $configContent = file_get_contents($targetConfigPath);
                $patched = false;
                if (!isset($config['date']['timezone'])) {
                    $this->logger->info('---> Found date.timezone is not set, patching...');
                    // Replace current timezone
                    if ($timezone = ini_get('date.timezone')) {
                        $this->logger->info("---> Found date.timezone, patching config timezone with {$timezone}");
                        $configContent = preg_replace('/^;?date.timezone\\s*=\\s*.*/im', "date.timezone = {$timezone}", $configContent);
                    }
                    $patched = true;
                }
                if (!isset($config['phar']['readonly'])) {
                    $pharReadonly = ini_get('phar.readonly');
                    // 0 or "" means readonly is disabled manually
                    if (!$pharReadonly) {
                        $this->logger->info("---> Disabling phar.readonly option.");
                        $configContent = preg_replace('/^;?phar.readonly\\s*=\\s*.*/im', "phar.readonly = 0", $configContent);
                    }
                }
                file_put_contents($targetConfigPath, $configContent);
            }
        }
        $this->logger->info("Initializing pear config...");
        $home = Config::getPhpbrewHome();
        @mkdir("{$home}/tmp/pear/temp", 0755, true);
        @mkdir("{$home}/tmp/pear/cache_dir", 0755, true);
        @mkdir("{$home}/tmp/pear/download_dir", 0755, true);
        system("pear config-set temp_dir {$home}/tmp/pear/temp");
        system("pear config-set cache_dir {$home}/tmp/pear/cache_dir");
        system("pear config-set download_dir {$home}/tmp/pear/download_dir");
        $this->logger->info("Enabling pear auto-discover...");
        system("pear config-set auto_discover 1");
        $this->logger->debug("Source directory: " . $targetDir);
        $buildName = $build->getName();
        $this->logger->info("Congratulations! Now you have PHP with {$version} as {$buildName}");
        echo <<<EOT
To use the newly built PHP, try the line(s) below:

    \$ phpbrew use {$buildName}

Or you can use switch command to switch your default php to {$buildName}:

    \$ phpbrew switch {$buildName}

Enjoy!

EOT;
    }
Example #19
0
    public function execute()
    {
        // $currentVersion;
        $root = Config::getPhpbrewRoot();
        $home = Config::getPhpbrewHome();
        $buildDir = Config::getBuildDir();
        $buildPrefix = Config::getInstallPrefix();
        // $versionBuildPrefix = Config::getVersionInstallPrefix($version);
        // $versionBinPath     = Config::getVersionBinPath($version);
        if (!file_exists($root)) {
            mkdir($root, 0755, true);
        }
        $paths = array();
        $paths[] = $home;
        $paths[] = $root;
        $paths[] = $buildDir;
        $paths[] = $buildPrefix;
        foreach ($paths as $p) {
            $this->logger->info("Checking directory {$p}");
            if (!file_exists($p)) {
                $this->logger->info("Creating directory {$p}");
                mkdir($p, 0755, true);
            }
        }
        $this->logger->info('Creating .metadata_never_index to prevent SpotLight indexing');
        touch($root . DIRECTORY_SEPARATOR . '.metadata_never_index');
        // prevent spotlight index here
        touch($home . DIRECTORY_SEPARATOR . '.metadata_never_index');
        if ($configFile = $this->options->{'config'}) {
            if (!file_exists($configFile)) {
                return $this->logger->error("{$configFile} does not exist.");
            }
            $this->logger->debug("Using yaml config from {$configFile}");
            copy($configFile, $root . DIRECTORY_SEPARATOR . 'config.yaml');
        }
        $this->logger->writeln($this->formatter->format("Initialization successfully finished!", 'strong_green'));
        $this->logger->writeln($this->formatter->format("<=====================================================>", 'strong_white'));
        // write bashrc script to phpbrew home
        file_put_contents($home . '/bashrc', $this->getBashScript());
        // write phpbrew.fish script to phpbrew home
        file_put_contents($home . '/phpbrew.fish', $this->getFishScript());
        if (strpos(getenv("SHELL"), "fish") !== false) {
            $initConfig = <<<EOS
Paste the following line(s) to the end of your ~/.config/fish/config.fish and start a
new shell, phpbrew should be up and fully functional from there:

    source {$home}/phpbrew.fish
EOS;
        } else {
            $initConfig = <<<EOS
Paste the following line(s) to the end of your ~/.bashrc and start a
new shell, phpbrew should be up and fully functional from there:

    source {$home}/bashrc

To enable PHP version info in your shell prompt, please set PHPBREW_SET_PROMPT=1
in your `~/.bashrc` before you source `~/.phpbrew/bashrc`

    export PHPBREW_SET_PROMPT=1
EOS;
        }
        echo <<<EOS
Phpbrew environment is initialized, required directories are created under

    {$home}

{$initConfig}

For further instructions, simply run `phpbrew` to see the help message.

Enjoy phpbrew at \$HOME!!


EOS;
        $this->logger->writeln($this->formatter->format("<=====================================================>", 'strong_white'));
    }
Example #20
0
 public function configure(Build $build, $options)
 {
     $root = Config::getPhpbrewRoot();
     $buildDir = Config::getBuildDir();
     $variantBuilder = new VariantBuilder();
     $extra = $build->getExtraOptions();
     if (!file_exists('configure')) {
         $this->debug("configure file not found, running buildconf script...");
         system('./buildconf') !== false or die('buildconf error');
     }
     $prefix = $build->getInstallPrefix();
     // append cflags
     if ($this->optimizationLevel) {
         $o = $this->optimizationLevel;
         $cflags = getenv('CFLAGS');
         putenv("CFLAGS={$cflags} -O{$o}");
         $_ENV['CFLAGS'] = "{$cflags} -O{$o}";
     }
     $args = array();
     $args[] = "--prefix=" . $prefix;
     $args[] = "--with-config-file-path={$prefix}/etc";
     $args[] = "--with-config-file-scan-dir={$prefix}/var/db";
     $args[] = "--with-pear={$prefix}/lib/php";
     $variantOptions = $variantBuilder->build($build);
     if ($variantOptions) {
         $args = array_merge($args, $variantOptions);
     }
     $this->debug('Enabled variants: ' . join(', ', array_keys($build->getVariants())));
     $this->debug('Disabled variants: ' . join(', ', array_keys($build->getDisabledVariants())));
     foreach ((array) $options->patch as $patchPath) {
         // copy patch file to here
         $this->info("===> Applying patch file from {$patchPath} ...");
         // Search for strip parameter
         for ($i = 0; $i <= 16; $i++) {
             ob_start();
             system("patch -p{$i} --dry-run < {$patchPath}", $return);
             ob_clean();
             if ($return === 0) {
                 system("patch -p{$i} < {$patchPath}");
                 break;
             }
         }
     }
     // let's apply patch for libphp{php version}.so (apxs)
     if ($build->isEnabledVariant('apxs2')) {
         $apxs2Checker = new \PhpBrew\Tasks\Apxs2CheckTask($this->logger);
         $apxs2Checker->check($build, $options);
         $apxs2Patch = new \PhpBrew\Tasks\Apxs2PatchTask($this->logger);
         $apxs2Patch->patch($build, $options);
     }
     foreach ($extra as $a) {
         $args[] = $a;
     }
     $cmd = new CommandBuilder('./configure');
     $cmd->args($args);
     $this->info("===> Configuring {$build->version}...");
     $cmd->append = false;
     $cmd->stdout = Config::getVersionBuildLogPath($build->name);
     echo "\n\n";
     echo "Use tail command to see what's going on:\n";
     echo "   \$ tail -f {$cmd->stdout}\n\n\n";
     $this->debug($cmd->getCommand());
     if ($options->nice) {
         $cmd->nice($options->nice);
     }
     if (!$options->dryrun) {
         $cmd->execute() !== false or die('Configure failed.');
     }
     $patch64bit = new \PhpBrew\Tasks\Patch64BitSupportTask($this->logger, $options);
     $patch64bit->patch($build, $options);
 }
Example #21
0
    public function execute($version)
    {
        if (extension_loaded('posix') && posix_getuid() === 0) {
            $this->logger->warn("*WARNING* You're runing phpbrew as root/sudo. Unless you're going to install\nsystem-wide phpbrew or this might cause problems.");
            sleep(3);
        }
        $distUrl = null;
        $versionInfo = array();
        $releaseList = ReleaseList::getReadyInstance($this->options);
        $versionDslParser = new VersionDslParser();
        $clean = new MakeTask($this->logger, $this->options);
        $clean->setQuiet();
        if ($root = $this->options->root) {
            Config::setPhpbrewRoot($root);
        }
        if ($home = $this->options->home) {
            Config::setPhpbrewHome($home);
        }
        if ('latest' === strtolower($version)) {
            $version = $releaseList->getLatestVersion();
        }
        // this should point to master or the latest version branch yet to be released
        if ('next' === strtolower($version)) {
            $version = 'github.com/php/php-src:master';
        }
        if ($info = $versionDslParser->parse($version)) {
            $version = $info['version'];
            $distUrl = $info['url'];
            // always redownload when installing from github master
            // beware to keep this behavior after clean up the TODO below
            $this->options['force']->setValue(true);
        } else {
            // TODO ↓ clean later ↓ d.d.d versions should be part of the DSL too
            $version = preg_replace('/^php-/', '', $version);
            $versionInfo = $releaseList->getVersion($version);
            if (!$versionInfo) {
                throw new Exception("Version {$version} not found.");
            }
            $version = $versionInfo['version'];
            $distUrlPolicy = new DistributionUrlPolicy();
            if ($this->options->mirror) {
                $distUrlPolicy->setMirrorSite($this->options->mirror);
            }
            $distUrl = $distUrlPolicy->buildUrl($version, $versionInfo['filename'], $versionInfo['museum']);
        }
        // get options and variants for building php
        // and skip the first argument since it's the target version.
        $args = func_get_args();
        array_shift($args);
        // shift the version name
        $semanticOptions = $this->parseSemanticOptions($args);
        $buildAs = isset($semanticOptions['as']) ? $semanticOptions['as'] : $this->options->name;
        $buildLike = isset($semanticOptions['like']) ? $semanticOptions['like'] : $this->options->like;
        // convert patch to realpath
        if ($this->options->patch) {
            $patchPaths = array();
            foreach ($this->options->patch as $patch) {
                /* @var \SplFileInfo $patch */
                $patchPath = realpath($patch);
                if ($patchPath !== false) {
                    $patchPaths[(string) $patch] = $patchPath;
                }
            }
            // rewrite patch paths
            $this->options->keys['patch']->value = $patchPaths;
        }
        // Initialize the build object, contains the information to build php.
        $build = new Build($version, $buildAs);
        $installPrefix = Config::getInstallPrefix() . DIRECTORY_SEPARATOR . $build->getName();
        if (!file_exists($installPrefix)) {
            mkdir($installPrefix, 0755, true);
        }
        $build->setInstallPrefix($installPrefix);
        // find inherited variants
        if ($buildLike) {
            if ($parentBuild = Build::findByName($buildLike)) {
                $this->logger->info("===> Loading build settings from {$buildLike}");
                $build->loadVariantInfo($parentBuild->settings->toArray());
            }
        }
        $msg = "===> phpbrew will now build {$build->getVersion()}";
        if ($buildLike) {
            $msg .= ' using variants from ' . $buildLike;
        }
        if (isset($semanticOptions['using'])) {
            $msg .= ' plus custom variants: ' . implode(', ', $semanticOptions['using']);
            $args = array_merge($args, $semanticOptions['using']);
        }
        if ($buildAs) {
            $msg .= ' as ' . $buildAs;
        }
        $this->logger->info($msg);
        if (!empty($args)) {
            $this->logger->debug("---> Parsing variants from command arguments '" . implode(' ', $args) . "'");
        }
        // ['extra_options'] => the extra options to be passed to ./configure command
        // ['enabled_variants'] => enabeld variants
        // ['disabled_variants'] => disabled variants
        $variantInfo = VariantParser::parseCommandArguments($args);
        $build->loadVariantInfo($variantInfo);
        // load again
        // assume +default variant if no build config is given and warn about that
        if (!$variantInfo['enabled_variants']) {
            $build->setBuildSettings(new DefaultBuildSettings());
            $this->logger->notice("You haven't set any variant. A default set of extensions will be installed for the minimum requirement:");
            $this->logger->notice('[' . implode(', ', array_keys($build->getVariants())) . ']');
            $this->logger->notice("Please run 'phpbrew variants' for more information.\n");
        }
        if (preg_match('/5\\.3\\./', $version)) {
            $this->logger->notice('PHP 5.3 requires +intl, enabled by default.');
            $build->enableVariant('intl');
        }
        // always add +xml by default unless --without-pear is present
        // TODO: This can be done by "-pear"
        if (!in_array('--without-pear', $variantInfo['extra_options'])) {
            $build->enableVariant('xml');
        }
        $this->logger->info('===> Loading and resolving variants...');
        $removedVariants = $build->loadVariantInfo($variantInfo);
        if (!empty($removedVariants)) {
            $this->logger->debug('Removed variants: ' . implode(',', $removedVariants));
        }
        $prepareTask = new PrepareDirectoryTask($this->logger, $this->options);
        $prepareTask->run($build);
        // Move to to build directory, because we are going to download distribution.
        $buildDir = $this->options->{'build-dir'} ?: Config::getBuildDir();
        if (!file_exists($buildDir)) {
            mkdir($buildDir, 0755, true);
        }
        $variantBuilder = new VariantBuilder();
        $configureOptions = $variantBuilder->build($build);
        $distFileDir = Config::getDistFileDir();
        $downloadTask = new DownloadTask($this->logger, $this->options);
        $targetFilePath = $downloadTask->download($distUrl, $distFileDir, isset($versionInfo['md5']) ? $versionInfo['md5'] : null);
        if (!file_exists($targetFilePath)) {
            throw new SystemCommandException("Download failed, {$targetFilePath} does not exist.", $build);
        }
        unset($downloadTask);
        $extractTask = new ExtractTask($this->logger, $this->options);
        $targetDir = $extractTask->extract($build, $targetFilePath, $buildDir);
        if (!file_exists($targetDir)) {
            throw new SystemCommandException("Extract failed, {$targetDir} does not exist.", $build);
        }
        unset($extractTask);
        // Update build source directory
        $this->logger->debug('Source Directory: ' . realpath($targetDir));
        $build->setSourceDirectory($targetDir);
        if (!$this->options->{'no-clean'} && file_exists($targetDir . DIRECTORY_SEPARATOR . 'Makefile')) {
            $this->logger->info('Found existing Makefile, running make clean to ensure everything will be rebuilt.');
            $this->logger->info("You can append --no-clean option after the install command if you don't want to rebuild.");
            $clean->clean($build);
        }
        // Change directory to the downloaded source directory.
        chdir($targetDir);
        // Write variants info.
        $variantInfoFile = $build->getInstallPrefix() . DIRECTORY_SEPARATOR . 'phpbrew.variants';
        $this->logger->debug("Writing variant info to {$variantInfoFile}");
        if (false === $build->writeVariantInfoFile($variantInfoFile)) {
            $this->logger->warn("Can't store variant info.");
        }
        $buildLogFile = $build->getBuildLogPath();
        if (!$this->options->{'no-configure'}) {
            $configureTask = new BeforeConfigureTask($this->logger, $this->options);
            $configureTask->run($build);
            unset($configureTask);
            // trigger __destruct
            $configureTask = new ConfigureTask($this->logger, $this->options);
            $configureTask->run($build, $configureOptions);
            unset($configureTask);
            // trigger __destruct
            $configureTask = new AfterConfigureTask($this->logger, $this->options);
            $configureTask->run($build);
            unset($configureTask);
            // trigger __destruct
        }
        $buildTask = new BuildTask($this->logger, $this->options);
        $buildTask->run($build);
        unset($buildTask);
        // trigger __destruct
        if ($this->options->{'test'}) {
            $testTask = new TestTask($this->logger, $this->options);
            $testTask->run($build);
            unset($testTask);
            // trigger __destruct
        }
        if (!$this->options->{'no-install'}) {
            $installTask = new InstallTask($this->logger, $this->options);
            $installTask->install($build);
            unset($installTask);
            // trigger __destruct
        }
        if ($this->options->{'post-clean'}) {
            $clean->clean($build);
        }
        $dsym = new DSymTask($this->logger, $this->options);
        $dsym->patch($build, $this->options);
        // copy php-fpm config
        $this->logger->info('---> Creating php-fpm.conf');
        $etcDirectory = $build->getEtcDirectory();
        $fpmUnixSocket = $build->getInstallPrefix() . "/var/run/php-fpm.sock";
        $this->installAs("{$etcDirectory}/php-fpm.conf.default", "{$etcDirectory}/php-fpm.conf");
        $this->installAs("{$etcDirectory}/php-fpm.d/www.conf.default", "{$etcDirectory}/php-fpm.d/www.conf");
        $patchingFiles = array("{$etcDirectory}/php-fpm.d/www.conf", "{$etcDirectory}/php-fpm.conf");
        foreach ($patchingFiles as $patchingFile) {
            if (file_exists($patchingFile)) {
                $this->logger->info("---> Found {$patchingFile}");
                // Patch pool listen unix
                // The original config was below:
                //
                // listen = 127.0.0.1:9000
                //
                // See http://php.net/manual/en/install.fpm.configuration.php for more details
                $ini = file_get_contents($patchingFile);
                $this->logger->info("---> Patching default fpm pool listen path to {$fpmUnixSocket}");
                $ini = preg_replace('/^listen = .*$/m', "listen = {$fpmUnixSocket}\n", $ini);
                file_put_contents($patchingFile, $ini);
                break;
            }
        }
        $this->logger->info('---> Creating php.ini');
        $phpConfigPath = $build->getSourceDirectory() . DIRECTORY_SEPARATOR . ($this->options->production ? 'php.ini-production' : 'php.ini-development');
        $this->logger->info("---> Copying {$phpConfigPath} ");
        if (file_exists($phpConfigPath) && !$this->options->dryrun) {
            $targetConfigPath = $etcDirectory . DIRECTORY_SEPARATOR . 'php.ini';
            if (file_exists($targetConfigPath)) {
                $this->logger->notice("Found existing {$targetConfigPath}.");
            } else {
                // TODO: Move this to PhpConfigPatchTask
                // move config file to target location
                copy($phpConfigPath, $targetConfigPath);
            }
            if (!$this->options->{'no-patch'}) {
                $config = parse_ini_file($targetConfigPath, true);
                $configContent = file_get_contents($targetConfigPath);
                $patched = false;
                if (!isset($config['date']['timezone'])) {
                    $this->logger->info('---> Found date.timezone is not set, patching...');
                    // Replace current timezone
                    if ($timezone = ini_get('date.timezone')) {
                        $this->logger->info("---> Found date.timezone, patching config timezone with {$timezone}");
                        $configContent = preg_replace('/^;?date.timezone\\s*=\\s*.*/im', "date.timezone = {$timezone}", $configContent);
                    }
                    $patched = true;
                }
                if (!isset($config['phar']['readonly'])) {
                    $pharReadonly = ini_get('phar.readonly');
                    // 0 or "" means readonly is disabled manually
                    if (!$pharReadonly) {
                        $this->logger->info('---> Disabling phar.readonly option.');
                        $configContent = preg_replace('/^;?phar.readonly\\s*=\\s*.*/im', 'phar.readonly = 0', $configContent);
                    }
                }
                // turn off detect_encoding for 5.3
                if ($build->compareVersion('5.4') < 0) {
                    $this->logger->info("---> Turn off detect_encoding for php 5.3.*");
                    $configContent = $configContent . "\ndetect_unicode = Off\n";
                }
                file_put_contents($targetConfigPath, $configContent);
            }
        }
        if ($build->isEnabledVariant('pear')) {
            $this->logger->info('Initializing pear config...');
            $home = Config::getHome();
            @mkdir("{$home}/tmp/pear/temp", 0755, true);
            @mkdir("{$home}/tmp/pear/cache_dir", 0755, true);
            @mkdir("{$home}/tmp/pear/download_dir", 0755, true);
            system("pear config-set temp_dir {$home}/tmp/pear/temp");
            system("pear config-set cache_dir {$home}/tmp/pear/cache_dir");
            system("pear config-set download_dir {$home}/tmp/pear/download_dir");
            $this->logger->info('Enabling pear auto-discover...');
            system('pear config-set auto_discover 1');
        }
        $this->logger->debug('Source directory: ' . $targetDir);
        $buildName = $build->getName();
        $this->logger->info("Congratulations! Now you have PHP with {$version} as {$buildName}");
        if ($build->isEnabledVariant('pdo') && $build->isEnabledVariant('mysql')) {
            echo <<<EOT

* We found that you enabled 'mysql' variant, you might need to setup your
  'pdo_mysql.default_socket' or 'mysqli.default_socket' in your php.ini file.

EOT;
        }
        if (isset($targetConfigPath)) {
            echo <<<EOT

* To configure your installed PHP further, you can edit the config file at
    {$targetConfigPath}

EOT;
        }
        // If the bashrc file is not found, it means 'init' command didn't get
        // a chance to be executed.
        if (!file_exists(Config::getHome() . DIRECTORY_SEPARATOR . 'bashrc')) {
            echo <<<EOT

* WARNING:
  You haven't run 'phpbrew init' yet! Be sure to setup your phpbrew to use your own php(s)
  Please run 'phpbrew init' to setup your phpbrew in place.

EOT;
        }
        // If the environment variable is not defined, it means users didn't
        // setup ther .bashrc or .zshrc
        if (!getenv('PHPBREW_HOME')) {
            echo <<<EOT

* WARNING:
  You haven't setup your .bashrc file to load phpbrew shell script yet!
  Please run 'phpbrew init' to see the steps!

EOT;
        }
        echo <<<EOT

To use the newly built PHP, try the line(s) below:

    \$ phpbrew use {$buildName}

Or you can use switch command to switch your default php to {$buildName}:

    \$ phpbrew switch {$buildName}

Enjoy!

EOT;
    }
Example #22
0
 public static function findLatestPhpVersion($version = null)
 {
     $foundVersion = false;
     $buildDir = Config::getBuildDir();
     $hasPrefix = self::startsWith($version, 'php-');
     if (is_dir($buildDir)) {
         if ($hasPrefix == true) {
             $version = str_replace('php-', '', $version);
         }
         $fp = opendir($buildDir);
         if ($fp !== false) {
             while ($file = readdir($fp)) {
                 if ($file === '.' || $file === '..' || is_file($buildDir . DIRECTORY_SEPARATOR . $file)) {
                     continue;
                 }
                 $curVersion = strtolower(preg_replace('/^[\\D]*-/', '', $file));
                 if (self::startsWith($curVersion, $version) && version_compare($curVersion, $foundVersion, '>=')) {
                     $foundVersion = $curVersion;
                     if (version_compare($foundVersion, $version, '=')) {
                         break;
                     }
                 }
             }
             closedir($fp);
         }
         if ($hasPrefix == true && $foundVersion !== false) {
             $foundVersion = 'php-' . $foundVersion;
         }
     }
     return $foundVersion;
 }
Example #23
0
 public function execute($extName, $version = 'stable')
 {
     if (version_compare(PHP_VERSION, '7.0.0') > 0) {
         $this->logger->warn("Warning: Some extension won't be able to be built with php7. If the extension\nsupports php7 in another branch or new major version, you will need to specify\nthe branch name or version name explicitly.\n\nFor example, to install memcached extension for php7, use:\n\n    phpbrew ext install github:php-memcached-dev/php-memcached php7 -- --disable-memcached-sasl\n");
     }
     if (strtolower($extName) === 'apc' && version_compare(PHP_VERSION, '5.6.0') > 0) {
         $this->logger->warn('apc is not compatible with php 5.6+ versions, install apcu instead.');
     }
     // Detect protocol
     if ((preg_match('#^git://#', $extName) || preg_match('#\\.git$#', $extName)) && !preg_match('#github|bitbucket#', $extName)) {
         $pathinfo = pathinfo($extName);
         $repoUrl = $extName;
         $extName = $pathinfo['filename'];
         $extDir = Config::getBuildDir() . DIRECTORY_SEPARATOR . Config::getCurrentPhpName() . DIRECTORY_SEPARATOR . 'ext' . DIRECTORY_SEPARATOR . $extName;
         if (!file_exists($extDir)) {
             passthru("git clone {$repoUrl} {$extDir}", $ret);
             if ($ret != 0) {
                 return $this->logger->error('Clone failed.');
             }
         }
     }
     // Expand extensionset from config
     $extensions = array();
     if (Utils::startsWith($extName, '+')) {
         $config = Config::getConfigParam('extensions');
         $extName = ltrim($extName, '+');
         if (isset($config[$extName])) {
             foreach ($config[$extName] as $extensionName => $extOptions) {
                 $args = explode(' ', $extOptions);
                 $extensions[$extensionName] = $this->getExtConfig($args);
             }
         } else {
             $this->logger->info('Extension set name not found. Have you configured it at the config.yaml file?');
         }
     } else {
         $args = array_slice(func_get_args(), 1);
         $extensions[$extName] = $this->getExtConfig($args);
     }
     $extensionList = new ExtensionList($this->logger, $this->options);
     $manager = new ExtensionManager($this->logger);
     foreach ($extensions as $extensionName => $extConfig) {
         $provider = $extensionList->exists($extensionName);
         if (!$provider) {
             throw new Exception("Could not find provider for {$extensionName}.");
         }
         $extensionName = $provider->getPackageName();
         $ext = ExtensionFactory::lookupRecursive($extensionName);
         $always_redownload = $this->options->{'pecl'} || $this->options->{'redownload'} || !$provider->isBundled($extensionName);
         // Extension not found, use pecl to download it.
         if (!$ext || $always_redownload) {
             // not every project has stable branch, using master as default version
             $args = array_slice(func_get_args(), 1);
             if (!isset($args[0]) || $args[0] != $extConfig->version) {
                 $extConfig->version = $provider->getDefaultVersion();
             }
             $extensionDownloader = new ExtensionDownloader($this->logger, $this->options);
             $extensionDownloader->download($provider, $extConfig->version);
             // Reload the extension
             if ($provider->shouldLookupRecursive()) {
                 $ext = ExtensionFactory::lookupRecursive($extensionName);
             } else {
                 $ext = ExtensionFactory::lookup($extensionName);
             }
             if ($ext) {
                 $extensionDownloader->renameSourceDirectory($ext);
             }
         }
         if (!$ext) {
             throw new Exception("{$extensionName} not found.");
         }
         $manager->installExtension($ext, $extConfig->options);
     }
 }